@acryldev/agent-panel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/client/describe.ts +101 -0
  3. package/client/driver-pick.ts +22 -0
  4. package/client/frame.ts +51 -0
  5. package/client/main.ts +707 -0
  6. package/client/markdown.ts +219 -0
  7. package/headless.ts +220 -0
  8. package/index.ts +523 -0
  9. package/launch.ts +67 -0
  10. package/lib/client/describe.ts +101 -0
  11. package/lib/client/driver-pick.ts +22 -0
  12. package/lib/client/frame.ts +51 -0
  13. package/lib/client/main.ts +707 -0
  14. package/lib/client/markdown.ts +219 -0
  15. package/lib/headless-B_RGxZFU.js +252 -0
  16. package/lib/headless-B_RGxZFU.js.map +1 -0
  17. package/lib/headless.js +2 -0
  18. package/lib/index.js +562 -0
  19. package/lib/index.js.map +1 -0
  20. package/lib/mount.js +25 -0
  21. package/lib/mount.js.map +1 -0
  22. package/lib/registry.js +13 -0
  23. package/lib/registry.js.map +1 -0
  24. package/lib/types/headless.d.ts +22 -0
  25. package/lib/types/index.d.ts +22 -0
  26. package/lib/types/launch.d.ts +18 -0
  27. package/lib/types/mount.d.ts +12 -0
  28. package/lib/types/registry.d.ts +10 -0
  29. package/lib/types/tsdown.config.d.ts +2 -0
  30. package/lib/types/visitors.d.ts +82 -0
  31. package/mount.ts +27 -0
  32. package/package.json +62 -3
  33. package/plugin.json +28 -0
  34. package/registry.ts +17 -0
  35. package/scripts/copy-assets.mjs +5 -0
  36. package/test/client-guards.test.ts +13 -0
  37. package/test/describe.test.ts +105 -0
  38. package/test/driver-pick.test.ts +24 -0
  39. package/test/frame.test.ts +35 -0
  40. package/test/launch.test.ts +90 -0
  41. package/test/markdown.test.ts +79 -0
  42. package/test/panel-client.test.ts +150 -0
  43. package/test/panel.test.ts +534 -0
  44. package/test/socket.test.ts +209 -0
  45. package/test/visitors.test.ts +112 -0
  46. package/test/why.test.ts +61 -0
  47. package/tsconfig.json +21 -0
  48. package/tsdown.config.ts +23 -0
  49. package/visitors.ts +231 -0
  50. package/README.md +0 -3
@@ -0,0 +1,707 @@
1
+ // The panel in the page: a button at the corner opens a side panel (a shadow root, so the app's CSS cannot touch it and it cannot touch the app's). It asks the app's
2
+ // agent through POST <prefix>/ask, shows the answer as it arrives, and reloads the page after a run that installed or removed a plugin. `panel.js` calls
3
+ // `start` with the prefix the app is served under (the root of its own server, or `/app` when the ACRYL frame hosts it).
4
+ import { describePageStep, describeTool } from './describe.ts'
5
+ import { createPickGeneration } from './driver-pick.ts'
6
+ import { FRAME_MODE_EVENT, frameViewOf, panelVariant, panelVisible } from './frame.ts'
7
+ import { renderMarkdown } from './markdown.ts'
8
+
9
+ let PREFIX = '/api/agent-panel'
10
+ /** Where the composer's draft is kept across a page reload or a remount. */
11
+ const DRAFT_KEY = 'agent-panel-draft'
12
+ /** Set when a visitor closed the Assistant, so it stays closed on the next page. */
13
+ const ASSISTANT_CLOSED_KEY = 'agent-panel-assistant-closed'
14
+ /** What the Assistant tells a visitor first: what it can do, and that it cannot change the app. */
15
+ export const ASSISTANT_NOTE =
16
+ 'The assistant can use the app for you: open pages, filter, fill in forms. It cannot change the app.'
17
+
18
+ /**
19
+ * Why a submit does not send: nothing typed, or a run still going. The panel says it in its log instead of returning silently - a Send that does nothing and
20
+ * says nothing reads as a broken button, and one was observed doing exactly that in the frame gate (empty log, enabled Send, no run).
21
+ */
22
+ export type SendRefusal = 'empty' | 'busy'
23
+ export function sendRefusal(message: string, following: boolean): SendRefusal | undefined {
24
+ if (message.trim() === '') return 'empty'
25
+ if (following) return 'busy'
26
+ return undefined
27
+ }
28
+
29
+ /**
30
+ * Whether the page may be replaced to show a change a run made. Asked at the moment of reloading, not earlier: text in the composer or the focus in it
31
+ * belongs to the person, and a run still going must not lose its page either.
32
+ */
33
+ export function reloadDecision(state: {
34
+ readonly value: string
35
+ readonly focused: boolean
36
+ readonly following: boolean
37
+ }): boolean {
38
+ return state.value.trim() === '' && !state.focused && !state.following
39
+ }
40
+
41
+ /** Where the last panel-initiated reload is recorded, for the page after it and for a gate looking at a failure. */
42
+ export const RELOAD_MARKER = 'agent-panel-reload'
43
+
44
+ /** Replace the page, saying why first: a warning the page's own error report and the frame gate both see, and a marker the reloaded page keeps. */
45
+ function reloadPage(reason: string): void {
46
+ try {
47
+ sessionStorage.setItem(RELOAD_MARKER, JSON.stringify({ reason, at: Date.now() }))
48
+ } catch {
49
+ // No storage: the warning below still names it.
50
+ }
51
+ console.warn(`agent-panel: reloading the page (${reason})`)
52
+ location.reload()
53
+ }
54
+
55
+ interface Session {
56
+ token: string
57
+ /** The production Assistant: the app's own agent drives the page for a visitor. */
58
+ assistant?: boolean
59
+ /** The app's production environment names the Assistant (ACRYL_ASSISTANT=on); the frame's Preview shows it even though the frame host runs in development. */
60
+ assistantInProduction?: boolean
61
+ drivers: Array<{
62
+ name: string
63
+ kind: 'chat' | 'terminal'
64
+ /** A terminal driver says where its view module is and which prefix its endpoints live under (the driver's own plugin serves both). */
65
+ view?: { module: string; prefix: string }
66
+ }>
67
+ }
68
+ interface PanelEvent {
69
+ event: string
70
+ data: Record<string, unknown>
71
+ }
72
+
73
+ /** The events of a server-sent stream, as they arrive. */
74
+ async function* events(response: Response): AsyncGenerator<PanelEvent> {
75
+ const reader = response.body!.getReader()
76
+ const decoder = new TextDecoder()
77
+ let buffer = ''
78
+ for (;;) {
79
+ const { value, done } = await reader.read()
80
+ if (done) return
81
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/gu, '\n')
82
+ for (let end = buffer.indexOf('\n\n'); end !== -1; end = buffer.indexOf('\n\n')) {
83
+ const block = buffer.slice(0, end)
84
+ buffer = buffer.slice(end + 2)
85
+ let event = 'message'
86
+ let data = ''
87
+ for (const line of block.split('\n')) {
88
+ if (line.startsWith('event:')) event = line.slice(6).trim()
89
+ else if (line.startsWith('data:')) data += line.slice(5).trim()
90
+ }
91
+ if (data !== '') yield { event, data: JSON.parse(data) as Record<string, unknown> }
92
+ }
93
+ }
94
+ }
95
+
96
+ /** What a run is read from: its events, and a way to end the run. A socket and a stream give the same events. */
97
+ interface RunSource {
98
+ readonly events: AsyncIterable<PanelEvent>
99
+ }
100
+
101
+ /** The door's id for this page, when the door is in it: sent with a question so the agent's calls (which name no window) drive this page and not another open one. */
102
+ function doorPage(): { page?: string } {
103
+ const published = (window as unknown as Record<symbol, { windowId?: unknown } | undefined>)[
104
+ Symbol.for('acryl.door.page')
105
+ ]
106
+ return typeof published?.windowId === 'string' ? { page: published.windowId } : {}
107
+ }
108
+
109
+ /** A WebSocket is not one of the browser's six connections per host, so the panel's Stop and a run still work when two windows stream their own state. */
110
+ let socketBroken = false
111
+ let activeSocket: WebSocket | undefined
112
+
113
+ /** The server did not accept the token: it is not the one this page was given (the app restarted since, which `node --watch` does at every change of a file). */
114
+ class Refused extends Error {}
115
+
116
+ /**
117
+ * Open the run socket and send the token and the first action. Resolves once the server has accepted the token (its `accepted` frame), with the socket and its events: the
118
+ * frames of the run as panel events, until the socket closes. One set of handlers serves the socket for its whole life, so a frame is never handed to a handler that was
119
+ * replaced. Rejects with `Refused` when the token is not accepted, and with another error when the page cannot upgrade (a proxy, a server without `ws`): the caller falls back
120
+ * to the stream.
121
+ */
122
+ function openSocket(
123
+ token: string,
124
+ action: Record<string, unknown>,
125
+ ): Promise<{ socket: WebSocket; events: AsyncGenerator<PanelEvent> }> {
126
+ return new Promise((resolve, reject) => {
127
+ const socket = new WebSocket(
128
+ `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}${PREFIX}/run/ws`,
129
+ )
130
+ const queue: PanelEvent[] = []
131
+ let wake: (() => void) | undefined
132
+ let closed = false
133
+ let accepted = false
134
+ const timer = setTimeout(() => {
135
+ socket.close()
136
+ reject(new Error('the socket was not accepted in time'))
137
+ }, 4000)
138
+ socket.onopen = () => {
139
+ socket.send(JSON.stringify({ t: 'hello', token }))
140
+ socket.send(JSON.stringify(action))
141
+ }
142
+ socket.onmessage = (message) => {
143
+ try {
144
+ const frame = JSON.parse(String(message.data)) as { e?: unknown; d?: unknown }
145
+ if (frame.e === 'accepted' && !accepted) {
146
+ accepted = true
147
+ clearTimeout(timer)
148
+ resolve({ socket, events: read() })
149
+ } else if (typeof frame.e === 'string')
150
+ queue.push({ event: frame.e, data: (frame.d ?? {}) as Record<string, unknown> })
151
+ } catch {
152
+ // Not a frame of ours.
153
+ }
154
+ wake?.()
155
+ }
156
+ socket.onclose = (event) => {
157
+ clearTimeout(timer)
158
+ closed = true
159
+ if (!accepted)
160
+ reject(
161
+ event.code === 4401
162
+ ? new Refused('the token was not accepted')
163
+ : new Error('the socket closed before it was accepted'),
164
+ )
165
+ wake?.()
166
+ }
167
+ socket.onerror = () => {
168
+ clearTimeout(timer)
169
+ if (!accepted) reject(new Error('the server refused the upgrade'))
170
+ }
171
+ async function* read(): AsyncGenerator<PanelEvent> {
172
+ for (;;) {
173
+ const next = queue.shift()
174
+ if (next !== undefined) {
175
+ yield next
176
+ continue
177
+ }
178
+ if (closed) return
179
+ await new Promise<void>((done) => {
180
+ wake = done
181
+ })
182
+ }
183
+ }
184
+ })
185
+ }
186
+
187
+ const css = `
188
+ :host { all: initial }
189
+ * { box-sizing: border-box; font: 14px system-ui, sans-serif }
190
+ button.open { position: fixed; right: 16px; bottom: 16px; z-index: 2147483000; border: 0; border-radius: 24px; padding: 10px 16px; background: #1f2937; color: #fff; cursor: pointer; box-shadow: 0 2px 8px #0004 }
191
+ section { position: fixed; top: 0; right: 0; bottom: 0; width: min(380px, 100vw); z-index: 2147483001; display: none; flex-direction: column; background: #fff; color: #111827; border-left: 1px solid #d1d5db; box-shadow: -2px 0 12px #0003 }
192
+ section.shown { display: flex }
193
+ header { display: flex; gap: 8px; align-items: center; padding: 8px 12px; border-bottom: 1px solid #e5e7eb }
194
+ header strong { flex: 1 }
195
+ #term { flex: 1; min-height: 0; background: #000 }
196
+ #term[hidden], form[hidden], #log[hidden] { display: none }
197
+ #log { flex: 1; overflow: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px }
198
+ .msg { white-space: pre-wrap; padding: 8px 10px; border-radius: 8px; background: #f3f4f6 }
199
+ .me { background: #dbeafe; align-self: flex-end }
200
+ .tool { font: 12px ui-monospace, monospace; color: #4b5563; background: none; padding: 0 }
201
+ .err { background: #fee2e2 }
202
+ .msg.md { white-space: normal; overflow-wrap: anywhere }
203
+ .md > :first-child { margin-top: 0 } .md > :last-child { margin-bottom: 0 }
204
+ .md p, .md ul, .md ol, .md pre, .md blockquote { margin: 0 0 8px }
205
+ .md h3, .md h4, .md h5, .md h6 { margin: 10px 0 4px; font-weight: 600 } .md h3 { font-size: 16px } .md h4, .md h5, .md h6 { font-size: 14px }
206
+ .md ul, .md ol { padding-left: 20px } .md li { margin: 2px 0 }
207
+ .md code { font: 12px ui-monospace, monospace; background: #e5e7eb; padding: 1px 4px; border-radius: 4px }
208
+ .md pre { overflow: auto; background: #111827; color: #f9fafb; padding: 8px 10px; border-radius: 6px }
209
+ .md pre code { background: none; padding: 0; color: inherit; white-space: pre }
210
+ .md blockquote { border-left: 3px solid #d1d5db; padding-left: 10px; color: #4b5563 }
211
+ .md a { color: #1d4ed8 }
212
+ .working { font: 12px ui-monospace, monospace; color: #6b7280; padding: 0 }
213
+ form { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; border-top: 1px solid #e5e7eb }
214
+ textarea { width: 100%; min-height: 64px; resize: vertical; padding: 8px; border: 1px solid #d1d5db; border-radius: 6px }
215
+ .row { display: flex; gap: 8px; align-items: center }
216
+ .row button, header button { padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: #fff; cursor: pointer }
217
+ .row button.send { background: #1f2937; color: #fff; border-color: #1f2937 }
218
+ .row button:disabled { opacity: 0.45; cursor: not-allowed }
219
+ .notice, .steps, .tab { display: none }
220
+ /* The Assistant (production): docked on the right in the app's dark surface, one tab, a note, the conversation and one line to ask. */
221
+ :host([data-assistant]) section { width: min(330px, 100vw); background: #18181b; color: #e4e4e7; border-left: 1px solid #27272a; box-shadow: none }
222
+ :host([data-assistant]) header { padding: 0 12px; border-bottom: 1px solid #27272a; min-height: 38px }
223
+ :host([data-assistant]) header select, :host([data-assistant]) header strong { display: none }
224
+ :host([data-assistant]) .tab { display: block; flex: 1; align-self: stretch }
225
+ :host([data-assistant]) .tab span { display: inline-block; height: 100%; padding: 10px 6px 8px; font-size: 12.5px; font-weight: 600; color: #fafafa; border-bottom: 2px solid #5468ff }
226
+ :host([data-assistant]) header button.close { border: 0; background: none; color: #a1a1aa; font-size: 18px; padding: 2px 6px }
227
+ :host([data-assistant]) .notice { display: block; margin: 8px 10px 0; padding: 7px 9px; border-radius: 6px; background: #15291e; color: #a7f3c0; font-size: 12px; line-height: 1.5 }
228
+ :host([data-assistant]) #log { padding: 10px; gap: 10px }
229
+ :host([data-assistant]) .msg { background: #232326; color: #e4e4e7; border-radius: 8px; padding: 9px 11px; line-height: 1.45; max-width: 92% }
230
+ :host([data-assistant]) .me { background: #23264f; color: #eef0ff; align-self: flex-end }
231
+ :host([data-assistant]) .err { background: #3b1d1d; color: #fecaca }
232
+ :host([data-assistant]) .tool, :host([data-assistant]) .working { background: none; color: #a1a1aa; padding: 0 2px }
233
+ :host([data-assistant]) .steps { display: block; margin-top: 6px; font: 11.5px ui-monospace, monospace; color: #a1a1aa; white-space: normal }
234
+ :host([data-assistant]) .steps:empty { display: none }
235
+ :host([data-assistant]) .md code { background: #2e2e33; color: #e4e4e7 }
236
+ :host([data-assistant]) form { border-top: 0; padding: 10px }
237
+ :host([data-assistant]) textarea { min-height: 0; height: 38px; resize: none; background: #18181b; color: #e4e4e7; border: 1px solid #3f3f46; border-radius: 8px; padding: 9px 11px; font-size: 13px }
238
+ :host([data-assistant]) textarea:focus { outline: none; border-color: #5468ff }
239
+ :host([data-assistant]) .row { display: none }
240
+ :host([data-assistant][data-following]) .row { display: flex; justify-content: flex-end }
241
+ :host([data-assistant]) .row .send { display: none }
242
+ :host([data-assistant]) .row button { background: none; color: #e4e4e7; border-color: #3f3f46 }
243
+ :host([data-assistant]) button.open { background: #18181b; color: #fafafa; border: 1px solid #3f3f46 }
244
+ `
245
+
246
+ /** Start the panel against the app served at `prefix` (`/api/agent-panel` at the root, `/app/api/agent-panel` in the frame). */
247
+ export async function start(prefix: string = '/api/agent-panel'): Promise<void> {
248
+ PREFIX = prefix
249
+ // A panel that is mounted again replaces the previous one: one live host, and the readiness mark then belongs to the instance being wired now. A
250
+ // duplicated or reused host once let a submit reach a form that no live instance was listening to (the frame gate's empty-log failure, 2026-11-02).
251
+ // The previous instance's run socket goes with it, so its watch ends instead of writing into a detached log.
252
+ activeSocket?.close()
253
+ activeSocket = undefined
254
+ document.getElementById('agent-panel')?.remove()
255
+ const reply = await fetch(`${PREFIX}/session`)
256
+ if (!reply.ok) return
257
+ let session = (await reply.json()) as Session
258
+
259
+ // The frame's Build is the builder's screen, and its Preview shows the app as production would: the panel takes the Assistant's variant only where
260
+ // production has it, and it is hidden everywhere the canvas should be the app alone. A direct page (no frame) is unchanged.
261
+ const frame = frameViewOf()
262
+ const assistant = panelVariant(session, frame)
263
+ const host = document.createElement('div')
264
+ host.id = 'agent-panel'
265
+ if (assistant) host.dataset.assistant = ''
266
+ const shadow = host.attachShadow({ mode: 'open' })
267
+ shadow.innerHTML = `<style>${css}</style>
268
+ <button class="open" type="button">${assistant ? 'Assistant' : 'Ask the agent'}</button>
269
+ <section aria-label="${assistant ? 'Assistant' : 'Agent panel'}">
270
+ <header><strong>Agent</strong><div class="tab"><span>Assistant</span></div><select aria-label="Agent">${session.drivers
271
+ .map((d) => `<option>${d.name}</option>`)
272
+ .join(
273
+ '',
274
+ )}</select><button class="termstop" type="button" hidden>Stop terminal</button><button class="close" type="button" aria-label="Close">×</button></header>
275
+ <p class="notice">${ASSISTANT_NOTE}</p>
276
+ <div id="log" role="log"></div>
277
+ <div id="term" hidden></div>
278
+ <form><textarea aria-label="Message" placeholder="${assistant ? 'Ask the assistant…' : 'What should the app do?'}"${assistant ? ' rows="1"' : ''}></textarea>
279
+ <div class="row"><button class="send" type="submit">Send</button><button class="stop" type="button" disabled>Stop</button></div></form>
280
+ </section>`
281
+ const $ = <T extends Element>(selector: string): T => shadow.querySelector<T>(selector)!
282
+ const panel = $<HTMLElement>('section')
283
+ const log = $<HTMLElement>('#log')
284
+ const input = $<HTMLTextAreaElement>('textarea')
285
+ // The composer survives the page being replaced (a run that changes files reloads the page, and a mount replaces this panel): the draft is kept
286
+ // beside the page, restored into this textarea before the form is wired, and cleared when a submit sends it.
287
+ try {
288
+ input.value = sessionStorage.getItem(DRAFT_KEY) ?? ''
289
+ } catch {
290
+ // No storage: the draft lives as long as this document.
291
+ }
292
+ input.addEventListener('input', () => {
293
+ try {
294
+ sessionStorage.setItem(DRAFT_KEY, input.value)
295
+ } catch {
296
+ // No storage: the draft lives as long as this document.
297
+ }
298
+ })
299
+ const send = $<HTMLButtonElement>('.send')
300
+ const stop = $<HTMLButtonElement>('.stop')
301
+ const driver = $<HTMLSelectElement>('select')
302
+ const term = $<HTMLElement>('#term')
303
+ const termStop = $<HTMLButtonElement>('.termstop')
304
+ termStop.addEventListener('click', () => void terminal?.stop())
305
+ const form = $<HTMLFormElement>('form')
306
+ document.body.append(host)
307
+ const applyFrame = (): void => {
308
+ host.style.display = panelVisible(frame, assistant) ? '' : 'none'
309
+ }
310
+ window.addEventListener(FRAME_MODE_EVENT, applyFrame)
311
+ applyFrame()
312
+ const kindOf = (name: string): 'chat' | 'terminal' =>
313
+ session.drivers.find((d) => d.name === name)?.kind ?? 'chat'
314
+ let terminal: { detach(): void; stop(): Promise<void> } | undefined
315
+ // A pick can land while an earlier pick's terminal is still loading (the page also restores a remembered terminal at
316
+ // start). Only the latest pick may apply its result; a stale terminal must never replace the form the person chose.
317
+ const picks = createPickGeneration()
318
+ // A terminal driver swaps the chat for the driver's own terminal (loaded from the plugin that provides it, only when asked for).
319
+ const choose = async (): Promise<void> => {
320
+ const generation = picks.begin()
321
+ const name = driver.value
322
+ terminal?.detach()
323
+ terminal = undefined
324
+ const isTerminal = kindOf(name) === 'terminal'
325
+ log.hidden = isTerminal
326
+ form.hidden = isTerminal
327
+ term.hidden = !isTerminal
328
+ termStop.hidden = !isTerminal
329
+ if (!isTerminal) return
330
+ const selected = session.drivers.find((entry) => entry.name === name)
331
+ if (selected?.view === undefined) {
332
+ line('This terminal driver does not provide its view.', 'err')
333
+ return
334
+ }
335
+ try {
336
+ const url = selected.view.module
337
+ const { openTerminal } = (await import(url)) as {
338
+ openTerminal(options: {
339
+ container: HTMLElement
340
+ token: string
341
+ driver: string
342
+ prefix: string
343
+ status(text: string): void
344
+ onChange(change: { extension: string; action: string }): void
345
+ }): Promise<{ detach(): void; stop(): Promise<void> }>
346
+ }
347
+ await refreshSession()
348
+ const opened = await openTerminal({
349
+ container: term,
350
+ token: session.token,
351
+ driver: name,
352
+ prefix: selected.view.prefix,
353
+ status: (text) => line(text, 'tool'),
354
+ onChange: (change) => {
355
+ line(`plugin ${change.extension}: ${change.action}`, 'tool')
356
+ line('Reloading the page to show it.', 'tool')
357
+ setTimeout(() => location.reload(), 900)
358
+ },
359
+ })
360
+ if (!picks.isCurrent(generation)) {
361
+ opened.detach()
362
+ return
363
+ }
364
+ terminal = opened
365
+ } catch (error) {
366
+ if (!picks.isCurrent(generation)) return
367
+ line(
368
+ `The terminal could not open: ${error instanceof Error ? error.message : String(error)}`,
369
+ 'err',
370
+ )
371
+ log.hidden = false
372
+ }
373
+ }
374
+ driver.addEventListener('change', () => void choose())
375
+ // The panel sits beside the page, not over it: while it is open the page is narrower by the panel's width, so its header and right-hand columns stay in view. (An element of the page
376
+ // that is positioned fixed to the window is not part of that layout and can still lie under the panel.)
377
+ const root = document.documentElement
378
+ const docked = ['margin-right'] as const
379
+ const saved = new Map<string, [string, string]>()
380
+ const dock = (open: boolean): void => {
381
+ if (open) {
382
+ for (const property of docked)
383
+ saved.set(property, [
384
+ root.style.getPropertyValue(property),
385
+ root.style.getPropertyPriority(property),
386
+ ])
387
+ // The panel's own width (the Assistant's is narrower than the builder's), so the page meets its edge with no gap.
388
+ root.style.setProperty(
389
+ 'margin-right',
390
+ `${String(Math.ceil(panel.getBoundingClientRect().width))}px`,
391
+ 'important',
392
+ )
393
+ } else {
394
+ for (const property of docked) {
395
+ const [value, priority] = saved.get(property) ?? ['', '']
396
+ if (value === '') root.style.removeProperty(property)
397
+ else root.style.setProperty(property, value, priority)
398
+ }
399
+ saved.clear()
400
+ }
401
+ }
402
+ const show = (open: boolean, focus = true): void => {
403
+ const was = panel.classList.contains('shown')
404
+ panel.classList.toggle('shown', open)
405
+ $<HTMLButtonElement>('button.open').hidden = open && assistant
406
+ if (open !== was) dock(open)
407
+ if (open && focus) input.focus()
408
+ // Other corner buttons of the page (the feedback button) stand clear of the panel.
409
+ window.dispatchEvent(new Event('agent-panel:layout'))
410
+ }
411
+ const remember = (closed: boolean): void => {
412
+ try {
413
+ if (closed) sessionStorage.setItem(ASSISTANT_CLOSED_KEY, '1')
414
+ else sessionStorage.removeItem(ASSISTANT_CLOSED_KEY)
415
+ } catch {
416
+ // No storage: the Assistant opens again on the next page.
417
+ }
418
+ }
419
+ $('button.open').addEventListener('click', () => {
420
+ show(true)
421
+ if (assistant) remember(false)
422
+ })
423
+ $('button.close').addEventListener('click', () => {
424
+ show(false)
425
+ if (assistant) remember(true)
426
+ })
427
+ // Enter asks (Shift+Enter is a new line): the Assistant has one line to ask in and no Send button.
428
+ if (assistant)
429
+ input.addEventListener('keydown', (event) => {
430
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
431
+ event.preventDefault()
432
+ form.requestSubmit()
433
+ }
434
+ })
435
+ const line = (text: string, kind = ''): HTMLElement => {
436
+ const el = document.createElement('div')
437
+ el.className = `msg ${kind}`
438
+ el.textContent = text
439
+ log.append(el)
440
+ log.scrollTop = log.scrollHeight
441
+ return el
442
+ }
443
+
444
+ // A run belongs to the app, not to this page: it goes on when the page reloads (the door reloads it after a plugin change, an agent may move it to another page) and the page that
445
+ // loads next follows it again. Only Stop cancels it.
446
+ const headers = { 'content-type': 'application/json', 'x-agent-panel-token': session.token }
447
+ /**
448
+ * The token belongs to one start of the app: `node --watch` restarts it at every change of a file, and a page left open across that restart holds a token the new server
449
+ * does not know. Ask for the session again; the caller tries once more with what it gets.
450
+ */
451
+ const refreshSession = async (): Promise<void> => {
452
+ const reply = await fetch(`${PREFIX}/session`)
453
+ if (!reply.ok) return
454
+ session = (await reply.json()) as Session
455
+ headers['x-agent-panel-token'] = session.token
456
+ }
457
+ let following = false
458
+ const stopRun = (): void => {
459
+ // On the run's socket when there is one: a request would wait behind the browser's six connections per host.
460
+ if (activeSocket?.readyState === WebSocket.OPEN)
461
+ activeSocket.send(JSON.stringify({ t: 'stop' }))
462
+ else void fetch(`${PREFIX}/stop`, { method: 'POST', headers })
463
+ }
464
+ stop.addEventListener('click', stopRun)
465
+ // The door's "Agent is driving" bar has a Stop too (the same page): it ends this run.
466
+ window.addEventListener('acryl:stop-run', stopRun)
467
+ const REFUSED = Symbol('refused')
468
+ /** A run over the socket when the server upgrades, else over the stream, with one console warning saying why. `REFUSED` when the server does not know the token. */
469
+ const tryOpenRun = async (
470
+ action: { t: 'ask'; message: string; driver: string; page?: string } | { t: 'follow' },
471
+ ): Promise<RunSource | { error: string } | undefined | typeof REFUSED> => {
472
+ if (!socketBroken && typeof WebSocket !== 'undefined') {
473
+ try {
474
+ const { socket, events: frames } = await openSocket(session.token, action)
475
+ activeSocket = socket
476
+ socket.addEventListener('close', () => {
477
+ if (activeSocket === socket) activeSocket = undefined
478
+ })
479
+ return { events: frames }
480
+ } catch (cause) {
481
+ if (cause instanceof Refused) return REFUSED
482
+ socketBroken = true
483
+ console.warn(
484
+ `agent-panel: the run could not open a WebSocket (${cause instanceof Error ? cause.message : String(cause)}); using server-sent events, which count against the browser's six connections per host`,
485
+ )
486
+ }
487
+ }
488
+ if (action.t === 'ask') {
489
+ const response = await fetch(`${PREFIX}/ask`, {
490
+ method: 'POST',
491
+ headers,
492
+ body: JSON.stringify({ message: action.message, driver: action.driver, page: action.page }),
493
+ })
494
+ if (response.status === 403) return REFUSED
495
+ if (!response.ok)
496
+ return {
497
+ error:
498
+ ((await response.json().catch(() => ({}))) as { error?: string }).error ??
499
+ `The panel answered ${response.status}.`,
500
+ }
501
+ return { events: events(response) }
502
+ }
503
+ const latest = await fetch(`${PREFIX}/run`, { headers })
504
+ if (latest.status === 403) return REFUSED
505
+ return latest.ok && (latest.headers.get('content-type') ?? '').includes('text/event-stream')
506
+ ? { events: events(latest) }
507
+ : undefined
508
+ }
509
+ /** `tryOpenRun`, and when the token was refused, a new session and one more try without the person seeing anything; a second refusal is shown. */
510
+ const openRun = async (
511
+ action: { t: 'ask'; message: string; driver: string; page?: string } | { t: 'follow' },
512
+ ): Promise<RunSource | { error: string } | undefined> => {
513
+ const first = await tryOpenRun(action)
514
+ if (first !== REFUSED) return first
515
+ await refreshSession()
516
+ const second = await tryOpenRun(action)
517
+ return second === REFUSED
518
+ ? { error: 'the panel was not accepted (reload the page and try again)' }
519
+ : second
520
+ }
521
+ /**
522
+ * Show one run, as its events come, until it ends. `own` is true for a run this page just started (its question is on screen); a run found on load is shown from its question, and
523
+ * a run that had already ended before the page loaded is only shown, never reloads the page.
524
+ */
525
+ const watch = async (source: RunSource, own: boolean): Promise<void> => {
526
+ let live = true
527
+ let changed = false
528
+ // Every run the server finishes ends with `done` or `error`; a stream that stops without either lost its server, and the run with it.
529
+ let finished = false
530
+ let answer: HTMLElement | undefined
531
+ let answered = ''
532
+ // The Assistant's steps on the page, shown under its answer in one line, as the person reads what it did.
533
+ const steps: string[] = []
534
+ const stepsLine = document.createElement('div')
535
+ stepsLine.className = 'steps'
536
+ // A coding agent started headless says little until it is done, so the panel says it is working, and for how long (from when the run began, not from when this page loaded).
537
+ let started = Date.now()
538
+ let working: HTMLElement | undefined
539
+ let timer: ReturnType<typeof setInterval> | undefined
540
+ const tick = (): void => {
541
+ if (working === undefined) return
542
+ const seconds = Math.max(0, Math.floor((Date.now() - started) / 1000))
543
+ working.textContent = `Working... ${String(Math.floor(seconds / 60))}:${String(seconds % 60).padStart(2, '0')}`
544
+ log.append(working)
545
+ }
546
+ // The panel is busy once there is a run to show. A page that just loaded asks the server for the latest run first, and "there is none" must not make a message typed in that moment
547
+ // wait or vanish, so a run that is only being looked for does not count (it begins at its first event).
548
+ const begin = (): void => {
549
+ if (working !== undefined) return
550
+ following = true
551
+ host.dataset.following = '1'
552
+ send.disabled = true
553
+ stop.disabled = false
554
+ working = line('', 'working')
555
+ tick()
556
+ timer = setInterval(tick, 1000)
557
+ }
558
+ if (own) begin()
559
+ try {
560
+ for await (const { event, data } of source.events) {
561
+ if (event === 'idle') continue
562
+ begin()
563
+ if (event === 'run') {
564
+ if (typeof data.startedAt === 'number') started = data.startedAt
565
+ tick()
566
+ live = data.ended !== true
567
+ if (!own) {
568
+ if (typeof data.message === 'string') line(data.message, 'me')
569
+ if (typeof data.driver === 'string' && kindOf(data.driver) === 'chat')
570
+ driver.value = data.driver
571
+ const recent =
572
+ data.ended !== true ||
573
+ (typeof data.endedAt === 'number' && Date.now() - data.endedAt < 120_000)
574
+ if (recent) show(true)
575
+ }
576
+ } else if (event === 'text') {
577
+ answer ??= line('', 'md')
578
+ answered += String(data.text ?? '')
579
+ answer.replaceChildren(renderMarkdown(answered, document))
580
+ if (assistant) {
581
+ stepsLine.textContent = steps.join(' · ')
582
+ answer.append(stepsLine)
583
+ }
584
+ log.scrollTop = log.scrollHeight
585
+ } else if (event === 'tool') {
586
+ if (assistant) {
587
+ const step = describePageStep(data)
588
+ if (step !== undefined) steps.push(step)
589
+ continue
590
+ }
591
+ const described = describeTool(data)
592
+ if (described !== undefined) line(described, 'tool')
593
+ } else if (event === 'change') {
594
+ changed = true
595
+ line(`plugin ${String(data.extension)}: ${String(data.action)}`, 'tool')
596
+ } else if (event === 'error') {
597
+ finished = true
598
+ line(String(data.message ?? 'The run failed.'), 'err')
599
+ } else if (event === 'done') {
600
+ finished = true
601
+ changed = changed || data.changed === true
602
+ }
603
+ }
604
+ if (live && working !== undefined && !finished)
605
+ line(
606
+ 'The app stopped while the agent was working, and the run ended with it (`npm run dev` restarts the app when a file it runs changes). Ask again to go on.',
607
+ 'err',
608
+ )
609
+ } catch (error) {
610
+ line(`The request failed: ${error instanceof Error ? error.message : String(error)}`, 'err')
611
+ } finally {
612
+ if (timer !== undefined) clearInterval(timer)
613
+ if (working !== undefined) {
614
+ working.remove()
615
+ following = false
616
+ delete host.dataset.following
617
+ send.disabled = false
618
+ stop.disabled = true
619
+ }
620
+ }
621
+ // A plugin was installed or removed while this page watched: the new feature is served by the running app, so the page only needs to be loaded again.
622
+ // The panel lives inside the app's own page (it cannot refresh the frame's canvas from here), so the page reload is the app's refresh - but the decision
623
+ // to reload is made at the moment of reloading, never on a check made a second earlier: a person (or the frame gate) can start typing in between, and a
624
+ // reload then replaces the page under their text (the frame gate's empty-composer dump, 2026-11-02).
625
+ if (live && changed) {
626
+ line('Reloading the page to show it.', 'tool')
627
+ setTimeout(() => {
628
+ if (
629
+ reloadDecision({
630
+ value: input.value,
631
+ focused: host.shadowRoot?.activeElement === input,
632
+ following,
633
+ })
634
+ )
635
+ reloadPage('a plugin changed')
636
+ }, 900)
637
+ }
638
+ }
639
+ form.addEventListener('submit', async (submitted) => {
640
+ submitted.preventDefault()
641
+ const refusal = sendRefusal(input.value, following)
642
+ if (refusal !== undefined) {
643
+ line(
644
+ refusal === 'empty' ? 'Type a message first.' : 'A run is already going; stop it first.',
645
+ 'err',
646
+ )
647
+ return
648
+ }
649
+ const message = input.value.trim()
650
+ input.value = ''
651
+ try {
652
+ sessionStorage.removeItem(DRAFT_KEY)
653
+ } catch {
654
+ // No storage.
655
+ }
656
+ // The message is sent: the composer is empty and the person is not typing, so it gives the focus back. A run that installs a plugin reloads the page
657
+ // afterwards, and that reload must not be refused for a focus nobody is using.
658
+ input.blur()
659
+ line(message, 'me')
660
+ try {
661
+ const run = await openRun({ t: 'ask', message, driver: driver.value, ...doorPage() })
662
+ if (run === undefined) return
663
+ if ('error' in run) {
664
+ line(run.error, 'err')
665
+ return
666
+ }
667
+ await watch(run, true)
668
+ } catch (error) {
669
+ line(`The request failed: ${error instanceof Error ? error.message : String(error)}`, 'err')
670
+ }
671
+ })
672
+ // The Assistant is open beside the page unless the visitor closed it.
673
+ if (assistant) {
674
+ let closed = false
675
+ try {
676
+ closed = sessionStorage.getItem(ASSISTANT_CLOSED_KEY) === '1'
677
+ } catch {
678
+ // No storage: open.
679
+ }
680
+ show(!closed, false)
681
+ }
682
+ // The form is wired: a script (the frame gate included) waits for this instead of guessing that the panel can be submitted, and a panel that never got
683
+ // this far says so by the mark's absence - together with the visible guards above, no submit can vanish without a trace.
684
+ host.dataset.ready = '1'
685
+ // The latest run, if there is one: shown again after a reload (its question, its events), and followed if it is still going. The server records a run
686
+ // before it answers the ask that started it (startRun sets the current run, then follow answers), so a page that asks after that answer always finds
687
+ // it - no client poll is needed. A run the app server itself restarted away (a file change the run made) no longer exists for that server to show.
688
+ try {
689
+ const latest = await openRun({ t: 'follow' })
690
+ if (latest !== undefined && !('error' in latest)) void watch(latest, false)
691
+ } catch {
692
+ // No run to show.
693
+ }
694
+ // A terminal that was open before a reload is still running on the server: show it again.
695
+ try {
696
+ const remembered = JSON.parse(sessionStorage.getItem('driver-pty-session') ?? 'null') as {
697
+ driver?: string
698
+ } | null
699
+ if (remembered?.driver && kindOf(remembered.driver) === 'terminal') {
700
+ driver.value = remembered.driver
701
+ show(true)
702
+ void choose()
703
+ }
704
+ } catch {
705
+ // No storage: nothing to show again.
706
+ }
707
+ }