@fabrika/canvas-kernel 0.9.0-dev.13 → 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.
package/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { compileJsx, compilePlan, KERNEL_COMPONENTS } from './src/engine/compiler'
2
- export type { CanvasComponents, CanvasComponentSpec, CompileOptions, CompileResult } from './src/engine/compiler'
1
+ export { canvasFileReferences, compileJsx, compilePlan, KERNEL_COMPONENTS } from './src/engine/compiler'
2
+ export type { CanvasComponents, CanvasComponentSpec, CompileOptions, CompileResult, FileReferenceProp } from './src/engine/compiler'
3
3
  export type { AssertReadable } from './src/engine/file-admission'
4
4
  export { createCanvasPaths } from './src/engine/paths'
5
5
  export type { CanvasPaths, CanvasPathsConfig } from './src/engine/paths'
@@ -14,7 +14,10 @@ export type {
14
14
  SecretResolution,
15
15
  SessionData,
16
16
  ShareEntry,
17
+ SubmittedResponse,
17
18
  } from './src/engine/session'
19
+ export { MAX_SUBMITTED_ANNOTATIONS, submittedAnnotationSchema } from './src/engine/sessionSchemas'
20
+ export type { SubmittedAnnotation } from './src/engine/sessionSchemas'
18
21
  export { unwatchAll, unwatchSession, watchSession } from './src/engine/watcher'
19
22
  export type { WatchOptions } from './src/engine/watcher'
20
23
  export { createWebSocketManager } from './src/engine/websocket'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/canvas-kernel",
3
- "version": "0.9.0-dev.13",
3
+ "version": "0.9.0-dev.14",
4
4
  "type": "module",
5
5
  "description": "Canvas JSX compiler, session/revision store, renderer and interactive component library.",
6
6
  "license": "MIT",
@@ -64,8 +64,8 @@
64
64
  },
65
65
  "dependencies": {
66
66
  "zod": "^3.25.76",
67
- "@fabrika/annotations": "0.9.0-dev.13",
68
- "@fabrika/daemon-kit": "0.9.0-dev.13",
67
+ "@fabrika/annotations": "0.9.0-dev.14",
68
+ "@fabrika/daemon-kit": "0.9.0-dev.14",
69
69
  "marked": "^17.0.4",
70
70
  "mermaid-parser-bundle": "^0.1.2",
71
71
  "preact": "^10.25.0",
@@ -1,16 +1,18 @@
1
1
  import { SessionContext } from '#canvas/runtime'
2
2
  import { AnnotationDraftFooter, AnnotationList, fileAnnotationPath, RESPONSE_ANNOTATION_PATH } from '@fabrika/annotations'
3
3
  import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react'
4
+ import type { SubmittedAnnotation } from '../engine/sessionSchemas'
4
5
  import { findAnnotationElement, scrollToAnnotation } from './annotationDom'
5
6
  import { useAnnotations } from './AnnotationProvider'
6
7
  import type { Annotation } from './AnnotationProvider'
7
8
  import { ActiveViewContext, RevisionContext } from './appContext'
8
9
  import { FileIcon } from './FileIcon'
9
- import { generateMarkdown, getMissingRequiredLabels, hasValue } from './generateMarkdown'
10
+ import { generateMarkdown, getMissingRequiredLabels, hasValue, type SubmittedAnswer, submittedAnswers } from './generateMarkdown'
10
11
  import { useCanvasHost } from './hostContext'
11
12
  import { feedbackResponseSchema } from './persistenceSchemas'
12
13
  import { MarkdownPreview } from './ResponsePreview'
13
14
  import { ResponsePreview } from './ResponsePreview'
15
+ import { ThreadList } from './ThreadList'
14
16
 
15
17
  /**
16
18
  * The canvas host's sidebar: the reusable annotation list and draft footer,
@@ -19,7 +21,8 @@ import { ResponsePreview } from './ResponsePreview'
19
21
  */
20
22
 
21
23
  interface AnnotationSidebarProps {
22
- onSubmit: (feedback: string) => void
24
+ /** `annotations` are the submitted ones a host with threads records; empty for a host without. `answers` are the answered questions. */
25
+ onSubmit: (feedback: string, annotations: readonly SubmittedAnnotation[], answers: SubmittedAnswer[]) => void
23
26
  collapseButton?: React.ReactNode
24
27
  }
25
28
 
@@ -215,6 +218,9 @@ function FeedbackDisplayContent({ sessionId, revision }: { sessionId: string; re
215
218
 
216
219
  return (
217
220
  <div className="flex-1 overflow-y-auto px-4">
221
+ <div className="-mx-4">
222
+ <ThreadList />
223
+ </div>
218
224
  {loading
219
225
  ? <p className="text-[12px] text-text-tertiary font-body py-4">Loading...</p>
220
226
  : feedback
@@ -340,9 +346,14 @@ function AnnotationSidebarInner({ onSubmit, agentWatching, collapseButton }: Omi
340
346
  const hasContent = annotations.length > 0 || generalNote.trim().length > 0 || hasResponses || hasFeedback
341
347
  const [validationError, setValidationError] = useState<string | null>(null)
342
348
 
349
+ const withThreads = host.threads !== null
350
+ const submit = (feedback: string) => {
351
+ // Threads are between the user and the agent; a remote reviewer's note is not one the user can answer for.
352
+ const submitted = withThreads ? annotations.filter((a) => a.source !== 'remote').map(toSubmitted) : []
353
+ onSubmit(feedback, submitted, submittedAnswers(submittableResponses))
354
+ }
343
355
  const submitMarkdown = () => {
344
- const md = generateMarkdown(annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds)
345
- onSubmit(md)
356
+ submit(generateMarkdown(annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds, { annotationIds: withThreads }))
346
357
  }
347
358
 
348
359
  return (
@@ -368,6 +379,7 @@ function AnnotationSidebarInner({ onSubmit, agentWatching, collapseButton }: Omi
368
379
 
369
380
  {/* Annotation list */}
370
381
  <div className="flex-1 overflow-y-auto">
382
+ <ThreadList />
371
383
  {annotations.length === 0 && (
372
384
  <p className="text-[12px] text-text-tertiary px-3 py-4 leading-relaxed font-body">
373
385
  Select text in the canvas or in files to add annotations.
@@ -392,7 +404,7 @@ function AnnotationSidebarInner({ onSubmit, agentWatching, collapseButton }: Omi
392
404
  setValidationError(null)
393
405
  submitMarkdown()
394
406
  }}
395
- onSubmitEmpty={() => onSubmit('No feedback — looks good.')}
407
+ onSubmitEmpty={() => onSubmit('No feedback — looks good.', [], [])}
396
408
  notice={validationError && (
397
409
  <div className="px-4 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2">
398
410
  <span>{validationError}</span>
@@ -420,10 +432,14 @@ function AnnotationSidebarInner({ onSubmit, agentWatching, collapseButton }: Omi
420
432
  <ResponsePreview
421
433
  open={previewOpen}
422
434
  onClose={() => setPreviewOpen(false)}
423
- onSubmit={onSubmit}
435
+ onSubmit={submit}
424
436
  includedRemoteIds={includedRemoteIds}
425
437
  onToggleRemoteId={toggleRemoteId}
426
438
  />
427
439
  </div>
428
440
  )
429
441
  }
442
+
443
+ function toSubmitted(annotation: Annotation): SubmittedAnnotation {
444
+ return { id: annotation.id, snippet: annotation.snippet, note: annotation.note, canvasFile: annotation.canvasFile, filePath: annotation.filePath }
445
+ }
@@ -1,7 +1,8 @@
1
- import { marked } from 'marked'
1
+ import { Marked } from 'marked'
2
2
  import { useEffect, useMemo, useRef, useState } from 'react'
3
3
  import { useAnnotations } from './AnnotationProvider'
4
4
  import { generateMarkdown, getMissingRequiredLabels } from './generateMarkdown'
5
+ import { useCanvasHost } from './hostContext'
5
6
 
6
7
  interface ResponsePreviewProps {
7
8
  open: boolean
@@ -13,6 +14,7 @@ interface ResponsePreviewProps {
13
14
 
14
15
  export function ResponsePreview({ open, onClose, onSubmit, includedRemoteIds, onToggleRemoteId }: ResponsePreviewProps) {
15
16
  const { annotations, generalNote, submittableResponses, feedbackEntries } = useAnnotations()
17
+ const annotationIds = useCanvasHost().threads !== null
16
18
  const [editedText, setEditedText] = useState('')
17
19
  const [manuallyEdited, setManuallyEdited] = useState(false)
18
20
  const [editMode, setEditMode] = useState(false)
@@ -40,8 +42,8 @@ export function ResponsePreview({ open, onClose, onSubmit, includedRemoteIds, on
40
42
  }
41
43
 
42
44
  const generatedText = useMemo(
43
- () => generateMarkdown(annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds),
44
- [annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds],
45
+ () => generateMarkdown(annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds, { annotationIds }),
46
+ [annotations, generalNote, submittableResponses, feedbackEntries, includedRemoteIds, annotationIds],
45
47
  )
46
48
  const text = manuallyEdited ? editedText : generatedText
47
49
 
@@ -198,8 +200,43 @@ function rewriteUploadPaths(md: string): string {
198
200
  return md.replace(UPLOADS_PATH_RE, (_match, alt, _fullPath, filename) => `![${alt}](/api/uploads/${filename})`)
199
201
  }
200
202
 
203
+ const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
204
+ const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char)
205
+ // Text nodes only: an entity there decodes to text, so `&amp;` keeps showing as `&`, as marked shows it.
206
+ const escapeText = (text: string) => text.replace(/&(?!#?\w+;)|[<>"']/g, (char) => HTML_ESCAPES[char] ?? char)
207
+ /** http(s), mailto, or a URL with no scheme of its own. */
208
+ const isSafeUrl = (href: string) => /^(?:https?|mailto):/i.test(href) || !/^[^/?#]*:/.test(href)
209
+ const titleAttribute = (title: string | null | undefined) => (title ? ` title="${escapeHtml(title)}"` : '')
210
+ // URLs are written escaped, so the browser sees the text that was checked and an entity cannot spell a scheme.
211
+ const escapingMarked = new Marked({
212
+ renderer: {
213
+ html: ({ text }) => escapeHtml(text),
214
+ // marked leaves the text after an unclosed `<pre>` or `<script>` tag unescaped; escape every plain text.
215
+ text(token) {
216
+ return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : escapeText(token.text)
217
+ },
218
+ link(token) {
219
+ const text = this.parser.parseInline(token.tokens)
220
+ return isSafeUrl(token.href) ? `<a href="${escapeHtml(token.href)}"${titleAttribute(token.title)}>${text}</a>` : text
221
+ },
222
+ image: (token) =>
223
+ isSafeUrl(token.href)
224
+ ? `<img src="${escapeHtml(token.href)}" alt="${escapeHtml(token.text)}"${titleAttribute(token.title)}>`
225
+ : escapeHtml(token.text),
226
+ },
227
+ })
228
+
229
+ /**
230
+ * Markdown to HTML for text the canvas did not author: feedback, which quotes annotation fields verbatim (a share
231
+ * reviewer's included), and agent responses, which can quote it. Raw HTML shows as text; a link or image whose URL is
232
+ * not http(s), mailto or relative shows as its text. Canvas modules render their own markdown with the shared `marked`.
233
+ */
234
+ export function renderUntrustedMarkdown(markdown: string): string {
235
+ return escapingMarked.parse(markdown, { async: false })
236
+ }
237
+
201
238
  export function MarkdownPreview({ text }: { text: string }) {
202
- const html = useMemo(() => marked.parse(rewriteUploadPaths(text), { async: false }) as string, [text])
203
- // oxlint-disable-next-line react/no-danger -- Canvas modules already execute as code in this document.
239
+ const html = useMemo(() => renderUntrustedMarkdown(rewriteUploadPaths(text)), [text])
240
+ // oxlint-disable-next-line react/no-danger -- renderUntrustedMarkdown escapes raw HTML and drops script URLs.
204
241
  return <div className="prose-canvas font-body text-body text-text-primary leading-relaxed" dangerouslySetInnerHTML={{ __html: html }} />
205
242
  }
@@ -0,0 +1,148 @@
1
+ import { RESPONSE_ANNOTATION_PATH } from '@fabrika/annotations'
2
+ import { useId, useState, useSyncExternalStore } from 'react'
3
+ import { type CanvasThread, type CanvasThreads, useCanvasHost } from './hostContext'
4
+ import { MarkdownPreview } from './ResponsePreview'
5
+
6
+ const NO_THREADS: readonly CanvasThread[] = []
7
+ const noSubscription = () => () => {}
8
+ const noThreads = () => NO_THREADS
9
+
10
+ /** The host's threads, or none when it has no thread store. */
11
+ function useCanvasThreads(): readonly CanvasThread[] {
12
+ const threads = useCanvasHost().threads
13
+ return useSyncExternalStore(threads?.subscribe ?? noSubscription, threads?.current ?? noThreads)
14
+ }
15
+
16
+ const STATE_LABELS: Record<CanvasThread['state'], string> = {
17
+ open: 'Answered',
18
+ queued: 'Reply sent',
19
+ working: 'Agent is on it',
20
+ resolved: 'Resolved',
21
+ }
22
+
23
+ /** Threads the agent opened by answering annotations, in the host's order; resolved ones collapse. */
24
+ export function ThreadList() {
25
+ const store = useCanvasHost().threads
26
+ const threads = useCanvasThreads()
27
+ // Kept here, not in the card, so a draft survives the card moving between the open and resolved lists.
28
+ const [drafts, setDrafts] = useState<ReadonlyMap<string, string>>(() => new Map())
29
+ const setDraft = (threadId: string, draft: string) => setDrafts((current) => new Map(current).set(threadId, draft))
30
+ if (store === null || threads.length === 0) return null
31
+ const active = threads.filter((thread) => thread.state !== 'resolved')
32
+ const resolved = threads.filter((thread) => thread.state === 'resolved')
33
+
34
+ return (
35
+ <section aria-label="Threads" className="px-3 pt-1 pb-3 border-b border-border-subtle">
36
+ <div className="text-[10px] uppercase tracking-widest text-text-tertiary font-body px-1 mb-1">Threads</div>
37
+ {active.map((thread) => (
38
+ <ThreadCard
39
+ key={thread.id}
40
+ thread={thread}
41
+ store={store}
42
+ draft={drafts.get(thread.id) ?? ''}
43
+ onDraft={(draft) => setDraft(thread.id, draft)}
44
+ />
45
+ ))}
46
+ {resolved.length > 0 && (
47
+ <details className="mt-1">
48
+ <summary className="text-[11px] text-text-tertiary font-body px-1 cursor-pointer">Resolved ({resolved.length})</summary>
49
+ {resolved.map((thread) => (
50
+ <ThreadCard
51
+ key={thread.id}
52
+ thread={thread}
53
+ store={store}
54
+ draft={drafts.get(thread.id) ?? ''}
55
+ onDraft={(draft) => setDraft(thread.id, draft)}
56
+ />
57
+ ))}
58
+ </details>
59
+ )}
60
+ </section>
61
+ )
62
+ }
63
+
64
+ interface ThreadCardProps {
65
+ thread: CanvasThread
66
+ store: CanvasThreads
67
+ draft: string
68
+ onDraft: (draft: string) => void
69
+ }
70
+
71
+ function ThreadCard({ thread, store, draft, onDraft }: ThreadCardProps) {
72
+ const replyId = useId()
73
+ const [error, setError] = useState<string | null>(null)
74
+ const [busy, setBusy] = useState(false)
75
+
76
+ const run = async (action: () => Promise<void>) => {
77
+ setBusy(true)
78
+ setError(null)
79
+ try {
80
+ await action()
81
+ } catch (e) {
82
+ setError(e instanceof Error ? e.message : String(e))
83
+ } finally {
84
+ setBusy(false)
85
+ }
86
+ }
87
+
88
+ const send = () =>
89
+ run(async () => {
90
+ await store.reply(thread.id, draft.trim())
91
+ onDraft('')
92
+ })
93
+
94
+ const where = thread.filePath === RESPONSE_ANNOTATION_PATH ? 'Agent response' : thread.filePath ?? thread.canvasFile?.replace(/\.jsx$/, '')
95
+
96
+ return (
97
+ <article className="rounded-lg border border-border-subtle bg-bg-elevated px-3 py-2 mt-2" data-thread-id={thread.id}>
98
+ <div className="flex items-center justify-between gap-2 text-[11px] text-text-tertiary font-body">
99
+ <span className="truncate">{where ? `${where} · ` : ''}Round {thread.revision}</span>
100
+ <span>{STATE_LABELS[thread.state]}</span>
101
+ </div>
102
+ {thread.snippet.trim() && (
103
+ <blockquote className="mt-1 border-l-2 border-border-medium pl-2 text-[12px] text-text-secondary font-body line-clamp-3">
104
+ {thread.snippet}
105
+ </blockquote>
106
+ )}
107
+ <ol className="mt-2 space-y-2">
108
+ {thread.comments.map((comment) => (
109
+ <li key={comment.id} className="text-[13px] font-body">
110
+ <div className="text-[10px] uppercase tracking-widest text-text-tertiary">{comment.author === 'agent' ? 'Agent' : 'You'}</div>
111
+ {/* The agent's markdown is formatted, with any HTML in it shown as text; the user's own is shown as typed. */}
112
+ {comment.author === 'agent'
113
+ ? <MarkdownPreview text={comment.body} />
114
+ : <p className="whitespace-pre-wrap text-text-primary">{comment.body}</p>}
115
+ </li>
116
+ ))}
117
+ </ol>
118
+ <label className="sr-only" htmlFor={replyId}>Reply</label>
119
+ <textarea
120
+ id={replyId}
121
+ value={draft}
122
+ onInput={(event) => onDraft(event.currentTarget.value)}
123
+ placeholder="Reply to the agent"
124
+ rows={2}
125
+ className="mt-2 w-full rounded-md bg-bg-input px-2 py-1.5 text-[13px] font-body text-text-primary"
126
+ />
127
+ {error && <p role="alert" className="text-[12px] text-accent-red font-body">{error}</p>}
128
+ <div className="mt-1 flex justify-end gap-2">
129
+ <button
130
+ type="button"
131
+ disabled={busy}
132
+ onClick={() => run(() => store.setResolved(thread.id, thread.state !== 'resolved'))}
133
+ className="px-2.5 py-1 rounded text-[12px] font-body text-text-secondary hover:text-text-primary"
134
+ >
135
+ {thread.state === 'resolved' ? 'Reopen' : 'Resolve'}
136
+ </button>
137
+ <button
138
+ type="button"
139
+ disabled={busy || draft.trim() === ''}
140
+ onClick={send}
141
+ className="px-2.5 py-1 rounded text-[12px] font-body font-medium bg-btn-primary text-btn-primary-text disabled:opacity-50"
142
+ >
143
+ Send
144
+ </button>
145
+ </div>
146
+ </article>
147
+ )
148
+ }
@@ -39,6 +39,16 @@ export function canPruneResponses(
39
39
  return canvasFiles.every((filename) => renderedCanvases.has(filename))
40
40
  }
41
41
 
42
+ export interface MarkdownOptions {
43
+ /** Labels each local annotation with its id, for a host whose agent answers them one by one; remote ones have no thread. */
44
+ annotationIds?: boolean
45
+ }
46
+
47
+ /** The annotations a submit carries: local ones, and the remote ones the user included. */
48
+ function includedAnnotations(annotations: Annotation[], includedRemoteIds?: Set<string>): Annotation[] {
49
+ return annotations.filter((a) => a.source !== 'remote' || (includedRemoteIds && includedRemoteIds.has(a.id)))
50
+ }
51
+
42
52
  /**
43
53
  * Generate human-readable markdown feedback from annotations and responses.
44
54
  */
@@ -48,9 +58,12 @@ export function generateMarkdown(
48
58
  responses?: Map<string, PlanResponse>,
49
59
  feedbackEntries?: Map<string, FeedbackEntry>,
50
60
  includedRemoteIds?: Set<string>,
61
+ options: MarkdownOptions = {},
51
62
  ): string {
52
63
  const parts: string[] = []
53
- const included = annotations.filter((a) => a.source !== 'remote' || (includedRemoteIds && includedRemoteIds.has(a.id)))
64
+ const included = includedAnnotations(annotations, includedRemoteIds)
65
+ const renderEntry = (ann: Annotation) =>
66
+ options.annotationIds && ann.source !== 'remote' ? `Annotation \`${ann.id}\`\n${renderAnnotation(ann)}` : renderAnnotation(ann)
54
67
  const responseAnns = included.filter((a) => a.filePath === RESPONSE_ANNOTATION_PATH)
55
68
  const canvasAnns = included.filter((a) => !a.filePath)
56
69
  const fileAnns = included.filter((a) => a.filePath && a.filePath !== RESPONSE_ANNOTATION_PATH)
@@ -78,7 +91,7 @@ export function generateMarkdown(
78
91
  parts.push('## Annotations on agent response')
79
92
  parts.push('')
80
93
  for (const ann of responseAnns) {
81
- parts.push(renderAnnotation(ann))
94
+ parts.push(renderEntry(ann))
82
95
  }
83
96
  }
84
97
 
@@ -105,7 +118,7 @@ export function generateMarkdown(
105
118
  parts.push('')
106
119
  }
107
120
  const grouped = groupByHierarchy(anns)
108
- parts.push(renderHierarchyGroup(grouped))
121
+ parts.push(renderHierarchyGroup(grouped, renderEntry))
109
122
  }
110
123
  }
111
124
 
@@ -123,7 +136,7 @@ export function generateMarkdown(
123
136
  parts.push(`### ${filePath}`)
124
137
  parts.push('')
125
138
  for (const ann of anns) {
126
- parts.push(renderAnnotation(ann))
139
+ parts.push(renderEntry(ann))
127
140
  }
128
141
  }
129
142
  }
@@ -139,6 +152,16 @@ export function generateMarkdown(
139
152
  return parts.join('\n').trim() + '\n'
140
153
  }
141
154
 
155
+ /** A submitted answer: the question's id and its value, sent beside the markdown so a host can act on it without parsing prose. */
156
+ export interface SubmittedAnswer {
157
+ id: string
158
+ value: unknown
159
+ }
160
+
161
+ export function submittedAnswers(responses: Map<string, PlanResponse>): SubmittedAnswer[] {
162
+ return Array.from(responses.values()).filter(hasValue).map(({ id, value }) => ({ id, value }))
163
+ }
164
+
142
165
  export function hasValue(r: PlanResponse): boolean {
143
166
  if (r.note?.trim()) return true
144
167
  if (r.value === null || r.value === undefined) return false
@@ -241,16 +264,16 @@ function groupByHierarchy(annotations: Annotation[]): HierarchyNode {
241
264
  return root
242
265
  }
243
266
 
244
- function renderHierarchyGroup(node: HierarchyNode, depth: number = 0): string {
267
+ function renderHierarchyGroup(node: HierarchyNode, renderEntry: (ann: Annotation) => string, depth: number = 0): string {
245
268
  const parts: string[] = []
246
269
  for (const ann of node.annotations) {
247
- parts.push(renderAnnotation(ann))
270
+ parts.push(renderEntry(ann))
248
271
  }
249
272
  for (const [, child] of node.children) {
250
273
  const prefix = depth === 0 ? '###' : '####'
251
274
  parts.push(`${prefix} ${child.label}`)
252
275
  parts.push('')
253
- parts.push(renderHierarchyGroup(child, depth + 1))
276
+ parts.push(renderHierarchyGroup(child, renderEntry, depth + 1))
254
277
  }
255
278
  return parts.join('\n')
256
279
  }
@@ -21,6 +21,40 @@ export interface CanvasHost {
21
21
  uploadUrl: (() => string) | null
22
22
  /** Fetch and `import()` a compiled canvas module. */
23
23
  loadCanvasModule: (filename: string, revision?: number) => Promise<CanvasModule>
24
+ /** Threads the agent opened by answering submitted annotations, or `null` for a host whose agent cannot answer
25
+ * one: the submit then carries no annotation ids and the sidebar shows no threads. */
26
+ threads: CanvasThreads | null
27
+ }
28
+
29
+ /** `open` waits on the user, `queued` holds a reply the agent has not read, `working` is with the agent, `resolved` is closed. */
30
+ export type CanvasThreadState = 'open' | 'queued' | 'working' | 'resolved'
31
+
32
+ export interface CanvasThreadComment {
33
+ id: string
34
+ author: 'user' | 'agent'
35
+ body: string
36
+ createdAt: string
37
+ }
38
+
39
+ /** A conversation on one submitted annotation. It outlives the revision it was submitted on. */
40
+ export interface CanvasThread {
41
+ /** The annotation's id. */
42
+ id: string
43
+ state: CanvasThreadState
44
+ /** The revision the annotation was submitted on. */
45
+ revision: number
46
+ snippet: string
47
+ canvasFile?: string
48
+ filePath?: string
49
+ comments: readonly CanvasThreadComment[]
50
+ }
51
+
52
+ /** A store the sidebar subscribes to; the host keeps it current. */
53
+ export interface CanvasThreads {
54
+ subscribe: (onChange: () => void) => () => void
55
+ current: () => readonly CanvasThread[]
56
+ reply: (threadId: string, body: string) => Promise<void>
57
+ setResolved: (threadId: string, resolved: boolean) => Promise<void>
24
58
  }
25
59
 
26
60
  /** What the canvas compiler emits: one module whose default export renders the canvas. */
@@ -51,6 +85,7 @@ export const localCanvasHost: CanvasHost = {
51
85
  const url = `/api/session/${localSessionId()}/canvas/${encodeURIComponent(jsName)}${query}`
52
86
  return import(/* @vite-ignore */ url)
53
87
  },
88
+ threads: null,
54
89
  }
55
90
 
56
91
  export const CanvasHostContext = createContext<CanvasHost>(localCanvasHost)
@@ -22,6 +22,7 @@ export type {
22
22
  FeedbackEntry,
23
23
  PlanResponse,
24
24
  } from '#canvas/runtime'
25
+ export type { SubmittedAnnotation } from '../engine/sessionSchemas'
25
26
  export { findAnnotationElement, scrollToAnnotation } from './annotationDom'
26
27
  export { annotationDraftKey, carryUnsubmittedDraft, clearPersistedDraft } from './annotationDraft'
27
28
  export type { AnnotationDraftPhase } from './annotationDraft'
@@ -30,6 +31,7 @@ export { ActiveViewContext, RevisionContext } from './appContext'
30
31
  export type { CanvasFileInfo, RevisionInfo } from './appContext'
31
32
  export * as components from './components'
32
33
  export { FileIcon } from './FileIcon'
34
+ export type { SubmittedAnswer } from './generateMarkdown'
33
35
  export {
34
36
  canPruneResponses,
35
37
  generateMarkdown,
@@ -40,9 +42,9 @@ export {
40
42
  pruneStaleResponses,
41
43
  } from './generateMarkdown'
42
44
  export { CanvasHostContext, localCanvasHost, useCanvasHost } from './hostContext'
43
- export type { CanvasHost } from './hostContext'
45
+ export type { CanvasHost, CanvasThread, CanvasThreadComment, CanvasThreads, CanvasThreadState } from './hostContext'
44
46
  export { pageHighlighter } from './pageGlobals'
45
47
  export { PlanRenderer } from './PlanRenderer'
46
48
  export { RenderErrorContext } from './RenderErrorContext'
47
49
  export type { CanvasRenderError } from './RenderErrorContext'
48
- export { MarkdownPreview, ResponsePreview } from './ResponsePreview'
50
+ export { MarkdownPreview, renderUntrustedMarkdown, ResponsePreview } from './ResponsePreview'
@@ -85,7 +85,7 @@
85
85
  /* ── Base styles ── */
86
86
  @layer base {
87
87
  body {
88
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
88
+ font-family: var(--font-body);
89
89
  background-color: var(--color-bg-base);
90
90
  color: var(--color-text-primary);
91
91
  -webkit-font-smoothing: antialiased;
@@ -94,7 +94,7 @@
94
94
  }
95
95
 
96
96
  code, pre, .font-mono {
97
- font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
97
+ font-family: var(--font-mono);
98
98
  }
99
99
 
100
100
  /* Selection color */
@@ -183,26 +183,23 @@ const MOCK_REACT = {
183
183
  StrictMode: Stub,
184
184
  }
185
185
 
186
+ /** One ESM import Bun emits for an external module: a default, namespace or named clause, alone on its line. */
187
+ const IMPORT_LINE = /^import\s+(?:\w+|\*\s+as\s+\w+|\{[^}]*\})\s+from\s+"[^"]+";?$/
188
+ const DEFAULT_EXPORT_TAIL = /(?:export\s*\{\s*(\w+)\s+as\s+default\s*\}|export\s+default\s+(\w+));?\s*$/
189
+
190
+ /**
191
+ * Removes the module syntax of Bun's bundle: each import is a whole line, the default export ends the file. Matching
192
+ * across lines or mid-line would also match string contents, which the bundle holds decoded.
193
+ */
194
+ function stripModuleSyntax(js: string): { code: string; defaultName: string | null } {
195
+ const body = js.split('\n').filter((line) => !IMPORT_LINE.test(line)).join('\n')
196
+ const tail = DEFAULT_EXPORT_TAIL.exec(body)
197
+ if (!tail) return { code: body, defaultName: null }
198
+ return { code: body.slice(0, tail.index), defaultName: tail[1] ?? tail[2] ?? null }
199
+ }
200
+
186
201
  async function validateCompiledPlan(js: string, stubs: Record<string, unknown>): Promise<{ ok: true } | { ok: false; error: string }> {
187
- let code = js
188
-
189
- // Strip ESM import statements
190
- code = code.replace(/import\s+\w+\s+from\s+"[^"]+";?/g, '')
191
- code = code.replace(/import\s+\*\s+as\s+\w+\s+from\s+"[^"]+";?/g, '')
192
- code = code.replace(/import\s*\{[^}]*\}\s*from\s+"[^"]+";?/g, '')
193
-
194
- // Strip export, extract default name
195
- let defaultName: string | null = null
196
- code = code.replace(/export\s*\{\s*(\w+)\s+as\s+default\s*\};?/g, (_, name) => {
197
- defaultName = name
198
- return ''
199
- })
200
- if (!defaultName) {
201
- code = code.replace(/export\s+default\s+(\w+);?/g, (_, name) => {
202
- defaultName = name
203
- return ''
204
- })
205
- }
202
+ const { code, defaultName } = stripModuleSyntax(js)
206
203
 
207
204
  const callDefault = defaultName
208
205
  ? `\nreturn typeof ${defaultName} === "function" ? ${defaultName}() : null;`
@@ -497,6 +494,57 @@ function resolveFilePreviews(jsx: string, projectRoot: string, assertReadable?:
497
494
  )
498
495
  }
499
496
 
497
+ /** A component prop whose string value names a local file. */
498
+ export type FileReferenceProp = readonly [tag: string, prop: string]
499
+
500
+ /** The kernel props that name a local file: what `/api/file` and `/api/image` are asked for when the canvas renders. */
501
+ const FILE_REFERENCE_PROPS: readonly FileReferenceProp[] = [
502
+ ['FilePreview', 'path'],
503
+ ['Markdown', 'file'],
504
+ ['ImageView', 'src'],
505
+ ]
506
+
507
+ /**
508
+ * The paths a canvas names as string literals in `FilePreview path`, `Markdown file`, `ImageView src` and the host's
509
+ * `hostProps`, as written. A path computed at run time is not found, so a host that serves files by this list serves
510
+ * such a path only when it would serve it anyway.
511
+ */
512
+ export function canvasFileReferences(jsx: string, hostProps: readonly FileReferenceProp[] = []): string[] {
513
+ const references = new Set<string>()
514
+ for (const [tag, prop] of [...FILE_REFERENCE_PROPS, ...hostProps]) {
515
+ const valuePattern = new RegExp(`(?:^|\\s)${prop}=(?:"([^"]+)"|'([^']+)'|\\{\\s*(?:"([^"]+)"|'([^']+)')\\s*\\})`)
516
+ for (const start of jsx.matchAll(new RegExp(`<${tag}\\b`, 'g'))) {
517
+ const from = start.index + start[0].length
518
+ const path = jsx.slice(from, tagEnd(jsx, from)).match(valuePattern)?.slice(1).find((group) => group !== undefined)
519
+ if (path !== undefined) references.add(path)
520
+ }
521
+ }
522
+ return [...references]
523
+ }
524
+
525
+ /** Where the opening tag whose attributes start at `from` ends: the first `>` (or a stray `<`) outside a quoted or `{…}` value. */
526
+ function tagEnd(jsx: string, from: number): number {
527
+ let quote: string | null = null
528
+ let depth = 0
529
+ for (let index = from; index < jsx.length; index++) {
530
+ const char = jsx[index]
531
+ if (quote !== null) {
532
+ if (char === quote) quote = null
533
+ } else if (char === '"' || char === "'" || char === '`') {
534
+ quote = char
535
+ } else if (char === '{') {
536
+ depth++
537
+ } else if (char === '}') {
538
+ depth--
539
+ } else if (char === '>' && depth === 0) {
540
+ return index
541
+ } else if (char === '<' && depth === 0) {
542
+ return index
543
+ }
544
+ }
545
+ return jsx.length
546
+ }
547
+
500
548
  /** @deprecated Use `compileJsx(jsx, { projectRoot, tempDir })`. */
501
549
  export async function compilePlan(jsx: string, projectRoot?: string): Promise<CompileResult> {
502
550
  return compileJsx(jsx, { projectRoot })
@@ -1,6 +1,14 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
- import { remoteFeedbackSchema, savedSessionMetadataSchema } from './sessionSchemas'
3
+ import { z } from 'zod'
4
+ import {
5
+ remoteFeedbackSchema,
6
+ savedSessionMetadataSchema,
7
+ type SubmittedAnnotation,
8
+ submittedAnnotationsSchema,
9
+ submittedResponseSchema,
10
+ submittedResponsesSchema,
11
+ } from './sessionSchemas'
4
12
 
5
13
  export interface DiffStats {
6
14
  added: number
@@ -35,6 +43,8 @@ export interface RevisionInfo {
35
43
  * the author's own annotations. `annotations` is the structured list of
36
44
  * highlighted-text comments; `generalNote` is the free-form markdown.
37
45
  */
46
+ export type SubmittedResponse = z.output<typeof submittedResponseSchema>
47
+
38
48
  export interface RemoteFeedbackEntry {
39
49
  /** Stable unique id assigned by the worker; used to dedupe on re-poll */
40
50
  id: string
@@ -449,10 +459,22 @@ export class SessionManager {
449
459
  }
450
460
  }
451
461
 
452
- saveFeedback(id: string, rev: number, markdown: string) {
462
+ /**
463
+ * `annotations` are the ones the feedback carries, kept so a host can open a thread on one later; `responses` are its answered questions.
464
+ * Both are written on every submission, so a later one never inherits an earlier one's.
465
+ */
466
+ saveFeedback(
467
+ id: string,
468
+ rev: number,
469
+ markdown: string,
470
+ annotations: readonly SubmittedAnnotation[] = [],
471
+ responses: readonly SubmittedResponse[] = [],
472
+ ) {
453
473
  const revDir = this.revisionDir(id, rev)
454
474
  mkdirSync(revDir, { recursive: true })
455
475
  writeFileSync(join(revDir, 'feedback.md'), markdown)
476
+ writeFileSync(join(revDir, 'annotations.json'), JSON.stringify(annotations, null, 2))
477
+ writeFileSync(join(revDir, 'feedback-responses.json'), JSON.stringify(responses))
456
478
 
457
479
  const session = this.sessions.get(id)
458
480
  if (session) {
@@ -468,6 +490,49 @@ export class SessionManager {
468
490
  }
469
491
  }
470
492
 
493
+ /** Where a host keeps files the user handed to this session; removed with the session. */
494
+ assetsDir(id: string): string {
495
+ return join(this.sessionDir(id), 'assets')
496
+ }
497
+
498
+ /** The latest submitted annotation with this id, and the revision it was submitted on. */
499
+ findSubmittedAnnotation(id: string, annotationId: string): { revision: number; annotation: SubmittedAnnotation } | null {
500
+ const session = this.sessions.get(id)
501
+ if (!session) return null
502
+ for (let i = session.revisions.length - 1; i >= 0; i--) {
503
+ const revision = session.revisions[i]?.revision
504
+ if (revision === undefined) continue
505
+ const annotation = this.getSubmittedAnnotations(id, revision).find((candidate) => candidate.id === annotationId)
506
+ if (annotation) return { revision, annotation }
507
+ }
508
+ return null
509
+ }
510
+
511
+ getSubmittedAnnotations(id: string, rev: number): SubmittedAnnotation[] {
512
+ const file = join(this.revisionDir(id, rev), 'annotations.json')
513
+ if (!existsSync(file)) return []
514
+ return submittedAnnotationsSchema.parse(JSON.parse(readFileSync(file, 'utf-8')))
515
+ }
516
+
517
+ /**
518
+ * The host's threads on this session's annotations, kept beside the session so they outlive revisions and go
519
+ * with the session. Opaque payload — the shape is the host's.
520
+ */
521
+ saveThreads(id: string, payload: unknown): void {
522
+ const dir = this.sessionDir(id)
523
+ mkdirSync(dir, { recursive: true })
524
+ const file = join(dir, 'threads.json')
525
+ const temporary = `${file}.${process.pid}.tmp`
526
+ writeFileSync(temporary, JSON.stringify(payload, null, 2))
527
+ renameSync(temporary, file)
528
+ }
529
+
530
+ getThreads(id: string): unknown | null {
531
+ const file = join(this.sessionDir(id), 'threads.json')
532
+ if (!existsSync(file)) return null
533
+ return JSON.parse(readFileSync(file, 'utf-8'))
534
+ }
535
+
471
536
  getFeedback(id: string, rev: number): string | null {
472
537
  try {
473
538
  return readFileSync(join(this.revisionDir(id, rev), 'feedback.md'), 'utf-8')
@@ -476,6 +541,22 @@ export class SessionManager {
476
541
  }
477
542
  }
478
543
 
544
+ /** The structured answers of the revision's latest submission; empty when none were sent. */
545
+ getSubmittedResponses(id: string, rev: number): SubmittedResponse[] {
546
+ let raw: string
547
+ try {
548
+ raw = readFileSync(join(this.revisionDir(id, rev), 'feedback-responses.json'), 'utf-8')
549
+ } catch {
550
+ return []
551
+ }
552
+ try {
553
+ const parsed = submittedResponsesSchema.safeParse(JSON.parse(raw))
554
+ return parsed.success ? parsed.data : []
555
+ } catch {
556
+ return []
557
+ }
558
+ }
559
+
479
560
  consumeFeedback(id: string, rev: number) {
480
561
  const session = this.sessions.get(id)
481
562
  if (!session) return
@@ -69,3 +69,35 @@ export const remoteFeedbackEntrySchema = z.object({
69
69
 
70
70
  export const remoteFeedbackSchema = z.array(remoteFeedbackEntrySchema.optional().catch(undefined))
71
71
  .transform(entries => entries.filter(entry => entry !== undefined)).catch([])
72
+
73
+ /** What a submit says about each annotation it carried: enough for the host to open a thread on it later. */
74
+ export const submittedAnnotationSchema = z.object({
75
+ id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),
76
+ snippet: z.string().max(20_000),
77
+ note: z.string().max(20_000),
78
+ canvasFile: z.string().max(500).optional(),
79
+ filePath: z.string().max(4_000).optional(),
80
+ })
81
+ export type SubmittedAnnotation = z.infer<typeof submittedAnnotationSchema>
82
+
83
+ export const MAX_SUBMITTED_ANNOTATIONS = 500
84
+ export const submittedAnnotationsSchema = z.array(submittedAnnotationSchema).max(MAX_SUBMITTED_ANNOTATIONS)
85
+
86
+ // A submit is the user's feedback: an annotation the host cannot thread is left out, the feedback is still saved.
87
+ export const submittedAnnotationsFrameSchema = z.array(submittedAnnotationSchema.optional().catch(undefined))
88
+ .transform(entries => entries.filter(entry => entry !== undefined).slice(0, MAX_SUBMITTED_ANNOTATIONS))
89
+ .catch([])
90
+
91
+ /** One answered question of a submitted review, kept beside the feedback markdown so a host can act on it without parsing prose. */
92
+ export const submittedResponseSchema = z.object({
93
+ id: z.string(),
94
+ value: z.union([z.string(), z.array(z.string()), z.number()]),
95
+ })
96
+
97
+ // A malformed answer is dropped, not the submission: the markdown still carries every answer.
98
+ export const submittedResponsesSchema = z.array(z.unknown()).transform(list =>
99
+ list.flatMap(response => {
100
+ const parsed = submittedResponseSchema.safeParse(response)
101
+ return parsed.success ? [parsed.data] : []
102
+ })
103
+ )
@@ -6,7 +6,8 @@
6
6
 
7
7
  import { type ChannelSocket, createNotificationChannel, type TopicChannel } from '@fabrika/daemon-kit'
8
8
  import { z } from 'zod'
9
- import type { RemoteFeedbackEntry, SessionManager } from './session'
9
+ import type { RemoteFeedbackEntry, SessionManager, SubmittedResponse } from './session'
10
+ import { type SubmittedAnnotation, submittedAnnotationsFrameSchema, submittedResponsesSchema } from './sessionSchemas'
10
11
 
11
12
  export type WSData = { type: 'browser' | 'wait'; sessionId: string }
12
13
 
@@ -25,6 +26,8 @@ interface CanvasRenderError {
25
26
  interface SubmitFrame {
26
27
  type: 'submit'
27
28
  feedback: string
29
+ annotations?: SubmittedAnnotation[]
30
+ responses?: SubmittedResponse[]
28
31
  }
29
32
 
30
33
  interface RenderErrorFrame {
@@ -33,7 +36,12 @@ interface RenderErrorFrame {
33
36
  }
34
37
 
35
38
  const browserFrameSchema = z.discriminatedUnion('type', [
36
- z.object({ type: z.literal('submit'), feedback: z.string() }).passthrough(),
39
+ z.object({
40
+ type: z.literal('submit'),
41
+ feedback: z.string(),
42
+ annotations: submittedAnnotationsFrameSchema.optional(),
43
+ responses: submittedResponsesSchema.optional().catch(undefined),
44
+ }).passthrough(),
37
45
  z.object({
38
46
  type: z.literal('render-error'),
39
47
  error: z.object({
@@ -80,7 +88,7 @@ export function createWebSocketManager(
80
88
  const session = sessionManager.get(sessionId)
81
89
  if (!session) return
82
90
 
83
- sessionManager.saveFeedback(sessionId, session.currentRevision, frame.feedback)
91
+ sessionManager.saveFeedback(sessionId, session.currentRevision, frame.feedback, frame.annotations, frame.responses)
84
92
  broadcastRevisionUpdate(sessionId)
85
93
  if (!topic.hasWaiter()) return
86
94
 
@@ -88,7 +96,7 @@ export function createWebSocketManager(
88
96
  sessionManager.consumeFeedback(sessionId, session.currentRevision)
89
97
  broadcastRevisionUpdate(sessionId)
90
98
  }
91
- topic.relayToWaiters({ type: 'submit', feedback: frame.feedback })
99
+ topic.relayToWaiters({ type: 'submit', feedback: frame.feedback, responses: frame.responses ?? [] })
92
100
  }
93
101
 
94
102
  function renderError(frame: RenderErrorFrame, topic: TopicChannel) {
@@ -151,11 +159,26 @@ export function createWebSocketManager(
151
159
  channel.broadcastPresence(sessionId)
152
160
  }
153
161
 
162
+ /** A host's own frame to the session's browsers. */
163
+ function broadcast(sessionId: string, frame: unknown) {
164
+ channel.broadcast(sessionId, frame)
165
+ }
166
+
167
+ /**
168
+ * A host's own frame to the session's waiters. It does not end their wait: a one-shot waiter decides itself
169
+ * whether the frame answers it. `false` when nobody was waiting.
170
+ */
171
+ function notifyWaiters(sessionId: string, frame: unknown): boolean {
172
+ return channel.relayToWaiters(sessionId, frame, { close: false })
173
+ }
174
+
154
175
  return {
155
176
  handlers: channel.handlers,
156
177
  broadcastPlanUpdate,
157
178
  broadcastRevisionUpdate,
158
179
  broadcastWatcherStatus,
159
180
  broadcastRemoteFeedback,
181
+ broadcast,
182
+ notifyWaiters,
160
183
  }
161
184
  }
package/types/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- export { compileJsx, compilePlan, KERNEL_COMPONENTS } from './src/engine/compiler';
2
- export type { CanvasComponents, CanvasComponentSpec, CompileOptions, CompileResult } from './src/engine/compiler';
1
+ export { canvasFileReferences, compileJsx, compilePlan, KERNEL_COMPONENTS } from './src/engine/compiler';
2
+ export type { CanvasComponents, CanvasComponentSpec, CompileOptions, CompileResult, FileReferenceProp } from './src/engine/compiler';
3
3
  export type { AssertReadable } from './src/engine/file-admission';
4
4
  export { createCanvasPaths } from './src/engine/paths';
5
5
  export type { CanvasPaths, CanvasPathsConfig } from './src/engine/paths';
6
6
  export { SessionManager } from './src/engine/session';
7
- export type { CanvasFileInfo, CanvasScope, DiffStats, RemoteAnnotation, RemoteFeedbackEntry, RevisionInfo, SecretResolution, SessionData, ShareEntry, } from './src/engine/session';
7
+ export type { CanvasFileInfo, CanvasScope, DiffStats, RemoteAnnotation, RemoteFeedbackEntry, RevisionInfo, SecretResolution, SessionData, ShareEntry, SubmittedResponse, } from './src/engine/session';
8
+ export { MAX_SUBMITTED_ANNOTATIONS, submittedAnnotationSchema } from './src/engine/sessionSchemas';
9
+ export type { SubmittedAnnotation } from './src/engine/sessionSchemas';
8
10
  export { unwatchAll, unwatchSession, watchSession } from './src/engine/watcher';
9
11
  export type { WatchOptions } from './src/engine/watcher';
10
12
  export { createWebSocketManager } from './src/engine/websocket';
@@ -1,11 +1,14 @@
1
1
  import React from 'react';
2
+ import type { SubmittedAnnotation } from '../engine/sessionSchemas';
3
+ import { type SubmittedAnswer } from './generateMarkdown';
2
4
  /**
3
5
  * The canvas host's sidebar: the reusable annotation list and draft footer,
4
6
  * wrapped in the chrome only a canvas has — revisions, per-revision feedback,
5
7
  * canvas files, agent responses, and the wait for the agent to come back.
6
8
  */
7
9
  interface AnnotationSidebarProps {
8
- onSubmit: (feedback: string) => void;
10
+ /** `annotations` are the submitted ones a host with threads records; empty for a host without. `answers` are the answered questions. */
11
+ onSubmit: (feedback: string, annotations: readonly SubmittedAnnotation[], answers: SubmittedAnswer[]) => void;
9
12
  collapseButton?: React.ReactNode;
10
13
  }
11
14
  export declare function AnnotationSidebar({ onSubmit, collapseButton }: AnnotationSidebarProps): React.JSX.Element;
@@ -6,6 +6,12 @@ interface ResponsePreviewProps {
6
6
  onToggleRemoteId: (id: string) => void;
7
7
  }
8
8
  export declare function ResponsePreview({ open, onClose, onSubmit, includedRemoteIds, onToggleRemoteId }: ResponsePreviewProps): import("react").JSX.Element | null;
9
+ /**
10
+ * Markdown to HTML for text the canvas did not author: feedback, which quotes annotation fields verbatim (a share
11
+ * reviewer's included), and agent responses, which can quote it. Raw HTML shows as text; a link or image whose URL is
12
+ * not http(s), mailto or relative shows as its text. Canvas modules render their own markdown with the shared `marked`.
13
+ */
14
+ export declare function renderUntrustedMarkdown(markdown: string): string;
9
15
  export declare function MarkdownPreview({ text }: {
10
16
  text: string;
11
17
  }): import("react").JSX.Element;
@@ -0,0 +1,2 @@
1
+ /** Threads the agent opened by answering annotations, in the host's order; resolved ones collapse. */
2
+ export declare function ThreadList(): import("react").JSX.Element | null;
@@ -18,10 +18,20 @@ export declare function pruneStaleResponses(responses: Map<string, PlanResponse>
18
18
  * pruning early would throw away every answer the author gave.
19
19
  */
20
20
  export declare function canPruneResponses(canvasFiles: readonly string[] | undefined, renderedCanvases: ReadonlySet<string>): boolean;
21
+ export interface MarkdownOptions {
22
+ /** Labels each local annotation with its id, for a host whose agent answers them one by one; remote ones have no thread. */
23
+ annotationIds?: boolean;
24
+ }
21
25
  /**
22
26
  * Generate human-readable markdown feedback from annotations and responses.
23
27
  */
24
- export declare function generateMarkdown(annotations: Annotation[], generalNote: string, responses?: Map<string, PlanResponse>, feedbackEntries?: Map<string, FeedbackEntry>, includedRemoteIds?: Set<string>): string;
28
+ export declare function generateMarkdown(annotations: Annotation[], generalNote: string, responses?: Map<string, PlanResponse>, feedbackEntries?: Map<string, FeedbackEntry>, includedRemoteIds?: Set<string>, options?: MarkdownOptions): string;
29
+ /** A submitted answer: the question's id and its value, sent beside the markdown so a host can act on it without parsing prose. */
30
+ export interface SubmittedAnswer {
31
+ id: string;
32
+ value: unknown;
33
+ }
34
+ export declare function submittedAnswers(responses: Map<string, PlanResponse>): SubmittedAnswer[];
25
35
  export declare function hasValue(r: PlanResponse): boolean;
26
36
  export declare function getMissingRequired(responses: Map<string, PlanResponse>): PlanResponse[];
27
37
  export declare function getMissingRequiredFeedback(entries: Map<string, FeedbackEntry>): FeedbackEntry[];
@@ -20,6 +20,36 @@ export interface CanvasHost {
20
20
  uploadUrl: (() => string) | null;
21
21
  /** Fetch and `import()` a compiled canvas module. */
22
22
  loadCanvasModule: (filename: string, revision?: number) => Promise<CanvasModule>;
23
+ /** Threads the agent opened by answering submitted annotations, or `null` for a host whose agent cannot answer
24
+ * one: the submit then carries no annotation ids and the sidebar shows no threads. */
25
+ threads: CanvasThreads | null;
26
+ }
27
+ /** `open` waits on the user, `queued` holds a reply the agent has not read, `working` is with the agent, `resolved` is closed. */
28
+ export type CanvasThreadState = 'open' | 'queued' | 'working' | 'resolved';
29
+ export interface CanvasThreadComment {
30
+ id: string;
31
+ author: 'user' | 'agent';
32
+ body: string;
33
+ createdAt: string;
34
+ }
35
+ /** A conversation on one submitted annotation. It outlives the revision it was submitted on. */
36
+ export interface CanvasThread {
37
+ /** The annotation's id. */
38
+ id: string;
39
+ state: CanvasThreadState;
40
+ /** The revision the annotation was submitted on. */
41
+ revision: number;
42
+ snippet: string;
43
+ canvasFile?: string;
44
+ filePath?: string;
45
+ comments: readonly CanvasThreadComment[];
46
+ }
47
+ /** A store the sidebar subscribes to; the host keeps it current. */
48
+ export interface CanvasThreads {
49
+ subscribe: (onChange: () => void) => () => void;
50
+ current: () => readonly CanvasThread[];
51
+ reply: (threadId: string, body: string) => Promise<void>;
52
+ setResolved: (threadId: string, resolved: boolean) => Promise<void>;
23
53
  }
24
54
  /** What the canvas compiler emits: one module whose default export renders the canvas. */
25
55
  export interface CanvasModule {
@@ -3,6 +3,7 @@ export type { PersistedState } from './AnnotationProvider';
3
3
  export { feedbackEntrySchema, filePreviewResponseSchema, parsePersistedState, persistedStateSchema, planResponseSchema } from './persistenceSchemas';
4
4
  export { ActiveViewCtx, AnnotationCtx, CanvasFileCtx, SessionContext, useAnnotations, useCanvasFile, useFeedback, useResponseRegistration, } from '#canvas/runtime';
5
5
  export type { ActiveView, Annotation, AnnotationAttachment, AnnotationAuthor, AnnotationContext, AnnotationContextValue, FeedbackEntry, PlanResponse, } from '#canvas/runtime';
6
+ export type { SubmittedAnnotation } from '../engine/sessionSchemas';
6
7
  export { findAnnotationElement, scrollToAnnotation } from './annotationDom';
7
8
  export { annotationDraftKey, carryUnsubmittedDraft, clearPersistedDraft } from './annotationDraft';
8
9
  export type { AnnotationDraftPhase } from './annotationDraft';
@@ -11,11 +12,12 @@ export { ActiveViewContext, RevisionContext } from './appContext';
11
12
  export type { CanvasFileInfo, RevisionInfo } from './appContext';
12
13
  export * as components from './components';
13
14
  export { FileIcon } from './FileIcon';
15
+ export type { SubmittedAnswer } from './generateMarkdown';
14
16
  export { canPruneResponses, generateMarkdown, getMissingRequired, getMissingRequiredFeedback, getMissingRequiredLabels, hasValue, pruneStaleResponses, } from './generateMarkdown';
15
17
  export { CanvasHostContext, localCanvasHost, useCanvasHost } from './hostContext';
16
- export type { CanvasHost } from './hostContext';
18
+ export type { CanvasHost, CanvasThread, CanvasThreadComment, CanvasThreads, CanvasThreadState } from './hostContext';
17
19
  export { pageHighlighter } from './pageGlobals';
18
20
  export { PlanRenderer } from './PlanRenderer';
19
21
  export { RenderErrorContext } from './RenderErrorContext';
20
22
  export type { CanvasRenderError } from './RenderErrorContext';
21
- export { MarkdownPreview, ResponsePreview } from './ResponsePreview';
23
+ export { MarkdownPreview, renderUntrustedMarkdown, ResponsePreview } from './ResponsePreview';
@@ -39,6 +39,14 @@ export interface CompileOptions {
39
39
  components?: CanvasComponents;
40
40
  }
41
41
  export declare function compileJsx(jsx: string, options?: CompileOptions): Promise<CompileResult>;
42
+ /** A component prop whose string value names a local file. */
43
+ export type FileReferenceProp = readonly [tag: string, prop: string];
44
+ /**
45
+ * The paths a canvas names as string literals in `FilePreview path`, `Markdown file`, `ImageView src` and the host's
46
+ * `hostProps`, as written. A path computed at run time is not found, so a host that serves files by this list serves
47
+ * such a path only when it would serve it anyway.
48
+ */
49
+ export declare function canvasFileReferences(jsx: string, hostProps?: readonly FileReferenceProp[]): string[];
42
50
  /** @deprecated Use `compileJsx(jsx, { projectRoot, tempDir })`. */
43
51
  export declare function compilePlan(jsx: string, projectRoot?: string): Promise<CompileResult>;
44
52
  export {};
@@ -1,3 +1,5 @@
1
+ import { z } from 'zod';
2
+ import { type SubmittedAnnotation, submittedResponseSchema } from './sessionSchemas';
1
3
  export interface DiffStats {
2
4
  added: number;
3
5
  removed: number;
@@ -30,6 +32,7 @@ export interface RevisionInfo {
30
32
  * the author's own annotations. `annotations` is the structured list of
31
33
  * highlighted-text comments; `generalNote` is the free-form markdown.
32
34
  */
35
+ export type SubmittedResponse = z.output<typeof submittedResponseSchema>;
33
36
  export interface RemoteFeedbackEntry {
34
37
  /** Stable unique id assigned by the worker; used to dedupe on re-poll */
35
38
  id: string;
@@ -148,8 +151,28 @@ export declare class SessionManager {
148
151
  resolveSecrets(id: string, fieldIds: string[]): SecretResolution | null;
149
152
  saveCompiled(id: string, filename: string, js: string, rev?: number): void;
150
153
  getCompiled(id: string, filename: string, rev?: number): string | null;
151
- saveFeedback(id: string, rev: number, markdown: string): void;
154
+ /**
155
+ * `annotations` are the ones the feedback carries, kept so a host can open a thread on one later; `responses` are its answered questions.
156
+ * Both are written on every submission, so a later one never inherits an earlier one's.
157
+ */
158
+ saveFeedback(id: string, rev: number, markdown: string, annotations?: readonly SubmittedAnnotation[], responses?: readonly SubmittedResponse[]): void;
159
+ /** Where a host keeps files the user handed to this session; removed with the session. */
160
+ assetsDir(id: string): string;
161
+ /** The latest submitted annotation with this id, and the revision it was submitted on. */
162
+ findSubmittedAnnotation(id: string, annotationId: string): {
163
+ revision: number;
164
+ annotation: SubmittedAnnotation;
165
+ } | null;
166
+ getSubmittedAnnotations(id: string, rev: number): SubmittedAnnotation[];
167
+ /**
168
+ * The host's threads on this session's annotations, kept beside the session so they outlive revisions and go
169
+ * with the session. Opaque payload — the shape is the host's.
170
+ */
171
+ saveThreads(id: string, payload: unknown): void;
172
+ getThreads(id: string): unknown | null;
152
173
  getFeedback(id: string, rev: number): string | null;
174
+ /** The structured answers of the revision's latest submission; empty when none were sent. */
175
+ getSubmittedResponses(id: string, rev: number): SubmittedResponse[];
153
176
  consumeFeedback(id: string, rev: number): void;
154
177
  getLatestUnconsumedFeedback(id: string): {
155
178
  revision: number;
@@ -2628,3 +2628,84 @@ export declare const remoteFeedbackSchema: z.ZodCatch<z.ZodEffects<z.ZodArray<z.
2628
2628
  }, "source" | "images" | "author">, z.ZodTypeAny, "passthrough">[], unknown[]>;
2629
2629
  generalNote: z.ZodOptional<z.ZodString>;
2630
2630
  }, z.ZodTypeAny, "passthrough">[], unknown[]>>;
2631
+ /** What a submit says about each annotation it carried: enough for the host to open a thread on it later. */
2632
+ export declare const submittedAnnotationSchema: z.ZodObject<{
2633
+ id: z.ZodString;
2634
+ snippet: z.ZodString;
2635
+ note: z.ZodString;
2636
+ canvasFile: z.ZodOptional<z.ZodString>;
2637
+ filePath: z.ZodOptional<z.ZodString>;
2638
+ }, "strip", z.ZodTypeAny, {
2639
+ id: string;
2640
+ note: string;
2641
+ snippet: string;
2642
+ filePath?: string | undefined;
2643
+ canvasFile?: string | undefined;
2644
+ }, {
2645
+ id: string;
2646
+ note: string;
2647
+ snippet: string;
2648
+ filePath?: string | undefined;
2649
+ canvasFile?: string | undefined;
2650
+ }>;
2651
+ export type SubmittedAnnotation = z.infer<typeof submittedAnnotationSchema>;
2652
+ export declare const MAX_SUBMITTED_ANNOTATIONS = 500;
2653
+ export declare const submittedAnnotationsSchema: z.ZodArray<z.ZodObject<{
2654
+ id: z.ZodString;
2655
+ snippet: z.ZodString;
2656
+ note: z.ZodString;
2657
+ canvasFile: z.ZodOptional<z.ZodString>;
2658
+ filePath: z.ZodOptional<z.ZodString>;
2659
+ }, "strip", z.ZodTypeAny, {
2660
+ id: string;
2661
+ note: string;
2662
+ snippet: string;
2663
+ filePath?: string | undefined;
2664
+ canvasFile?: string | undefined;
2665
+ }, {
2666
+ id: string;
2667
+ note: string;
2668
+ snippet: string;
2669
+ filePath?: string | undefined;
2670
+ canvasFile?: string | undefined;
2671
+ }>, "many">;
2672
+ export declare const submittedAnnotationsFrameSchema: z.ZodCatch<z.ZodEffects<z.ZodArray<z.ZodCatch<z.ZodOptional<z.ZodObject<{
2673
+ id: z.ZodString;
2674
+ snippet: z.ZodString;
2675
+ note: z.ZodString;
2676
+ canvasFile: z.ZodOptional<z.ZodString>;
2677
+ filePath: z.ZodOptional<z.ZodString>;
2678
+ }, "strip", z.ZodTypeAny, {
2679
+ id: string;
2680
+ note: string;
2681
+ snippet: string;
2682
+ filePath?: string | undefined;
2683
+ canvasFile?: string | undefined;
2684
+ }, {
2685
+ id: string;
2686
+ note: string;
2687
+ snippet: string;
2688
+ filePath?: string | undefined;
2689
+ canvasFile?: string | undefined;
2690
+ }>>>, "many">, {
2691
+ id: string;
2692
+ note: string;
2693
+ snippet: string;
2694
+ filePath?: string | undefined;
2695
+ canvasFile?: string | undefined;
2696
+ }[], unknown[]>>;
2697
+ /** One answered question of a submitted review, kept beside the feedback markdown so a host can act on it without parsing prose. */
2698
+ export declare const submittedResponseSchema: z.ZodObject<{
2699
+ id: z.ZodString;
2700
+ value: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">, z.ZodNumber]>;
2701
+ }, "strip", z.ZodTypeAny, {
2702
+ id: string;
2703
+ value: string | number | string[];
2704
+ }, {
2705
+ id: string;
2706
+ value: string | number | string[];
2707
+ }>;
2708
+ export declare const submittedResponsesSchema: z.ZodEffects<z.ZodArray<z.ZodUnknown, "many">, {
2709
+ id: string;
2710
+ value: string | number | string[];
2711
+ }[], unknown[]>;
@@ -35,4 +35,6 @@ export declare function createWebSocketManager(sessionManager: SessionManager, o
35
35
  broadcastRevisionUpdate: (sessionId: string) => void;
36
36
  broadcastWatcherStatus: (sessionId: string) => void;
37
37
  broadcastRemoteFeedback: (sessionId: string, revision: number, entries: RemoteFeedbackEntry[]) => void;
38
+ broadcast: (sessionId: string, frame: unknown) => void;
39
+ notifyWaiters: (sessionId: string, frame: unknown) => boolean;
38
40
  };