@linxin666/dsh-client-ui-task-board 0.4.12 → 0.4.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.i18n.yaml +2 -2
  2. package/README.md +9 -3
  3. package/README.zh.md +9 -3
  4. package/lib/client.js +1476 -478
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1280 -65
  7. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  8. package/lib/types/client/board/model-options.d.ts +21 -1
  9. package/lib/types/client/board/source-group.d.ts +27 -0
  10. package/lib/types/client/host-api.d.ts +25 -0
  11. package/lib/types/client/locales.d.ts +17 -0
  12. package/lib/types/client/pending-verify.d.ts +47 -0
  13. package/lib/types/client/service.d.ts +4 -1
  14. package/lib/types/core/attachment.d.ts +132 -0
  15. package/lib/types/core/controller.d.ts +26 -2
  16. package/lib/types/core/extension.d.ts +82 -0
  17. package/lib/types/core/session-reuse.d.ts +7 -1
  18. package/lib/types/core/tasks.d.ts +38 -1
  19. package/lib/types/core/use-cases/task-update.d.ts +21 -0
  20. package/lib/types/core/wire-projection.d.ts +35 -0
  21. package/lib/types/host/attachments.d.ts +250 -0
  22. package/lib/types/host/extension-registry.d.ts +40 -0
  23. package/lib/types/host-ledger.d.ts +16 -0
  24. package/lib/types/host-routes.d.ts +14 -0
  25. package/lib/types/host-runner.d.ts +53 -1
  26. package/lib/types/host-service.d.ts +59 -0
  27. package/lib/types/index.d.ts +23 -0
  28. package/lib/types/protocol.d.ts +39 -6
  29. package/locale/en.json +6 -0
  30. package/locale/zh.json +6 -0
  31. package/package.json +6 -2
  32. package/src/client/TaskBoardSettingsCard.tsx +11 -1
  33. package/src/client/board/AttachmentField.tsx +383 -0
  34. package/src/client/board/EditTaskModal.tsx +63 -0
  35. package/src/client/board/NewTaskModal.tsx +76 -4
  36. package/src/client/board/TaskBoard.tsx +47 -10
  37. package/src/client/board/TaskDetail.tsx +30 -2
  38. package/src/client/board/model-options.ts +32 -2
  39. package/src/client/board/source-group.ts +94 -0
  40. package/src/client/board.module.css +83 -0
  41. package/src/client/host-api.ts +70 -0
  42. package/src/client/index.ts +11 -0
  43. package/src/client/locales.ts +34 -0
  44. package/src/client/pending-verify.ts +90 -0
  45. package/src/client/service.ts +24 -0
  46. package/src/core/attachment.ts +287 -0
  47. package/src/core/controller.ts +47 -1
  48. package/src/core/extension.ts +86 -0
  49. package/src/core/session-reuse.ts +7 -1
  50. package/src/core/store.ts +10 -1
  51. package/src/core/tasks.ts +49 -0
  52. package/src/core/use-cases/task-update.ts +27 -2
  53. package/src/core/wire-projection.ts +81 -0
  54. package/src/host/attachments.ts +650 -0
  55. package/src/host/extension-registry.ts +150 -5
  56. package/src/host-ledger.ts +32 -4
  57. package/src/host-routes.ts +168 -13
  58. package/src/host-runner.ts +124 -4
  59. package/src/host-service.ts +165 -12
  60. package/src/index.ts +47 -0
  61. package/src/protocol.ts +57 -9
@@ -15,6 +15,7 @@ import type { TaskBoardAction, TaskBoardSnapshot } from '../protocol.ts'
15
15
  import { canEditTaskContent } from '../core/use-cases/task-update.ts'
16
16
  import {
17
17
  TASK_BOARD_API_VERSION,
18
+ TASK_BOARD_MESSAGE_MAX_LENGTH,
18
19
  isTaskBoardExtensionPayload,
19
20
  taskBoardPayloadBytes,
20
21
  type TaskBoardCreateOptions,
@@ -26,7 +27,9 @@ import {
26
27
  type TaskBoardExtensionPayload,
27
28
  type TaskBoardIntegrationFace,
28
29
  type TaskBoardLinkedTask,
30
+ type TaskBoardSessionsFace,
29
31
  type TaskBoardStatusChangedEvent,
32
+ type TaskBoardTaskDraft,
30
33
  type TaskBoardTaskDeletedEvent,
31
34
  type TaskBoardTasksFace,
32
35
  } from '../core/extension.ts'
@@ -56,11 +59,27 @@ export interface TaskBoardExtensionToolRegistry {
56
59
  /** Applies one board action with every board gate intact (never an extension action). */
57
60
  export type TaskBoardActionApplier = (action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string) => TaskBoardSnapshot
58
61
 
62
+ /** Delivers one follow-up message into an existing execution session. */
63
+ export type TaskBoardFollowUpDelivery = (sessionId: string, text: string) => Promise<void>
64
+
65
+ /** Applies one rework request through the board's own run path. */
66
+ export type TaskBoardReworkApplier = (taskId: string, instructions: string, initiator?: string) => void
67
+
59
68
  /** Registry dependencies. */
60
69
  export interface TaskBoardExtensionRegistryOptions {
61
70
  ledger: HostTaskLedger
62
71
  /** Apply an action through the board service (gates, run dispatch, schedule). */
63
72
  apply?: TaskBoardActionApplier
73
+ /**
74
+ * Queue one follow-up message into a session. Absent means this deployment
75
+ * serves no session delivery, which the capability face refuses visibly.
76
+ */
77
+ followUp?: TaskBoardFollowUpDelivery
78
+ /**
79
+ * Apply one rework run request (through the same gates a run takes). Absent
80
+ * means this deployment serves no rework, which the face refuses visibly.
81
+ */
82
+ rework?: TaskBoardReworkApplier
64
83
  /** Resolve the deployment's tool registry; absent loses the tool surface only. */
65
84
  toolRegistry?: () => TaskBoardExtensionToolRegistry | undefined
66
85
  now?: () => number
@@ -137,10 +156,54 @@ function readPayload(value: unknown): TaskBoardExtensionPayload | undefined {
137
156
  return isTaskBoardExtensionPayload(value) ? value : undefined
138
157
  }
139
158
 
159
+ /** One-line text of a delivery failure, for a diagnosable refusal. */
160
+ function failureText(error: unknown): string {
161
+ return error instanceof Error ? error.message : String(error)
162
+ }
163
+
164
+ /**
165
+ * Validate one free text a provider pushes into an execution. Blank text would
166
+ * queue an empty turn, and an unbounded one would let a single provider call
167
+ * inject an arbitrarily large instruction, so both are refused here rather
168
+ * than at the gateway.
169
+ */
170
+ function extensionText(value: string, what: string): string {
171
+ const text = typeof value === 'string' ? value.trim() : ''
172
+ if (text === '') throw new TaskBoardExtensionError('invalid-text', `a ${what} must be a non-blank string`)
173
+ if (text.length > TASK_BOARD_MESSAGE_MAX_LENGTH) {
174
+ throw new TaskBoardExtensionError('invalid-text', `a ${what} is limited to ${TASK_BOARD_MESSAGE_MAX_LENGTH} characters`)
175
+ }
176
+ return text
177
+ }
178
+
179
+ /**
180
+ * The session a follow-up message goes to, or the refusal that says why there
181
+ * is none. The open execution owns the answer while one is running: delivering
182
+ * into the previous conversation instead would answer a question the current
183
+ * run never asked.
184
+ */
185
+ function followUpTarget(task: TaskRecord): { sessionId: string } | { refusal: string; message: string } {
186
+ if (task.executions.length === 0) {
187
+ return { refusal: 'not-executed', message: `task ${task.id} has never executed, so it has no session to deliver to` }
188
+ }
189
+ const open = [...task.executions].reverse().find(record => record.endedAt === undefined)
190
+ if (open !== undefined) {
191
+ return open.sessionId === undefined
192
+ ? { refusal: 'session-unreachable', message: `the current execution of task ${task.id} has not attached a session yet` }
193
+ : { sessionId: open.sessionId }
194
+ }
195
+ const settled = [...task.executions].reverse().find(record => record.sessionId !== undefined)
196
+ return settled?.sessionId === undefined
197
+ ? { refusal: 'session-unreachable', message: `task ${task.id} records no execution session to deliver to` }
198
+ : { sessionId: settled.sessionId }
199
+ }
200
+
140
201
  export class TaskBoardExtensionRegistry {
141
202
  private readonly entries = new Map<string, RegistryEntry>()
142
203
  private readonly ledger: HostTaskLedger
143
204
  private readonly applyAction: TaskBoardActionApplier | undefined
205
+ private readonly followUpDelivery: TaskBoardFollowUpDelivery | undefined
206
+ private readonly reworkApply: TaskBoardReworkApplier | undefined
144
207
  private readonly now: () => number
145
208
  private readonly uuid: () => string
146
209
  private readonly logger: TaskBoardExtensionLogger
@@ -152,6 +215,8 @@ export class TaskBoardExtensionRegistry {
152
215
  constructor(options: TaskBoardExtensionRegistryOptions) {
153
216
  this.ledger = options.ledger
154
217
  this.applyAction = options.apply
218
+ this.followUpDelivery = options.followUp
219
+ this.reworkApply = options.rework
155
220
  this.now = options.now ?? Date.now
156
221
  this.uuid = options.uuid ?? (() => crypto.randomUUID())
157
222
  this.logger = options.logger ?? DEFAULT_LOGGER
@@ -381,6 +446,10 @@ export class TaskBoardExtensionRegistry {
381
446
  patchContent: (taskId, patch) => this.patchContent(entry, taskId, patch),
382
447
  setStatus: (taskId, status, initiator) => this.setStatus(entry, taskId, status, initiator),
383
448
  linked: () => this.linkedTasks(entry),
449
+ rework: (taskId, instructions, initiator) => { this.rework(entry, taskId, instructions, initiator) },
450
+ }
451
+ const sessions: TaskBoardSessionsFace = {
452
+ followUp: async (taskId, text) => { await this.followUp(entry, taskId, text) },
384
453
  }
385
454
  const integration: TaskBoardIntegrationFace = {
386
455
  read: (taskId) => {
@@ -396,6 +465,7 @@ export class TaskBoardExtensionRegistry {
396
465
  }
397
466
  return {
398
467
  tasks,
468
+ sessions,
399
469
  integration,
400
470
  events,
401
471
  publish: (summary) => { this.publish(entry, summary) },
@@ -403,7 +473,7 @@ export class TaskBoardExtensionRegistry {
403
473
  }
404
474
  }
405
475
 
406
- private createTask(entry: RegistryEntry, draft: { title: string; description: string; prompt: string; status?: TaskStatus; parentId?: string; workspaceId?: string }, options?: TaskBoardCreateOptions): TaskRecord {
476
+ private createTask(entry: RegistryEntry, draft: TaskBoardTaskDraft, options?: TaskBoardCreateOptions): TaskRecord {
407
477
  this.assertActive(entry, 'create a task')
408
478
  if (this.applyAction === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no action applier')
409
479
  if (draft.status !== undefined && !isTaskStatus(draft.status)) throw new TaskBoardExtensionError('invalid-status', 'unknown task status')
@@ -422,6 +492,14 @@ export class TaskBoardExtensionRegistry {
422
492
  ...(draft.status === undefined ? {} : { status: draft.status }),
423
493
  ...(draft.parentId === undefined ? {} : { parentId: draft.parentId }),
424
494
  ...(draft.workspaceId === undefined ? {} : { workspaceId: draft.workspaceId }),
495
+ // Execution targets travel to the board's own creation path verbatim:
496
+ // what the caller sent wins there, the parent's pins fill the rest, and
497
+ // the board's new-card defaults stay out of it (this face never opts
498
+ // into them). Validating preset or route existence is the RUN's job, so
499
+ // an unknown value fails closed at launch instead of being judged here.
500
+ ...(draft.mode === undefined ? {} : { mode: draft.mode }),
501
+ ...(draft.model === undefined ? {} : { model: draft.model }),
502
+ ...(draft.reasoningEffort === undefined ? {} : { reasoningEffort: draft.reasoningEffort }),
425
503
  ...(payload === undefined ? {} : { integrations: { [entry.extension.id]: payload } }),
426
504
  ...(options?.hidden === true ? { hidden: true } : {}),
427
505
  },
@@ -434,8 +512,7 @@ export class TaskBoardExtensionRegistry {
434
512
  private patchContent(entry: RegistryEntry, taskId: string, patch: { title?: string; description?: string; prompt?: string }): void {
435
513
  this.assertActive(entry, 'patch content')
436
514
  if (this.applyAction === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no action applier')
437
- const task = this.ledger.getTask(taskId)
438
- if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
515
+ const task = this.requireTask(taskId)
439
516
  // The board's own content authority: an executed (or archived) card keeps
440
517
  // the title/description/prompt that were actually planned and run.
441
518
  if (!canEditTaskContent(task)) throw new TaskBoardExtensionError('content-frozen', `task ${taskId} has started executing; its content is read-only`)
@@ -453,6 +530,75 @@ export class TaskBoardExtensionRegistry {
453
530
  this.applyAction({ kind: 'move', taskId, status }, initiator)
454
531
  }
455
532
 
533
+ /**
534
+ * Queue one follow-up message into the session of a card's current or most
535
+ * recent execution.
536
+ *
537
+ * A running card is the point of the capability, so an open execution is not
538
+ * a refusal: the message is queued behind the turn that is already going. What
539
+ * IS refused is a card with no conversation to deliver into, and a session
540
+ * this Host no longer reaches — the delivery refuses, and that refusal must
541
+ * reach the provider as such instead of looking like a silent success.
542
+ */
543
+ private async followUp(entry: RegistryEntry, taskId: string, text: string): Promise<void> {
544
+ this.assertActive(entry, 'deliver a follow-up message')
545
+ const task = this.requireTask(taskId)
546
+ const message = extensionText(text, 'follow-up message')
547
+ if (task.archivedAt !== undefined) {
548
+ throw new TaskBoardExtensionError('task-archived', `task ${taskId} is archived; an archived card's execution is closed`)
549
+ }
550
+ const target = followUpTarget(task)
551
+ if ('refusal' in target) throw new TaskBoardExtensionError(target.refusal, target.message)
552
+ if (this.followUpDelivery === undefined) {
553
+ throw new TaskBoardExtensionError('unavailable', 'this deployment serves no session delivery')
554
+ }
555
+ try {
556
+ await this.followUpDelivery(target.sessionId, message)
557
+ } catch (error) {
558
+ throw new TaskBoardExtensionError(
559
+ 'session-unreachable',
560
+ `session ${target.sessionId} of task ${taskId} did not accept the message: ${failureText(error)}`,
561
+ )
562
+ }
563
+ }
564
+
565
+ /**
566
+ * Re-run an executed card in its own session with rework instructions.
567
+ *
568
+ * The registry decides only what it can read from the ledger — the card
569
+ * exists, is not archived, is not running, and has a conversation to continue
570
+ * — and then hands the request to the board's own run path, so the running
571
+ * lock, the permission confirmation, the acceptance contract and the spend cap
572
+ * keep judging it. A board refusal surfaces unchanged, exactly as it does for
573
+ * {@link setStatus}, because those are the board's own words.
574
+ */
575
+ private rework(entry: RegistryEntry, taskId: string, instructions: string, initiator?: string): void {
576
+ this.assertActive(entry, 'rework a task')
577
+ if (this.reworkApply === undefined) throw new TaskBoardExtensionError('unavailable', 'this deployment serves no rework applier')
578
+ const task = this.requireTask(taskId)
579
+ const text = extensionText(instructions, 'rework instructions')
580
+ if (task.archivedAt !== undefined) {
581
+ throw new TaskBoardExtensionError('task-archived', `task ${taskId} is archived; an archived card is read-only`)
582
+ }
583
+ if (task.executions.some(record => record.endedAt === undefined)) {
584
+ throw new TaskBoardExtensionError('running', `task ${taskId} is still running; a card is reworked once its run settles`)
585
+ }
586
+ if (task.executions.length === 0) {
587
+ throw new TaskBoardExtensionError('not-executed', `task ${taskId} has never executed, so there is no run to rework`)
588
+ }
589
+ if (!task.executions.some(record => record.sessionId !== undefined)) {
590
+ throw new TaskBoardExtensionError('session-unreachable', `task ${taskId} records no execution session to continue`)
591
+ }
592
+ this.reworkApply(taskId, text, initiator)
593
+ }
594
+
595
+ /** One task by id, or the refusal that names the unknown id. */
596
+ private requireTask(taskId: string): TaskRecord {
597
+ const task = this.ledger.getTask(taskId)
598
+ if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
599
+ return task
600
+ }
601
+
456
602
  private linkedTasks(entry: RegistryEntry): readonly TaskBoardLinkedTask[] {
457
603
  const id = entry.extension.id
458
604
  const result: TaskBoardLinkedTask[] = []
@@ -469,8 +615,7 @@ export class TaskBoardExtensionRegistry {
469
615
  if (!isTaskBoardExtensionPayload(payload)) {
470
616
  throw new TaskBoardExtensionError('invalid-payload', 'integration payload must be a pure JSON object within the size limit')
471
617
  }
472
- const task = this.ledger.getTask(taskId)
473
- if (task === undefined) throw new TaskBoardExtensionError('task-not-found', `no task with id ${taskId}`)
618
+ const task = this.requireTask(taskId)
474
619
  const id = entry.extension.id
475
620
  const next = mergePayload(readPayload(task.integrations?.[id]), payload)
476
621
  if (!isTaskBoardExtensionPayload(next)) {
@@ -7,7 +7,7 @@ import { isValidCron, isValidTimeZone, nextRunAtMs, resolveHostTimeZone } from '
7
7
  import { isTaskRecord, parseLedger } from './core/store.ts'
8
8
  import { DEFAULT_SPEND_BUDGET_TOKENS, spendCapMessage, spendCapReached } from './core/spend-budget.ts'
9
9
  import { usedTokensToday } from './host-spend.ts'
10
- import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ExecutionSummary, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
10
+ import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ExecutionRework, type ExecutionSummary, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
11
11
  import {
12
12
  DEFAULT_SUBTASK_DEPTH,
13
13
  ancestorChain,
@@ -1289,17 +1289,23 @@ export class HostTaskLedger {
1289
1289
  this.document.tasks = [...result.tasks]
1290
1290
  break
1291
1291
  }
1292
+ case 'rework':
1292
1293
  case 'rerun':
1293
1294
  case 'run': {
1294
1295
  const task = this.document.tasks.find(item => item.id === action.taskId)
1295
1296
  if (task?.archivedAt !== undefined) throw new Error('archived task is read-only')
1296
1297
  if (task === undefined || hasOpenExecution(task)) throw new Error('task is already running or missing')
1298
+ // A rework asks for a second attempt at work this card's own conversation
1299
+ // already holds; the ledger alone decides whether that conversation
1300
+ // exists, so the run can never be opened with instructions no session
1301
+ // ever saw.
1302
+ const rework = action.kind === 'rework' ? this.reworkInput(task, action.instructions) : undefined
1297
1303
  // The confirmation gate judges the RESOLVED binding: a subtask that
1298
1304
  // inherits an elevated permission from its parent is exactly as
1299
1305
  // unconfirmed as the parent would be without its own stamp.
1300
1306
  const refusal = this.bindingRefusal(task)
1301
1307
  if (refusal !== undefined) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, 'run'))
1302
- runs = this.startRun(task, now, initiator, action.kind === 'rerun')
1308
+ runs = this.startRun(task, now, initiator, action.kind !== 'run', undefined, rework)
1303
1309
  break
1304
1310
  }
1305
1311
  default: {
@@ -1358,6 +1364,26 @@ export class HostTaskLedger {
1358
1364
  return { kind: root.parentId === undefined ? 'root' : 'inherited', title: root.title }
1359
1365
  }
1360
1366
 
1367
+ /**
1368
+ * The rework block a rework request opens its execution with, or the refusal
1369
+ * that names why there is nothing to rework.
1370
+ *
1371
+ * Read from the ledger alone: a card that never ran, and a card whose runs
1372
+ * recorded no session, have no conversation to send the reviewer's
1373
+ * instructions into. Minting one would hand those instructions to an agent
1374
+ * that never saw the work being sent back, which is the opposite of what a
1375
+ * rework asks for.
1376
+ * @param task - the card being reworked.
1377
+ * @param instructions - the reviewer's instructions, already validated.
1378
+ * @returns the block recorded on the opened execution.
1379
+ */
1380
+ private reworkInput(task: TaskRecord, instructions: string): ExecutionRework {
1381
+ if (task.executions.length === 0) throw new Error('task ' + task.id + ' has never executed; there is no run to rework')
1382
+ const settled = [...task.executions].reverse().find(entry => entry.endedAt !== undefined && entry.sessionId !== undefined)
1383
+ if (settled?.sessionId === undefined) throw new Error('task ' + task.id + ' records no execution session to continue')
1384
+ return { instructions }
1385
+ }
1386
+
1361
1387
  /** Whether a task or any of its subtasks still has an open execution. */
1362
1388
  private subtreeHasOpenExecution(id: string): boolean {
1363
1389
  return subtreeTasks(this.document.tasks, id, this.maxSubtaskDepth)
@@ -1388,15 +1414,17 @@ export class HostTaskLedger {
1388
1414
  * @param progress - when set, this run was a due occurrence and the root's
1389
1415
  * rule is advanced (counter, next target, stop/skip record) in the same
1390
1416
  * atomic commit that opened the execution.
1417
+ * @param rework - the reviewer's instructions, when this run redoes previous
1418
+ * work; recorded on the execution it opens.
1391
1419
  */
1392
- private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress): OpenedRun[] {
1420
+ private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress, rework?: ExecutionRework): OpenedRun[] {
1393
1421
  const before = this.document.tasks
1394
1422
  const [participant] = cascadeTargets(before, root.id)
1395
1423
  if (participant === undefined || participant.archivedAt !== undefined) return []
1396
1424
  if (hasOpenExecution(participant)) return []
1397
1425
  const groupId = crypto.randomUUID()
1398
1426
  const base = rerun ? withStatus(participant, 'todo', now) : participant
1399
- const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId)
1427
+ const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId, rework)
1400
1428
  let tasks: readonly TaskRecord[] = before.map(task => task.id === participant.id ? opened.task : task)
1401
1429
  if (progress !== undefined) tasks = applyScheduleProgress(tasks, root.id, progress, now)
1402
1430
  this.document.tasks = [...tasks]
@@ -12,10 +12,27 @@ import {
12
12
  type TaskBoardParseDraft,
13
13
  type TaskBoardParseRequest,
14
14
  } from './protocol.ts'
15
+ import {
16
+ attachmentErrorStatus,
17
+ effectiveImageByteLimit,
18
+ imageRefOf,
19
+ readRequestBytes,
20
+ requestChunks,
21
+ sanitizeAttachmentName,
22
+ storeFile,
23
+ storeImage,
24
+ TaskBoardAttachmentError,
25
+ type TaskBoardAttachmentStore,
26
+ } from './host/attachments.ts'
15
27
 
16
28
  const ACTION_LIMIT = 64 * 1024
17
29
  const IMPORT_LIMIT = 2 * 1024 * 1024
18
- const HEARTBEAT_MS = 15_000
30
+ /**
31
+ * Comment-frame cadence on the event stream. It keeps the connection alive
32
+ * through intermediaries that would close an idle one; it is not a frame the
33
+ * browser reports to the panel (an SSE comment is invisible to EventSource).
34
+ */
35
+ export const HEARTBEAT_MS = 15_000
19
36
 
20
37
  /** Header replaced by an authenticated same-host reverse proxy. */
21
38
  export const TASK_BOARD_PROXY_TOKEN_HEADER = 'x-dsh-task-board-proxy-token'
@@ -64,6 +81,13 @@ export interface TaskBoardRouteAccess {
64
81
  */
65
82
  export interface TaskBoardRouteOptions {
66
83
  parseTask?: (request: TaskBoardParseRequest, signal: AbortSignal) => Promise<TaskBoardParseDraft>
84
+ /**
85
+ * The official attachment storage, read at request time so a deployment that
86
+ * mounts it after these routes still gains the attachment surface. Absent
87
+ * means this deployment stores no attachments, and every attachment route
88
+ * answers with a typed "storage unavailable" failure.
89
+ */
90
+ attachments?: () => TaskBoardAttachmentStore | undefined
67
91
  }
68
92
 
69
93
  interface ResolvedRouteAccess {
@@ -235,6 +259,18 @@ async function readBody(req: IncomingMessage): Promise<{ raw: string; value: unk
235
259
  return { raw, value: JSON.parse(raw) }
236
260
  }
237
261
 
262
+ /**
263
+ * The query parameters of one request, read against a fixed base so a
264
+ * relative request target still parses.
265
+ */
266
+ function requestQuery(req: IncomingMessage): URLSearchParams {
267
+ try {
268
+ return new URL(req.url ?? '/', 'http://localhost').searchParams
269
+ } catch {
270
+ return new URLSearchParams()
271
+ }
272
+ }
273
+
238
274
  export function makeTaskBoardRoutes(
239
275
  service: TaskBoardHostService,
240
276
  access: TaskBoardRouteAccess = {},
@@ -271,9 +307,19 @@ export function makeTaskBoardRoutes(
271
307
  if (parsed.action.kind !== 'import' && Buffer.byteLength(body.raw) > ACTION_LIMIT) {
272
308
  return writeJson(res, 413, { ok: false, error: 'body-too-large' }, { 'cache-control': 'no-store' })
273
309
  }
274
- writeJson(res, 200, await service.apply(parsed.requestId, parsed.action, parsed.initiator), { 'cache-control': 'no-store' })
310
+ // The verified path: an action that carries attachments is proven
311
+ // against the official storage BEFORE the ledger commits it, so a
312
+ // spoofed claim can never become a stored fact.
313
+ writeJson(res, 200, await service.applyVerified(parsed.requestId, parsed.action, parsed.initiator), { 'cache-control': 'no-store' })
275
314
  } catch (error) {
276
315
  const message = error instanceof Error ? error.message : String(error)
316
+ // An attachment failure keeps its own class: a storage that is
317
+ // unavailable answers 503 exactly like the upload route does, instead
318
+ // of being flattened into a generic rejected action.
319
+ if (error instanceof TaskBoardAttachmentError) {
320
+ writeJson(res, attachmentErrorStatus(error.code), { ok: false, code: error.code, error: message }, { 'cache-control': 'no-store' })
321
+ return
322
+ }
277
323
  writeJson(res, message === 'body-too-large' ? 413 : 400, { ok: false, error: message }, { 'cache-control': 'no-store' })
278
324
  }
279
325
  },
@@ -293,18 +339,48 @@ export function makeTaskBoardRoutes(
293
339
  'cache-control': 'no-cache',
294
340
  connection: 'keep-alive',
295
341
  })
296
- const push = (): void => {
297
- const payload = service.eventPayload()
298
- res.write(`data: ${JSON.stringify(payload)}\n\n`)
342
+ // The stream is the board's only live signal, so it also has to be able to
343
+ // STOP being one. A connection can stop accepting bytes while neither end
344
+ // has closed it (a half-open socket, an intermediary that stopped
345
+ // reading); from then on every frame is written into nothing, the browser's
346
+ // EventSource sees an open stream that never speaks, and the panel keeps
347
+ // the snapshot it last applied with no error to react to. A failed write is
348
+ // the one report of that state, so it ends the connection here: the browser
349
+ // then reports the closed stream, and a closed stream makes the panel read
350
+ // the state again.
351
+ let heartbeat: ReturnType<typeof setInterval> | undefined
352
+ let release: (() => void) | undefined
353
+ const stop = (): void => {
354
+ if (heartbeat !== undefined) {
355
+ clearInterval(heartbeat)
356
+ heartbeat = undefined
357
+ }
358
+ const unsubscribe = release
359
+ release = undefined
360
+ unsubscribe?.()
361
+ }
362
+ const drop = (): void => {
363
+ if (release === undefined) return
364
+ stop()
365
+ res.destroy()
299
366
  }
300
- const unsubscribe = service.subscribe(push)
301
- const heartbeat = setInterval(() => { res.write(': ping\n\n') }, HEARTBEAT_MS)
302
- const close = (): void => {
303
- clearInterval(heartbeat)
304
- unsubscribe()
367
+ const write = (chunk: string): void => {
368
+ if (release === undefined || res.writableEnded || res.destroyed) return
369
+ // The callback is the only place Node reports a write that never landed;
370
+ // its result (backpressure) is not an error and is ignored.
371
+ res.write(chunk, (error) => { if (error !== null && error !== undefined) drop() })
305
372
  }
306
- req.once('close', close)
307
- res.once('close', close)
373
+ const push = (): void => {
374
+ write(`data: ${JSON.stringify(service.eventPayload())}\n\n`)
375
+ }
376
+ release = service.subscribe(push)
377
+ heartbeat = setInterval(() => { write(': ping\n\n') }, HEARTBEAT_MS)
378
+ req.once('close', stop)
379
+ res.once('close', stop)
380
+ // A reset socket reports the same fact as a failed write. Without this
381
+ // listener Node treats a response error as unhandled, so the connection is
382
+ // released here instead of being left behind.
383
+ res.on('error', () => { drop() })
308
384
  push()
309
385
  },
310
386
  }
@@ -365,5 +441,84 @@ export function makeTaskBoardRoutes(
365
441
  }
366
442
  },
367
443
  }
368
- return [state, action, events, parse, verification]
444
+ const attachmentUpload: WebRoute = {
445
+ kind: 'exact',
446
+ path: `${TASK_BOARD_API_PREFIX}/attachments/upload`,
447
+ handler: async (req, res): Promise<void> => {
448
+ if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'method-not-allowed' }, { 'cache-control': 'no-store' })
449
+ if (!guard(req, res)) return
450
+ const store = options.attachments?.()
451
+ if (store === undefined) {
452
+ return writeJson(res, 503, { ok: false, code: 'storage-unavailable', error: 'this deployment serves no attachment storage' }, { 'cache-control': 'no-store' })
453
+ }
454
+ const query = requestQuery(req)
455
+ const kind = query.get('kind')
456
+ if (kind !== 'image' && kind !== 'file') {
457
+ return writeJson(res, 400, { ok: false, code: 'invalid-request', error: 'the attachment kind must be image or file' }, { 'cache-control': 'no-store' })
458
+ }
459
+ const name = sanitizeAttachmentName(query.get('name'))
460
+ const mediaType = query.get('mediaType') ?? ''
461
+ try {
462
+ if (kind === 'image') {
463
+ // The declared type is what the storage checks the decoded bytes
464
+ // against, so it is required rather than guessed: a guess would
465
+ // store a mislabelled object or fail with the storage's own
466
+ // mismatch error.
467
+ if (mediaType === '') {
468
+ return writeJson(res, 400, { ok: false, code: 'invalid-request', error: 'an image upload must declare its media type' }, { 'cache-control': 'no-store' })
469
+ }
470
+ const limit = effectiveImageByteLimit(store)
471
+ const bytes = await readRequestBytes(req, limit)
472
+ const attachment = await storeImage(store, bytes, name, mediaType)
473
+ writeJson(res, 200, { ok: true, attachment }, { 'cache-control': 'no-store' })
474
+ return
475
+ }
476
+ const stored = await storeFile(store, requestChunks(req), name, mediaType)
477
+ writeJson(res, 200, { ok: true, attachment: stored.attachment }, { 'cache-control': 'no-store' })
478
+ } catch (error) {
479
+ // The body is drained so the refusal reaches the caller instead of a
480
+ // closed socket.
481
+ req.resume()
482
+ const failure = error instanceof TaskBoardAttachmentError
483
+ ? error
484
+ : new TaskBoardAttachmentError('storage-unavailable', 'the attachment storage is unavailable', { cause: error })
485
+ writeJson(res, attachmentErrorStatus(failure.code), { ok: false, code: failure.code, error: failure.message }, { 'cache-control': 'no-store' })
486
+ }
487
+ },
488
+ }
489
+ const attachmentImage: WebRoute = {
490
+ kind: 'exact',
491
+ path: `${TASK_BOARD_API_PREFIX}/attachments/image`,
492
+ handler: async (req, res): Promise<void> => {
493
+ if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'method-not-allowed' }, { 'cache-control': 'no-store' })
494
+ if (!guard(req, res)) return
495
+ const store = options.attachments?.()
496
+ if (store === undefined) {
497
+ return writeJson(res, 503, { ok: false, code: 'storage-unavailable', error: 'this deployment serves no attachment storage' }, { 'cache-control': 'no-store' })
498
+ }
499
+ const id = requestQuery(req).get('id') ?? ''
500
+ // An image is served only when a card of THIS board references it: an
501
+ // unreferenced identifier must never become a readable object.
502
+ const referenced = service.ledger.allTasks().flatMap(task => task.attachments ?? [])
503
+ .find(attachment => attachment.kind === 'image' && attachment.attachmentId === id)
504
+ if (referenced === undefined) {
505
+ return writeJson(res, 404, { ok: false, code: 'not-found', error: 'no card references this attachment' }, { 'cache-control': 'no-store' })
506
+ }
507
+ try {
508
+ const stored = await store.readImage(imageRefOf(referenced))
509
+ res.writeHead(200, {
510
+ 'content-type': stored.ref.mediaType,
511
+ 'content-length': String(stored.data.byteLength),
512
+ 'cache-control': 'no-store',
513
+ })
514
+ res.end(Buffer.from(stored.data))
515
+ } catch (error) {
516
+ const failure = error instanceof TaskBoardAttachmentError
517
+ ? error
518
+ : new TaskBoardAttachmentError('unreadable', 'the stored attachment could not be read back', { cause: error })
519
+ writeJson(res, attachmentErrorStatus(failure.code), { ok: false, code: failure.code, error: failure.message }, { 'cache-control': 'no-store' })
520
+ }
521
+ },
522
+ }
523
+ return [state, action, events, parse, verification, attachmentUpload, attachmentImage]
369
524
  }