Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions resources/plugins/types/orca-frame.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ declare module 'orca/frame' {
data: string | ArrayBuffer | ArrayBufferView
}
export type EditorDocumentApi = {
/** The latest document, with your accepted edits' content at the same version. */
get(): Promise<EditorDocument>
/** Replays the current document, then each one Orca sends when the file changes outside. */
onDidChange(handler: (document: EditorDocument) => void): Disposable
Expand Down
2 changes: 1 addition & 1 deletion skill-guides/orca-plugin-authoring/references/host-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Host API 1.2 (`"pluginApi": 1`). Call `host.call(method, params, { signal })`; a
- `shell.openExternal(url: string)`: `reason`: the person cancelled, or Orca's window was hidden so nobody could confirm.
- `files.saveAs(options: SaveAsOptions)`: Desktop isolated frames only; `cancelled` when the person closes the dialog.
- `document?: EditorDocumentApi`: Custom editors only.
- `document.get()`
- `document.get()`: The latest document, with your accepted edits' content at the same version.
- `document.onDidChange(handler: (document: EditorDocument) => void)`: Replays the current document, then each one Orca sends when the file changes outside.
- `document.applyEdit(edit: EditorEdit)`: Rejects with `conflict`, `too_large` or `not_permitted` (read-only).

Expand Down
2 changes: 1 addition & 1 deletion src/cli/bundled-skill-guides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2905,7 +2905,7 @@ const ORCA_PLUGIN_AUTHORING_HOST_API_REFERENCE_MARKDOWN = [
"- `shell.openExternal(url: string)`: `reason`: the person cancelled, or Orca's window was hidden so nobody could confirm.",
"- `files.saveAs(options: SaveAsOptions)`: Desktop isolated frames only; `cancelled` when the person closes the dialog.",
"- `document?: EditorDocumentApi`: Custom editors only.",
"- `document.get()`",
"- `document.get()`: The latest document, with your accepted edits' content at the same version.",
"- `document.onDidChange(handler: (document: EditorDocument) => void)`: Replays the current document, then each one Orca sends when the file changes outside.",
"- `document.applyEdit(edit: EditorEdit)`: Rejects with `conflict`, `too_large` or `not_permitted` (read-only).",
"",
Expand Down
94 changes: 94 additions & 0 deletions src/cli/plugin-authoring/plugin-editor-template.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// @vitest-environment happy-dom

import { describe, expect, it } from 'vitest'
import {
flush,
mountShell
} from '../../shared/plugins/frames/plugin-frame-shell-mount.test-fixture'
import { editor } from './plugin-frame-templates'

const doc = (version: number, text: string) => ({
orca: 1,
kind: 'evt',
event: 'editor.document',
payload: { version, readOnly: false, content: { kind: 'text', text } }
})

function mountEditorTemplate() {
const html = editor({ id: 'notes', name: 'Notes' }).files['editor/index.html']
document.body.innerHTML = html.match(/<body>([\s\S]*?)<script>/)?.[1] ?? ''
const shell = mountShell('editor')
// A block scopes the template's top-level consts to this mount.
window.eval(`{${html.match(/<script>([\s\S]*?)<\/script>/)?.[1] ?? ''}}`)
const textarea = document.querySelector('textarea')!
const notice = document.getElementById('notice')!
const type = (value: string) => {
textarea.value = value
textarea.dispatchEvent(new Event('input'))
}
return { ...shell, textarea, notice, type }
}

describe('editor template', () => {
it('keeps typing Orca has not accepted when the file changes outside', async () => {
const { fromHost, textarea, type } = mountEditorTemplate()
fromHost(doc(1, 'start'))
await flush()
expect(textarea.value).toBe('start')
type('start typed')
fromHost(doc(2, 'outside'))
expect(textarea.value).toBe('start typed')
})

it('follows outside changes once its edits are accepted', async () => {
const { fromHost, textarea, type } = mountEditorTemplate()
fromHost(doc(1, 'start'))
await flush()
type('mine')
fromHost({ orca: 1, kind: 'res', id: 0, result: null })
await flush()
fromHost(doc(2, 'outside'))
expect(textarea.value).toBe('outside')
})

it('shows a refused edit and clears it once an edit is accepted', async () => {
const { fromHost, notice, posted, type } = mountEditorTemplate()
fromHost(doc(1, 'start'))
await flush()
type('mine')
fromHost({
orca: 1,
kind: 'res',
id: 0,
error: { code: 'conflict', message: 'The file changed outside this editor.' }
})
await flush()
expect(notice.textContent).toBe('Not saved: The file changed outside this editor.')
fromHost(doc(2, 'outside'))
type('mine again')
expect(posted().at(-1)).toMatchObject({ params: { baseVersion: 2 } })
fromHost({ orca: 1, kind: 'res', id: 1, result: null })
await flush()
expect(notice.textContent).toBe('')
})

it('lets only the newest input settle dirty and the notice', async () => {
const { fromHost, textarea, notice, type } = mountEditorTemplate()
fromHost(doc(1, 'start'))
await flush()
type('A')
type('AB')
type('A')
fromHost({ orca: 1, kind: 'res', id: 0, result: null })
await flush()
// The final `A` is still unanswered, so an outside change must not replace it.
fromHost(doc(2, 'outside'))
expect(textarea.value).toBe('A')
fromHost({ orca: 1, kind: 'res', id: 2, error: { code: 'conflict', message: 'Changed.' } })
await flush()
// An older success arriving after a newer refusal keeps the notice.
fromHost({ orca: 1, kind: 'res', id: 1, result: null })
await flush()
expect(notice.textContent).toBe('Not saved: Changed.')
})
})
31 changes: 27 additions & 4 deletions src/cli/plugin-authoring/plugin-frame-templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,31 +44,54 @@ export function editor(input: PluginTemplateInput): PluginTemplate {
textarea {
box-sizing: border-box;
width: 100%;
height: calc(100vh - 24px);
height: calc(100vh - 48px);
color: inherit;
background: transparent;
border: 1px solid var(--orca-border);
font: 13px ui-monospace, monospace;
}
#notice {
margin: 4px 0 0;
min-height: 16px;
color: var(--orca-destructive);
}
</style>
</head>
<body>
<textarea id="text" spellcheck="false"></textarea>
<p id="notice" role="status"></p>
<script>
const text = document.getElementById('text')
const notice = document.getElementById('notice')
let version = 0
// True while the textarea holds typing Orca has not accepted yet.
let dirty = false
// Only the newest input's answer settles dirty and the notice; older ones are stale.
let generation = 0
// Orca sends the document now and again whenever the file changes outside the editor.
orca.document.onDidChange((doc) => {
version = doc.version
text.readOnly = doc.readOnly
if (doc.content.kind === 'text' && text.value !== doc.content.text) {
if (!dirty && doc.content.kind === 'text' && text.value !== doc.content.text) {
text.value = doc.content.text
}
})
text.addEventListener('input', () => {
void orca.document
dirty = true
const current = ++generation
orca.document
.applyEdit({ baseVersion: version, content: { kind: 'text', text: text.value } })
.catch((error) => console.warn(error.code, error.message))
.then(
() => {
if (current !== generation) return
dirty = false
notice.textContent = ''
},
(error) => {
// Your text stays; the next keystroke edits the latest document.
if (current === generation) notice.textContent = 'Not saved: ' + error.message
}
)
})
</script>
</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ function harness(
return { host, posted, send, messages, documents, answers, answerFlushes }
}

function setup(initial: { text: string; readOnly?: boolean; maxEdits?: number }) {
function setup(initial: {
text: string
readOnly?: boolean
maxEdits?: number
now?: () => number
}) {
const doc = { text: initial.text, readOnly: initial.readOnly ?? false }
const onEdit = vi.fn((text: string) => {
doc.text = text
Expand All @@ -88,6 +93,7 @@ function setup(initial: { text: string; readOnly?: boolean; maxEdits?: number })
onUnappliedEdit,
onKeyChord,
flushTimeoutMs: 50,
...(initial.now ? { now: initial.now } : {}),
...(initial.maxEdits === undefined
? {}
: {
Expand Down Expand Up @@ -364,17 +370,57 @@ describe('custom editor document channel', () => {
send(edit('d', 1, 15))
expect(onEdit).toHaveBeenCalledTimes(1)
expect(onUnappliedEdit).toHaveBeenLastCalledWith('held')
// `c` is superseded by the full-document `d`, so it succeeded.
expect(answers(14)).toEqual([{ orca: 1, kind: 'res', id: 14, result: null }])
// `c` is superseded by the full-document `d`, so it gets `d`'s answer once `d` commits.
expect(answers(14)).toEqual([])
expect(answers(15)).toEqual([])
const flushed = host.flush()
answerFlushes()
await expect(flushed).resolves.toBe(true)
expect(onEdit).toHaveBeenLastCalledWith('d')
expect(answers(14)).toEqual([{ orca: 1, kind: 'res', id: 14, result: null }])
expect(answers(15)).toEqual([{ orca: 1, kind: 'res', id: 15, result: null }])
expect(onUnappliedEdit).toHaveBeenLastCalledWith(null)
})

it('gives a superseded held edit the refusal of the edit that replaced it', async () => {
const { host, doc, send, answers, answerFlushes } = setup({ text: 'a', maxEdits: 1 })
send(READY)
send(edit('b', 1, 16))
send(edit('c', 1, 17))
doc.text = 'outside'
host.syncDocument()
send(edit('d', 1, 18))
const flushed = host.flush()
answerFlushes()
await flushed
expect(answers(17)).toMatchObject([{ error: { code: 'conflict' } }])
expect(answers(18)).toMatchObject([{ error: { code: 'conflict' } }])
})

it('keeps a held edit when an oversized one follows, and the save stays blocked', async () => {
let clock = 0
const { host, onEdit, send, answers, answerFlushes } = setup({
text: 'a',
maxEdits: 1,
now: () => clock
})
send(READY)
send(edit('b', 1, 19))
send(edit('c', 1, 20))
// A new rate window, so the next edit is refused for its size alone.
clock = 60_000
send(edit('x'.repeat(CUSTOM_EDITOR_DOCUMENT_MAX_BYTES + 1), 1, 21))
// `c` is not answered as a success before it reaches the buffer.
expect(answers(20)).toEqual([])
expect(answers(21)).toMatchObject([{ error: { code: 'too_large' } }])
const flushed = host.flush()
answerFlushes()
expect(onEdit).toHaveBeenLastCalledWith('c')
expect(answers(20)).toEqual([{ orca: 1, kind: 'res', id: 20, result: null }])
// The frame's newest change was lost, so a save must not mark the tab clean.
await expect(flushed).resolves.toBe(false)
})

it('never spends the edit budget on chords or flush replies', () => {
const { onEdit, send } = setup({ text: 'a', maxEdits: 1 })
send(READY)
Expand Down
24 changes: 19 additions & 5 deletions src/renderer/src/components/editor/plugin-custom-editor-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,12 @@ export function createCustomEditorHost(options: CustomEditorHostOptions): Custom
// The newest edit refused for the rate limit, unparsed until applied; full-text, so it wins.
let heldEdit: unknown = null
let heldId: number | null = null
// Held edits a newer one replaced; they get that edit's answer, so success means committed.
let supersededIds: (number | null)[] = []
let heldTimer: ReturnType<typeof setTimeout> | null = null
let lostEdit = false
// An oversized edit came after the held one, so applying the held one leaves it still lost.
let lostAfterHeld = false
let unapplied: CustomEditorUnappliedEdit = null

const reportUnapplied = (): void => {
Expand Down Expand Up @@ -198,8 +202,11 @@ export function createCustomEditorHost(options: CustomEditorHostOptions): Custom
const receiveEdit = (data: unknown): void => {
const message = readPluginEnvelope(data)
const edit = message?.kind === 'req' ? readCustomEditorEdit(message.params) : null
const id = pluginRequestId(data)
answer(id, edit ? applyEdit(edit) : pluginError('invalid_params', 'malformed editor edit'))
const error = edit ? applyEdit(edit) : pluginError('invalid_params', 'malformed editor edit')
answer(pluginRequestId(data), error)
for (const id of supersededIds.splice(0)) {
answer(id, error)
Comment on lines +206 to +208

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Supported by static analysis

Script executed:

sed -n '95,115p;195,250p' src/renderer/src/components/editor/plugin-custom-editor-host.ts
sed -n '215,260p' src/shared/plugins/frames/plugin-panel-shell.ts

Repository: stablyai/orca

Length of output: 5228


Script executed:

set -o pipefail
printf '%s\n' '--- host definitions and callers ---'
rg -n -F --glob '*.ts' -e 'const receiveEdit' -e 'function receiveEdit' -e 'function answer' -e 'const answer' -e 'version++' -e 'editorDocument' -e 'document.update' -e 'commit' -- src/renderer/src/components/editor/plugin-custom-editor-host.ts src/shared/plugins/frames src/renderer/src/components/editor || test "$?" -eq 1
sed -n '1,280p' src/renderer/src/components/editor/plugin-custom-editor-host.ts
printf '%s\n' '--- frame shell message handling ---'
rg -n -F --glob '*.ts' -e 'pending' -e 'applyEdit' -e 'editorDocument' -e 'editorDocumentChanged' -e 'latest' -e 'response' -- src/shared/plugins/frames/plugin-panel-shell.ts src/shared/plugins/frames src/shared/plugins || test "$?" -eq 1
sed -n '1,280p' src/shared/plugins/frames/plugin-panel-shell.ts

Repository: stablyai/orca

Length of output: 41823


Script executed:

set -o pipefail
printf '%s\n' '--- host state and edit flow ---'
nl -ba src/renderer/src/components/editor/plugin-custom-editor-host.ts | sed -n '110,225p'
printf '%s\n' '--- host callers / document pushes ---'
rg -n -F --glob '*.ts' -e 'post(pluginEvent(FRAME_EVENTS.editorDocument' -e 'version +=' -e 'version++' -e 'receiveEdit(' -e 'applyHeldEdit(' -e 'supersedeHeldEdit(' -- src/renderer/src/components/editor/plugin-custom-editor-host.ts
printf '%s\n' '--- frame receive and editor facade ---'
nl -ba src/shared/plugins/frames/plugin-panel-shell.ts | sed -n '130,185p;218,245p'

Repository: stablyai/orca

Length of output: 9919


Script executed:

set -o pipefail
printf '%s\n' '--- host factory and callers ---'
rg -n -F --glob '*.ts' -e 'createPluginCustomEditorHost' -e 'plugin-custom-editor-host' -e 'onEdit:' -e 'onBytesEdit:' -- src/renderer src/main src/shared || test "$?" -eq 1
printf '%s\n' '--- full host tail and relevant caller blocks ---'
nl -ba src/renderer/src/components/editor/plugin-custom-editor-host.ts | sed -n '225,360p'

Repository: stablyai/orca

Length of output: 5295


Answer superseded edits before the replacement edit.

When held edit c is replaced by d, receiveEdit answers d before c. The frame applies both successful responses because their base versions match. The cache can therefore end with c, while the host has applied d. The accepted-edit path does not bump the version or post a correcting document update.

Suggested fix
--- "a/src/renderer/src/components/editor/plugin-custom-editor-host.ts"
+++ "b/src/renderer/src/components/editor/plugin-custom-editor-host.ts"
@@ -203,10 +203,10 @@
     const message = readPluginEnvelope(data)
     const edit = message?.kind === 'req' ? readCustomEditorEdit(message.params) : null
     const error = edit ? applyEdit(edit) : pluginError('invalid_params', 'malformed editor edit')
-    answer(pluginRequestId(data), error)
     for (const id of supersededIds.splice(0)) {
       answer(id, error)
     }
+    answer(pluginRequestId(data), error)
   }
 
   const applyHeldEdit = (): void => {

}
}

const applyHeldEdit = (): void => {
Expand All @@ -208,25 +215,32 @@ export function createCustomEditorHost(options: CustomEditorHostOptions): Custom
heldTimer = null
}
const held = heldEdit
const stillLost = lostAfterHeld
heldEdit = null
heldId = null
lostAfterHeld = false
if (held !== null) {
receiveEdit(held)
lostEdit ||= stillLost
}
reportUnapplied()
}

/** A newer full-document edit carries the held one's intent, so the held one succeeds. */
/** A newer full-document edit carries the held one's intent, so it shares that edit's answer. */
const supersedeHeldEdit = (): void => {
answer(heldId, null)
if (heldEdit !== null) {
supersededIds.push(heldId)
}
lostAfterHeld = false
heldEdit = null
heldId = null
}

const refuseEdit = (data: unknown, refusal: CustomEditorEditRefusal): void => {
options.onEditRefused?.(refusal)
if (refusal === 'oversized') {
supersedeHeldEdit()
// The held edit stays: an edit Orca refuses carries nothing to replace it with.
lostAfterHeld ||= heldEdit !== null
lostEdit = true
answer(pluginRequestId(data), CUSTOM_EDITOR_TOO_LARGE)
} else {
Expand Down
60 changes: 2 additions & 58 deletions src/shared/plugins/frames/plugin-frame-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,64 +3,8 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildPluginGuestShellHtml,
buildPluginPanelShellHtml,
type PluginFrameSurface
} from './plugin-panel-shell'

/** The injected `window.orca` is the public frame API; the envelope under it stays internal. */

type FrameOrca = {
api: { major: number; minor: number }
host: {
call: (method: string, params?: unknown, options?: { signal?: AbortSignal }) => Promise<unknown>
has: (method: string) => boolean
}
on: (event: string, handler: (payload: unknown) => unknown) => { dispose: () => void }
locale: string
plugin: object
storage: object
shell?: { openExternal: (url: string) => Promise<unknown> }
files?: {
saveAs: (options: {
suggestedName?: string
mimeType?: string
data: unknown
}) => Promise<unknown>
}
document?: {
get: () => Promise<unknown>
onDidChange: (handler: (document: unknown) => void) => { dispose: () => void }
applyEdit: (edit: unknown) => Promise<unknown>
}
}

const realParent = window.parent

afterEach(() => {
Object.defineProperty(window, 'parent', { value: realParent, configurable: true })
})

function mountShell(surface: PluginFrameSurface = 'panel') {
const parent = { postMessage: vi.fn() }
Object.defineProperty(window, 'parent', { value: parent, configurable: true })
const script = buildPluginPanelShellHtml('<main></main>', surface).match(
/<script>\n([\s\S]*?)<\/script>/
)?.[1]
// Configurable only so happy-dom can tear down; the frame's copy stays locked.
window.eval(script!.replaceAll('configurable: false', 'configurable: true'))
const orca: FrameOrca = Object.getOwnPropertyDescriptor(window, 'orca')?.value
const fromHost = (data: unknown, source: unknown = parent) =>
window.dispatchEvent(
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the shim only compares source identity.
new MessageEvent('message', { data, source: source as Window })
)
const posted = () => parent.postMessage.mock.calls.map(([message]) => message)
return { orca, parent, fromHost, posted }
}

const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
import { buildPluginGuestShellHtml, type PluginFrameSurface } from './plugin-panel-shell'
import { flush, mountShell, type FrameOrca } from './plugin-frame-shell-mount.test-fixture'

describe('window.orca', () => {
it('times out a call the host never answers, and bounds calls in flight', async () => {
Expand Down
Loading
Loading