agent-canvas 0.9.0-dev.12 → 0.9.0-dev.14

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 (61) hide show
  1. package/README.md +28 -0
  2. package/bin/agent-canvas.ts +8 -1
  3. package/bin/lib/cli-auth.ts +31 -0
  4. package/bin/lib/commands/daemon.ts +2 -1
  5. package/bin/lib/commands/exec.ts +5 -4
  6. package/bin/lib/commands/fetch.ts +4 -4
  7. package/bin/lib/commands/push.ts +3 -2
  8. package/bin/lib/commands/reply.ts +45 -0
  9. package/bin/lib/commands/review.ts +4 -2
  10. package/bin/lib/commands/watch.ts +100 -5
  11. package/bin/lib/helpers.ts +121 -43
  12. package/bin/lib/instructions/component-download.md +28 -0
  13. package/bin/lib/instructions/component-filedrop.md +50 -0
  14. package/bin/lib/instructions/overview.md +41 -1
  15. package/bin/lib/instructions/template-dashboard.md +177 -0
  16. package/bin/lib/instructions/template-slides.md +196 -0
  17. package/bin/lib/instructions/theming.md +25 -0
  18. package/daemon/client/App.tsx +17 -5
  19. package/daemon/client/clientApi.ts +64 -5
  20. package/daemon/client/components/Download.tsx +28 -0
  21. package/daemon/client/components/FileDrop.tsx +164 -0
  22. package/daemon/client/components/index.ts +3 -1
  23. package/daemon/client/threadStore.ts +70 -0
  24. package/daemon/dist/client.css +1 -1
  25. package/daemon/dist/client.js +57 -56
  26. package/daemon/dist/components.js +52 -49
  27. package/daemon/src/admission.ts +102 -0
  28. package/daemon/src/assets.ts +16 -0
  29. package/daemon/src/components.ts +6 -1
  30. package/daemon/src/handlers/api.ts +7 -4
  31. package/daemon/src/handlers/assets.ts +126 -0
  32. package/daemon/src/handlers/files.ts +124 -19
  33. package/daemon/src/handlers/static.ts +65 -1
  34. package/daemon/src/handlers/theme.ts +150 -0
  35. package/daemon/src/handlers/threads.ts +93 -0
  36. package/daemon/src/review/server.ts +1 -1
  37. package/daemon/src/server.ts +81 -47
  38. package/daemon/src/threads.ts +132 -0
  39. package/package.json +4 -4
  40. package/skills/canvas/SKILL.md +5 -0
  41. package/types/bin/lib/cli-auth.d.ts +9 -0
  42. package/types/bin/lib/commands/reply.d.ts +2 -0
  43. package/types/bin/lib/commands/watch.d.ts +3 -1
  44. package/types/bin/lib/helpers.d.ts +102 -0
  45. package/types/daemon/client/clientApi.d.ts +14 -1
  46. package/types/daemon/client/components/Download.d.ts +9 -0
  47. package/types/daemon/client/components/FileDrop.d.ts +12 -0
  48. package/types/daemon/client/components/index.d.ts +2 -0
  49. package/types/daemon/client/threadStore.d.ts +15 -0
  50. package/types/daemon/src/admission.d.ts +24 -0
  51. package/types/daemon/src/assets.d.ts +23 -0
  52. package/types/daemon/src/components.d.ts +3 -1
  53. package/types/daemon/src/handlers/assets.d.ts +14 -0
  54. package/types/daemon/src/handlers/files.d.ts +8 -2
  55. package/types/daemon/src/handlers/static.d.ts +16 -0
  56. package/types/daemon/src/handlers/theme.d.ts +18 -0
  57. package/types/daemon/src/handlers/threads.d.ts +19 -0
  58. package/types/daemon/src/review/model.d.ts +24 -24
  59. package/types/daemon/src/review/remote.d.ts +8 -8
  60. package/types/daemon/src/review/server.d.ts +2 -0
  61. package/types/daemon/src/threads.d.ts +109 -0
package/README.md CHANGED
@@ -58,6 +58,25 @@ Claude uses different canvas flows depending on the task:
58
58
  | **Decision** | Choosing between options | Single canvas with comparison |
59
59
  | **Runbook** | User must complete manual setup or provide a secret | Instructions → secure handoff → command → result |
60
60
 
61
+ ### Files from the user
62
+
63
+ `<FileDrop id label accept maxBytes required>` lets the user hand the agent a file from the canvas. The daemon stores it with the session (`sessions/<id>/assets/<field>/`, mode 0600), caps a file at 25 MB and a session at 100 files and 250 MB, and keeps the files until the session directory is removed; nothing deletes them automatically. A field's files stay listed on later revisions. The feedback lists their absolute paths; the agent reads them with its own tools. No route serves them back, so an upload is never rendered as a page or run as a script.
64
+
65
+ ### Threads and following a session
66
+
67
+ Submitted feedback labels each of the user's own annotations with its id; a remote reviewer's has none and opens no
68
+ thread. The agent can answer one annotation with `bunx agent-canvas reply <annotation-id> "<text>" [--resolve]`; the
69
+ reply appears under the annotation in the sidebar, where the user can answer back. The thread stays visible on later
70
+ revisions and is kept until the session directory is removed; nothing deletes it automatically. The user's answer
71
+ reaches the agent through `watch` and `fetch` like a submit. Answering a thread whose reply the agent has not read yet
72
+ is refused until `watch` hands that reply over.
73
+
74
+ `bunx agent-canvas watch --follow` keeps watching instead of exiting after the first answer. It prints one block per
75
+ submit, thread reply, render error and remote-feedback arrival, for hosts that turn each output line into an event
76
+ (Claude Code's Monitor). For remote feedback it prints only the count and the reviewers' self-typed names; their text
77
+ reaches the agent when the user includes it in a submit. A remote-feedback arrival is a best-effort notice: one that
78
+ comes while the watcher is reconnecting is not repeated.
79
+
61
80
  ### Local secret handoff
62
81
 
63
82
  Runbooks can use `SecretInput` when a command needs a token that must stay out of feedback and model context. The browser stores the value only in the local daemon's memory. Feedback contains the field ID and environment variable name, not the value.
@@ -73,6 +92,8 @@ bunx agent-canvas exec \
73
92
 
74
93
  Secret resolution requires a daemon capability available to the CLI but not to canvas JavaScript. A new canvas revision, daemon shutdown, or session cleanup clears the value. The target command must not print its environment or credentials.
75
94
 
95
+ The daemon answers only requests addressed to `localhost`, `127.0.0.1` or `[::1]` on its port. It refuses state-changing requests and WebSocket upgrades from any origin other than its own UI, requires the CLI capability on the routes only the CLI calls (push, feedback, secret resolution, thread replies and claims, review agent routes), and never serves its own temporary or data directory through the file routes. The file routes serve a session's project root and, outside it, only the files its canvases name in `FilePreview path`, `Markdown file`, `ImageView src` or `Download path`, symlinks resolved; they list no directory outside it. `/api/download`, behind `<Download path>`, serves only a named file, inside the root too, as an `application/octet-stream` attachment. The canvas author controls that list, so it stops reads of paths no canvas names, not a hostile canvas. The canvas page carries a Content-Security-Policy that lets canvas JavaScript connect only to the daemon. Images, fonts, stylesheets and media may come from any https origin, and such a URL, like a navigation, can still carry data out. Every other daemon response carries an inert policy, so a frame or window of it cannot be scripted past the page's.
96
+
76
97
  ### Review mode
77
98
 
78
99
  Review mode puts the same comment loop on a running web application: a prototype, a mock or any dev server. Open the
@@ -111,6 +132,13 @@ stored on this machine. `watch`, `reply`, `fetch` and `list` work as above.
111
132
 
112
133
  Agent Canvas supports light and dark themes, automatically matching your system preference.
113
134
 
135
+ A project can set its own colours and fonts in `.agent-canvas/theme.css` at its root; they apply to the canvases and
136
+ the UI around them. The daemon accepts only `--color-*` and `--font-*` variables on `:root`, `[data-theme="light"]`
137
+ and `[data-theme="dark"]`, with balanced plain values, and serves its own rebuild of them, so a theme cannot load a
138
+ URL or style the page otherwise. The file must stay inside the project (no symlink out) and under 64 KB. A file that
139
+ breaks a rule is not applied; the daemon log and the browser console give the line. The `template-dashboard` and
140
+ `template-slides` instructions topics are starting points for a status dashboard and a deck.
141
+
114
142
  **Dark mode**
115
143
 
116
144
  ![](docs/dark.png)
@@ -6,6 +6,7 @@ import { handleFetch } from './lib/commands/fetch.ts'
6
6
  import { handleInstall } from './lib/commands/install.ts'
7
7
  import { handleInstructions } from './lib/commands/instructions.ts'
8
8
  import { handlePush } from './lib/commands/push.ts'
9
+ import { handleReply } from './lib/commands/reply.ts'
9
10
  import { handleReview } from './lib/commands/review.ts'
10
11
  import { handleWatch } from './lib/commands/watch.ts'
11
12
  import { VERSION } from './lib/config.ts'
@@ -18,7 +19,11 @@ Commands:
18
19
  agent-canvas instructions [topic] Show usage instructions (for AI agents)
19
20
  agent-canvas push <directory> Push canvases, open browser
20
21
  agent-canvas fetch [--session <id>] Check for feedback (returns immediately)
21
- agent-canvas watch [--session <id>] Wait for user feedback (blocks until submitted)
22
+ agent-canvas watch [--session <id>] Wait for user feedback or a thread reply (blocks until one arrives)
23
+ agent-canvas watch --follow Keep watching; print every submit, thread reply, render error
24
+ and remote-feedback arrival as its own block
25
+ agent-canvas reply <annotation-id> "<text>" [--resolve]
26
+ Answer one submitted annotation in its thread
22
27
  agent-canvas review <command> Comment on a running application (see: agent-canvas review --help)
23
28
  agent-canvas exec --secret ENV=id -- <command>
24
29
  Run a command with an in-memory secret
@@ -54,6 +59,8 @@ async function main() {
54
59
  return handleFetch(rest)
55
60
  case 'watch':
56
61
  return handleWatch(rest)
62
+ case 'reply':
63
+ return handleReply(rest)
57
64
  case 'review':
58
65
  return handleReview(rest)
59
66
  case 'exec':
@@ -0,0 +1,31 @@
1
+ import { readFileSync } from 'fs'
2
+ import { CLI_TOKEN_HEADER, CLI_TOKEN_QUERY } from '../../daemon/src/admission.ts'
3
+ import { CLI_AUTH_FILE } from './config.ts'
4
+
5
+ /**
6
+ * The capability the running daemon wrote for its owner's CLI, or undefined when no daemon wrote one. Read on every
7
+ * request: a restarted daemon writes a new one.
8
+ */
9
+ export function readCliAuthToken(): string | undefined {
10
+ try {
11
+ const token = readFileSync(CLI_AUTH_FILE, 'utf-8').trim()
12
+ return token === '' ? undefined : token
13
+ } catch {
14
+ return undefined
15
+ }
16
+ }
17
+
18
+ /** Headers that authenticate a CLI request to the daemon; empty when no capability is available. */
19
+ export function cliAuthHeaders(): Record<string, string> {
20
+ const token = readCliAuthToken()
21
+ return token === undefined ? {} : { [CLI_TOKEN_HEADER]: token }
22
+ }
23
+
24
+ /** A daemon WebSocket URL that authenticates the CLI; the DOM `WebSocket` constructor the CLI is typed against takes no headers. */
25
+ export function cliSocketUrl(url: string): string {
26
+ const token = readCliAuthToken()
27
+ if (token === undefined) return url
28
+ const authenticated = new URL(url)
29
+ authenticated.searchParams.set(CLI_TOKEN_QUERY, token)
30
+ return authenticated.toString()
31
+ }
@@ -1,5 +1,6 @@
1
1
  import { parseArgs } from 'util'
2
2
  import { z } from 'zod'
3
+ import { cliAuthHeaders } from '../cli-auth.ts'
3
4
  import { BASE_URL, DAEMON_PORT } from '../config.ts'
4
5
  import { isDaemonRunning, startDaemon, stopDaemon } from '../daemon-lifecycle.ts'
5
6
 
@@ -16,7 +17,7 @@ export async function handleDaemon(args: string[]) {
16
17
  switch (subcommand) {
17
18
  case 'status': {
18
19
  try {
19
- const res = await fetch(`${BASE_URL}/health`, { signal: AbortSignal.timeout(2000) })
20
+ const res = await fetch(`${BASE_URL}/health`, { headers: cliAuthHeaders(), signal: AbortSignal.timeout(2000) })
20
21
  const data = healthResponseSchema.parse(await res.json())
21
22
  console.log(`Daemon: running on port ${DAEMON_PORT}`)
22
23
  console.log(`Sessions: ${data.sessions.length > 0 ? data.sessions.join(', ') : 'none'}`)
@@ -1,7 +1,8 @@
1
- import { existsSync, readFileSync } from 'fs'
1
+ import { existsSync } from 'fs'
2
2
  import { resolve } from 'path'
3
3
  import { parseArgs } from 'util'
4
- import { BASE_URL, CLI_AUTH_FILE } from '../config.ts'
4
+ import { readCliAuthToken } from '../cli-auth.ts'
5
+ import { BASE_URL } from '../config.ts'
5
6
  import { ensureDaemon } from '../daemon-lifecycle.ts'
6
7
  import { getSessionId } from '../helpers.ts'
7
8
 
@@ -44,8 +45,8 @@ export function parseSecretAssignments(rawAssignments: string[]): SecretAssignme
44
45
  }
45
46
 
46
47
  async function resolveSecretValues(sessionId: string, fieldIds: string[]): Promise<Map<string, string>> {
47
- if (!existsSync(CLI_AUTH_FILE)) throw new Error('Canvas daemon CLI capability is unavailable')
48
- const cliAuthToken = readFileSync(CLI_AUTH_FILE, 'utf-8').trim()
48
+ const cliAuthToken = readCliAuthToken()
49
+ if (cliAuthToken === undefined) throw new Error('Canvas daemon CLI capability is unavailable')
49
50
  const response = await fetch(`${BASE_URL}/api/session/${encodeURIComponent(sessionId)}/secrets/resolve`, {
50
51
  method: 'POST',
51
52
  headers: {
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from 'util'
2
2
  import { ensureDaemon } from '../daemon-lifecycle.ts'
3
- import { consumeFeedback, getSessionId } from '../helpers.ts'
3
+ import { getSessionId, pendingInput } from '../helpers.ts'
4
4
 
5
5
  export async function handleFetch(args: string[]) {
6
6
  const { values } = parseArgs({
@@ -13,8 +13,8 @@ export async function handleFetch(args: string[]) {
13
13
  const sessionId = getSessionId(values.session)
14
14
  await ensureDaemon()
15
15
 
16
- const feedback = await consumeFeedback(sessionId)
17
- if (feedback) {
18
- process.stdout.write(feedback)
16
+ const pending = await pendingInput(sessionId)
17
+ if (pending) {
18
+ process.stdout.write(pending)
19
19
  }
20
20
  }
@@ -2,6 +2,7 @@ import { existsSync, statSync } from 'fs'
2
2
  import { basename, resolve } from 'path'
3
3
  import { parseArgs } from 'util'
4
4
  import { z } from 'zod'
5
+ import { cliAuthHeaders } from '../cli-auth.ts'
5
6
  import { BASE_URL } from '../config.ts'
6
7
  import { ensureDaemon, startDaemon, stopDaemon } from '../daemon-lifecycle.ts'
7
8
  import { getSessionId, openBrowser } from '../helpers.ts'
@@ -60,7 +61,7 @@ export async function handlePush(args: string[]) {
60
61
 
61
62
  const response = await fetch(`${BASE_URL}/api/session/${sessionId}/plan`, {
62
63
  method: 'POST',
63
- headers: { 'Content-Type': 'application/json' },
64
+ headers: { 'Content-Type': 'application/json', ...cliAuthHeaders() },
64
65
  body: JSON.stringify({
65
66
  directory: resolvedPath,
66
67
  projectRoot,
@@ -89,7 +90,7 @@ export async function handlePush(args: string[]) {
89
90
  await startDaemon()
90
91
  const retryResponse = await fetch(`${BASE_URL}/api/session/${sessionId}/plan`, {
91
92
  method: 'POST',
92
- headers: { 'Content-Type': 'application/json' },
93
+ headers: { 'Content-Type': 'application/json', ...cliAuthHeaders() },
93
94
  body: JSON.stringify({
94
95
  directory: resolvedPath,
95
96
  projectRoot,
@@ -0,0 +1,45 @@
1
+ import { parseArgs } from 'util'
2
+ import { z } from 'zod'
3
+ import { cliAuthHeaders } from '../cli-auth.ts'
4
+ import { BASE_URL } from '../config.ts'
5
+ import { ensureDaemon } from '../daemon-lifecycle.ts'
6
+ import { getSessionId } from '../helpers.ts'
7
+
8
+ const USAGE = 'Usage: agent-canvas reply <annotation-id> "<text>" [--resolve] [--session <id>]'
9
+
10
+ const replyResponseSchema = z.union([
11
+ z.object({ thread: z.object({ id: z.string(), state: z.string() }) }),
12
+ z.object({ error: z.string() }),
13
+ ])
14
+
15
+ /** Answers one submitted annotation; the user sees the reply under it in the sidebar. */
16
+ export async function handleReply(args: string[]) {
17
+ const { values, positionals } = parseArgs({
18
+ args,
19
+ allowPositionals: true,
20
+ options: {
21
+ session: { type: 'string' },
22
+ resolve: { type: 'boolean', default: false },
23
+ },
24
+ })
25
+ const [annotationId, ...words] = positionals
26
+ const body = words.join(' ').trim()
27
+ if (annotationId === undefined || body === '') {
28
+ console.error(USAGE)
29
+ process.exit(1)
30
+ }
31
+
32
+ const sessionId = getSessionId(values.session)
33
+ await ensureDaemon()
34
+ const res = await fetch(`${BASE_URL}/api/session/${sessionId}/threads/${encodeURIComponent(annotationId)}/reply`, {
35
+ method: 'POST',
36
+ headers: { 'Content-Type': 'application/json', ...cliAuthHeaders() },
37
+ body: JSON.stringify({ body, resolve: values.resolve }),
38
+ })
39
+ const data = replyResponseSchema.parse(await res.json())
40
+ if ('error' in data) {
41
+ console.error(`Error: ${data.error}`)
42
+ process.exit(1)
43
+ }
44
+ console.log(`Replied to ${data.thread.id}; the thread is ${data.thread.state === 'resolved' ? 'resolved' : 'back with the user'}.`)
45
+ }
@@ -5,6 +5,7 @@ import { parseArgs } from 'util'
5
5
  import { z } from 'zod'
6
6
  import { PROJECT_RE, type ReviewThread, reviewThreadSchema } from '../../../daemon/src/review/model.ts'
7
7
  import { KEEPALIVE_PONG } from '../../../daemon/src/review/remote.ts'
8
+ import { cliAuthHeaders, cliSocketUrl } from '../cli-auth.ts'
8
9
  import { BASE_URL, TIMEOUT_MS, WS_URL } from '../config.ts'
9
10
  import { ensureDaemon } from '../daemon-lifecycle.ts'
10
11
  import { openBrowser } from '../helpers.ts'
@@ -47,7 +48,8 @@ function defaultProject(): string {
47
48
  async function call(project: string, method: string, path: string, body?: unknown): Promise<unknown> {
48
49
  const response = await fetch(`${BASE_URL}/api/review/${encodeURIComponent(project)}${path}`, {
49
50
  method,
50
- ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }),
51
+ headers: body === undefined ? cliAuthHeaders() : { 'Content-Type': 'application/json', ...cliAuthHeaders() },
52
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
51
53
  })
52
54
  const result: unknown = await response.json()
53
55
  if (!response.ok) {
@@ -74,7 +76,7 @@ class DaemonReviewBackend implements ReviewBackend {
74
76
  }
75
77
 
76
78
  createSocket(url: string): WebSocket {
77
- return new WebSocket(url)
79
+ return new WebSocket(cliSocketUrl(url))
78
80
  }
79
81
 
80
82
  async claim(): Promise<string | undefined> {
@@ -1,26 +1,38 @@
1
1
  import { parseArgs } from 'util'
2
+ import { cliSocketUrl } from '../cli-auth.ts'
3
+ import { WS_URL } from '../config.ts'
2
4
  import { ensureDaemon } from '../daemon-lifecycle.ts'
3
- import { consumeFeedback, getSessionId, waitForFeedback } from '../helpers.ts'
5
+ import {
6
+ claimThreadReplies,
7
+ consumeFeedback,
8
+ formatCanvasRenderError,
9
+ getSessionId,
10
+ parseWaitFrame,
11
+ pendingInput,
12
+ waitForFeedback,
13
+ } from '../helpers.ts'
4
14
 
5
15
  export async function handleWatch(args: string[]) {
6
16
  const { values } = parseArgs({
7
17
  args,
8
18
  options: {
9
19
  session: { type: 'string' },
20
+ follow: { type: 'boolean', default: false },
10
21
  },
11
22
  })
12
23
 
13
24
  const sessionId = getSessionId(values.session)
14
25
  await ensureDaemon()
26
+ if (values.follow) return followSession(sessionId)
15
27
 
16
- const feedback = await consumeFeedback(sessionId)
17
- if (feedback) {
18
- process.stdout.write(feedback)
28
+ const pending = await pendingInput(sessionId)
29
+ if (pending) {
30
+ process.stdout.write(pending)
19
31
  process.exit(0)
20
32
  }
21
33
 
22
34
  try {
23
- const submittedFeedback = await waitForFeedback(sessionId)
35
+ const submittedFeedback = await waitForFeedback(sessionId, { probe: () => pendingInput(sessionId) })
24
36
  process.stdout.write(submittedFeedback)
25
37
  } catch (error) {
26
38
  const message = error instanceof Error ? error.message : String(error)
@@ -28,3 +40,86 @@ export async function handleWatch(args: string[]) {
28
40
  process.exit(1)
29
41
  }
30
42
  }
43
+
44
+ const RECONNECT_MS = 2_000
45
+ const GIVE_UP_MS = 60_000
46
+ const MAX_NAME = 40
47
+
48
+ /** A name a reviewer typed, as a quoted label that cannot pass for anything else in the agent's output. */
49
+ export function reviewerLabel(name: string): string {
50
+ return JSON.stringify(name.replace(/\p{Cc}/gu, ' ').trim().slice(0, MAX_NAME))
51
+ }
52
+
53
+ function emit(event: string, body: string): void {
54
+ process.stdout.write(`[agent-canvas ${event}]\n${body.trimEnd()}\n\n`)
55
+ }
56
+
57
+ /**
58
+ * The streaming watcher for hosts that turn each output line into an event (Claude Code's Monitor): one block per
59
+ * submit, thread reply, render error or remote-feedback arrival. Status goes to stderr, so every stdout block is
60
+ * worth acting on. A submit ends the daemon's wait, so the socket reconnects after each one.
61
+ */
62
+ function followSession(sessionId: string): Promise<never> {
63
+ let draining = Promise.resolve()
64
+ let unreachableSince: number | null = null
65
+
66
+ // Reads what the socket only announces, or what arrived while it was reconnecting; each is handed over once.
67
+ const drain = () => {
68
+ draining = draining.then(async () => {
69
+ const feedback = await consumeFeedback(sessionId)
70
+ if (feedback) emit('submit', feedback)
71
+ const replies = await claimThreadReplies(sessionId)
72
+ if (replies) emit('thread-reply', replies)
73
+ }).catch((error: unknown) => {
74
+ console.error(`watch: ${error instanceof Error ? error.message : String(error)}`)
75
+ })
76
+ }
77
+
78
+ const onFrame = (raw: unknown) => {
79
+ if (typeof raw !== 'string') return
80
+ let json: unknown
81
+ try {
82
+ json = JSON.parse(raw)
83
+ } catch {
84
+ return
85
+ }
86
+ const frame = parseWaitFrame(json)
87
+ switch (frame?.type) {
88
+ case 'submit':
89
+ return emit('submit', frame.feedback)
90
+ case 'render-error':
91
+ return emit('render-error', formatCanvasRenderError(frame.error))
92
+ case 'thread-queued':
93
+ return drain()
94
+ case 'remote-feedback-arrived':
95
+ return emit(
96
+ 'remote-feedback-arrived',
97
+ `${frame.count} comment(s) on revision ${frame.revision} from reviewer(s) ${frame.reviewers.map(reviewerLabel).join(', ')}`
98
+ + ' (names as they typed them). Their text reaches you only when the user includes it in a submit.',
99
+ )
100
+ default:
101
+ return
102
+ }
103
+ }
104
+
105
+ const connect = () => {
106
+ const socket = new WebSocket(cliSocketUrl(`${WS_URL}/ws/wait/${sessionId}`))
107
+ socket.onopen = () => {
108
+ unreachableSince = null
109
+ console.error(`watch: following session ${sessionId}`)
110
+ drain()
111
+ }
112
+ socket.onmessage = (event) => onFrame(event.data)
113
+ socket.onclose = () => {
114
+ unreachableSince ??= Date.now()
115
+ if (Date.now() - unreachableSince > GIVE_UP_MS) {
116
+ console.log(`[agent-canvas stopped]\nThe daemon has been unreachable for a minute; stopped following session ${sessionId}.`)
117
+ process.exit(1)
118
+ }
119
+ setTimeout(connect, RECONNECT_MS)
120
+ }
121
+ }
122
+
123
+ connect()
124
+ return new Promise<never>(() => {})
125
+ }
@@ -1,7 +1,8 @@
1
- import { type WaiterSocket, waitForEvent, type WaitVerdict } from '@fabrika/daemon-kit'
1
+ import { WaitError, type WaiterSocket, waitForEvent, type WaitVerdict } from '@fabrika/daemon-kit'
2
2
  import { spawn } from 'child_process'
3
3
  import { randomUUID } from 'crypto'
4
4
  import { z } from 'zod'
5
+ import { cliAuthHeaders, cliSocketUrl } from './cli-auth.ts'
5
6
  import { BASE_URL, TIMEOUT_MS, WS_URL } from './config.ts'
6
7
 
7
8
  export function getSessionId(session?: string): string {
@@ -19,12 +20,26 @@ const consumeResponseSchema = z.discriminatedUnion('found', [
19
20
  ])
20
21
 
21
22
  export async function consumeFeedback(sessionId: string): Promise<string | null> {
22
- const res = await fetch(`${BASE_URL}/api/session/${sessionId}/feedback/consume`, { method: 'POST' })
23
+ const res = await fetch(`${BASE_URL}/api/session/${sessionId}/feedback/consume`, { method: 'POST', headers: cliAuthHeaders() })
23
24
  const data = consumeResponseSchema.parse(await res.json())
24
25
  if (data.found) return data.feedback
25
26
  return null
26
27
  }
27
28
 
29
+ const claimResponseSchema = z.object({ markdown: z.string().nullable() })
30
+
31
+ /** The thread replies the user sent since the last claim, as markdown; each is handed over once. */
32
+ export async function claimThreadReplies(sessionId: string): Promise<string | null> {
33
+ const res = await fetch(`${BASE_URL}/api/session/${sessionId}/threads/claim`, { method: 'POST', headers: cliAuthHeaders() })
34
+ if (!res.ok) throw new Error(`Claiming thread replies failed with status ${res.status}`)
35
+ return claimResponseSchema.parse(await res.json()).markdown
36
+ }
37
+
38
+ /** What the user sent and the agent has not read yet: a submit first, then thread replies. */
39
+ export async function pendingInput(sessionId: string): Promise<string | null> {
40
+ return (await consumeFeedback(sessionId)) ?? (await claimThreadReplies(sessionId))
41
+ }
42
+
28
43
  export function openBrowser(url: string) {
29
44
  const candidates = process.platform === 'darwin'
30
45
  ? ['open']
@@ -42,67 +57,130 @@ export function openBrowser(url: string) {
42
57
 
43
58
  interface FeedbackWaitOptions {
44
59
  createSocket?: (url: string) => WaiterSocket
60
+ /** Reads input the socket only announces (a thread reply) or that arrived while it was reconnecting. */
61
+ probe?: () => Promise<string | null>
45
62
  timeoutMs?: number
46
63
  reconnectAttempts?: number
47
64
  reconnectDelayMs?: number
48
65
  }
49
66
 
50
- interface CanvasRenderError {
51
- revision: number
52
- filename: string
53
- message: string
54
- stack?: string
55
- componentStack?: string
56
- }
67
+ const canvasRenderErrorSchema = z.object({
68
+ revision: z.number().int(),
69
+ filename: z.string(),
70
+ message: z.string(),
71
+ stack: z.string().optional(),
72
+ componentStack: z.string().optional(),
73
+ })
74
+ type CanvasRenderError = z.infer<typeof canvasRenderErrorSchema>
57
75
 
58
- function isRecord(value: unknown): value is Record<string, unknown> {
59
- return typeof value === 'object' && value !== null && !Array.isArray(value)
60
- }
76
+ /** What the daemon sends a waiting CLI. */
77
+ const waitFrameSchema = z.discriminatedUnion('type', [
78
+ z.object({ type: z.literal('submit'), feedback: z.string() }),
79
+ z.object({ type: z.literal('render-error'), error: canvasRenderErrorSchema }),
80
+ z.object({ type: z.literal('thread-queued') }),
81
+ z.object({ type: z.literal('remote-feedback-arrived'), revision: z.number().int(), count: z.number().int(), reviewers: z.array(z.string()) }),
82
+ ])
83
+ export type WaitFrame = z.infer<typeof waitFrameSchema>
61
84
 
62
- function isCanvasRenderError(value: unknown): value is CanvasRenderError {
63
- return typeof value === 'object' && value !== null
64
- && 'revision' in value && Number.isInteger(value.revision)
65
- && 'filename' in value && typeof value.filename === 'string'
66
- && 'message' in value && typeof value.message === 'string'
67
- && (!('stack' in value) || value.stack === undefined || typeof value.stack === 'string')
68
- && (!('componentStack' in value) || value.componentStack === undefined || typeof value.componentStack === 'string')
85
+ /** A frame the CLI understands, or null for anything else (a keepalive, a newer daemon's frame). */
86
+ export function parseWaitFrame(frame: unknown): WaitFrame | null {
87
+ const parsed = waitFrameSchema.safeParse(frame)
88
+ return parsed.success ? parsed.data : null
69
89
  }
70
90
 
71
- function formatCanvasRenderError(error: CanvasRenderError): string {
91
+ export function formatCanvasRenderError(error: CanvasRenderError): string {
72
92
  const details = [`Canvas render failed in ${error.filename} (revision ${error.revision}):`, error.message]
73
93
  if (error.componentStack?.trim()) details.push(`Component stack:${error.componentStack}`)
74
94
  if (error.stack?.trim()) details.push(`Browser stack:\n${error.stack}`)
75
95
  return details.join('\n')
76
96
  }
77
97
 
98
+ /** One handed-over input. Boxed so the wait can tell which probe settled it, whatever the text. */
99
+ interface Input {
100
+ text: string
101
+ }
102
+
78
103
  /** A canvas that failed to render is the answer — retrying the socket cannot fix it. */
79
- function readFeedbackFrame(frame: unknown): WaitVerdict<string> | undefined {
80
- if (!isRecord(frame)) return undefined
81
- if (frame.type === 'submit' && typeof frame.feedback === 'string') {
82
- return { type: 'settle', value: frame.feedback }
104
+ function readFeedbackFrame(raw: unknown): WaitVerdict<Input> | undefined {
105
+ const frame = parseWaitFrame(raw)
106
+ switch (frame?.type) {
107
+ case 'submit':
108
+ return { type: 'settle', value: { text: frame.feedback } }
109
+ case 'render-error':
110
+ return { type: 'fail', error: new Error(formatCanvasRenderError(frame.error)) }
111
+ case 'thread-queued':
112
+ return { type: 'recheck' }
113
+ default:
114
+ return undefined
115
+ }
116
+ }
117
+
118
+ type ConnectionOutcome =
119
+ | { type: 'settled'; text: string; late: string[] }
120
+ | { type: 'failed'; error: unknown; late: string[] }
121
+
122
+ const LATE_PROBE_GRACE_MS = 2_000
123
+
124
+ /**
125
+ * One connection's wait. A probe hands input over once, so one that resolves after its connection settled or
126
+ * dropped is returned as `late` instead of being lost.
127
+ */
128
+ async function waitOnConnection(sessionId: string, options: FeedbackWaitOptions, timeoutMs: number): Promise<ConnectionOutcome> {
129
+ const { probe } = options
130
+ const reads: Promise<Input | null>[] = []
131
+ const late = async (settled: Input | null): Promise<string[]> => {
132
+ // A probe is one local request; a daemon that never answers it must not hold the wait open.
133
+ let timer: ReturnType<typeof setTimeout> | undefined
134
+ const giveUp = new Promise<null>((resolve) => (timer = setTimeout(() => resolve(null), LATE_PROBE_GRACE_MS)))
135
+ const inputs = await Promise.all(reads.map((read) => Promise.race([read.catch(() => null), giveUp])))
136
+ clearTimeout(timer)
137
+ return inputs.flatMap((input) => (input === null || input === settled ? [] : [input.text]))
83
138
  }
84
- if (frame.type === 'render-error' && isCanvasRenderError(frame.error)) {
85
- return { type: 'fail', error: new Error(formatCanvasRenderError(frame.error)) }
139
+ try {
140
+ const settled = await waitForEvent<Input>({
141
+ url: `${WS_URL}/ws/wait/${sessionId}`,
142
+ onFrame: readFeedbackFrame,
143
+ ...(probe === undefined ? {} : {
144
+ probe: async () => {
145
+ const read = probe().then((text) => (text === null ? null : { text }))
146
+ reads.push(read)
147
+ const input = await read
148
+ return input === null ? undefined : { value: input }
149
+ },
150
+ alreadyProbed: true,
151
+ }),
152
+ createSocket: options.createSocket ?? ((url) => new WebSocket(cliSocketUrl(url))),
153
+ timeoutMs,
154
+ messages: {
155
+ timeout: 'Timeout waiting for feedback.',
156
+ closed: 'WebSocket closed before feedback was submitted.',
157
+ connectionFailed: 'WebSocket connection failed.',
158
+ },
159
+ })
160
+ return { type: 'settled', text: settled.text, late: await late(settled) }
161
+ } catch (error) {
162
+ return { type: 'failed', error, late: await late(null) }
86
163
  }
87
- return undefined
88
164
  }
89
165
 
90
- export function waitForFeedback(sessionId: string, options: FeedbackWaitOptions = {}): Promise<string> {
91
- return waitForEvent<string>({
92
- url: `${WS_URL}/ws/wait/${sessionId}`,
93
- onFrame: readFeedbackFrame,
94
- ...(options.createSocket ? { createSocket: options.createSocket } : {}),
95
- timeoutMs: options.timeoutMs ?? TIMEOUT_MS,
96
- reconnect: {
97
- attempts: options.reconnectAttempts ?? 3,
98
- delayMs: options.reconnectDelayMs ?? 1_000,
99
- },
100
- messages: {
101
- timeout: 'Timeout waiting for feedback.',
102
- closed: 'WebSocket closed before feedback was submitted.',
103
- connectionFailed: 'WebSocket connection failed.',
104
- },
105
- })
166
+ export async function waitForFeedback(sessionId: string, options: FeedbackWaitOptions = {}): Promise<string> {
167
+ const deadline = Date.now() + (options.timeoutMs ?? TIMEOUT_MS)
168
+ const reconnectAttempts = options.reconnectAttempts ?? 3
169
+ const reconnectDelayMs = options.reconnectDelayMs ?? 1_000
170
+ // Reconnects here rather than in the waiter, so input claimed on a dropped connection is seen before the next one.
171
+ for (let attempt = 0;; attempt++) {
172
+ const outcome = await waitOnConnection(sessionId, options, deadline - Date.now())
173
+ if (outcome.type === 'settled') return [outcome.text, ...outcome.late].join('\n')
174
+ const { error, late } = outcome
175
+ const dropped = error instanceof WaitError && error.retryable
176
+ if (dropped && late.length > 0) return late.join('\n')
177
+ if (!dropped || attempt >= reconnectAttempts) {
178
+ if (late.length === 0) throw error
179
+ const message = error instanceof Error ? error.message : String(error)
180
+ throw new Error(`${message}\n\n${late.join('\n')}`, { cause: error })
181
+ }
182
+ await Bun.sleep(Math.min(reconnectDelayMs, Math.max(0, deadline - Date.now())))
183
+ }
106
184
  }
107
185
 
108
186
  export async function readLine(): Promise<string> {
@@ -0,0 +1,28 @@
1
+ # Component: Download
2
+
3
+ Hands the user a file you produced: a generated report, a patch, an export. Renders a download link.
4
+
5
+ The daemon serves the file only because this canvas names it, so write `path` as a string literal
6
+ (`path="/abs/out/report.pdf"` or `path={"/abs/out/report.pdf"}`). A path computed at run time is refused. The file
7
+ is sent as an attachment and never opened in the canvas.
8
+
9
+ ## Props
10
+
11
+ - `path` (string, required) — an absolute path, or one relative to the project root.
12
+ - `label` (string) — the link text; the file name by default.
13
+
14
+ ## Usage
15
+
16
+ ```jsx
17
+ <Section title="Migration report">
18
+ The dry run touched 1,204 rows. The full report is below.
19
+ <Download
20
+ path="/home/user/project/out/migration-report.csv"
21
+ label="Migration report (CSV)"
22
+ />
23
+ <Download path="/home/user/project/out/fix.patch" />
24
+ </Section>
25
+ ```
26
+
27
+ Write the file before you push the canvas. On a shared link the component shows the file name only; the file stays
28
+ on your machine.