@fish-under-sea/dsh-client-ui-task-board-fish 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +6 -4
  3. package/README.md +6 -4
  4. package/README.zh.md +6 -4
  5. package/icon.png +0 -0
  6. package/lib/client.js +4428 -1508
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +2670 -496
  9. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +130 -19
  11. package/lib/types/client/RangeBubble.d.ts +46 -0
  12. package/lib/types/client/SegmentGroup.d.ts +28 -0
  13. package/lib/types/client/TaskBoardSettingsCard.d.ts +63 -0
  14. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  15. package/lib/types/client/board/ExecutionLog.d.ts +24 -0
  16. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  17. package/lib/types/client/board/TaskForm.d.ts +4 -0
  18. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  19. package/lib/types/client/board/model-options.d.ts +87 -0
  20. package/lib/types/client/board/preset-label.d.ts +21 -0
  21. package/lib/types/client/board/preset-roster.d.ts +45 -0
  22. package/lib/types/client/board/source-group.d.ts +27 -0
  23. package/lib/types/client/body-mutations.d.ts +45 -0
  24. package/lib/types/client/host-api.d.ts +25 -0
  25. package/lib/types/client/locales.d.ts +87 -9
  26. package/lib/types/client/pending-verify.d.ts +47 -0
  27. package/lib/types/client/plugin-card-seat.d.ts +3 -1
  28. package/lib/types/client/service.d.ts +4 -1
  29. package/lib/types/client/settings-form.d.ts +73 -51
  30. package/lib/types/core/attachment.d.ts +132 -0
  31. package/lib/types/core/card-defaults.d.ts +78 -0
  32. package/lib/types/core/controller.d.ts +57 -8
  33. package/lib/types/core/execution-summary.d.ts +52 -0
  34. package/lib/types/core/extension.d.ts +116 -0
  35. package/lib/types/core/launch-width.d.ts +31 -0
  36. package/lib/types/core/reasoning-effort.d.ts +57 -0
  37. package/lib/types/core/session-reuse.d.ts +7 -1
  38. package/lib/types/core/spend-budget.d.ts +28 -0
  39. package/lib/types/core/subtask.d.ts +100 -37
  40. package/lib/types/core/tasks.d.ts +94 -10
  41. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  42. package/lib/types/core/use-cases/task-tag.d.ts +36 -0
  43. package/lib/types/core/use-cases/task-update.d.ts +22 -1
  44. package/lib/types/core/wire-projection.d.ts +35 -0
  45. package/lib/types/core/workspace-target.d.ts +23 -3
  46. package/lib/types/host/attachments.d.ts +250 -0
  47. package/lib/types/host/extension-registry.d.ts +40 -0
  48. package/lib/types/host/launch-admission.d.ts +71 -0
  49. package/lib/types/host-ledger.d.ts +114 -47
  50. package/lib/types/host-routes.d.ts +63 -0
  51. package/lib/types/host-runner.d.ts +164 -18
  52. package/lib/types/host-service.d.ts +182 -46
  53. package/lib/types/host-spend.d.ts +52 -0
  54. package/lib/types/index.d.ts +173 -54
  55. package/lib/types/loopback.d.ts +41 -1
  56. package/lib/types/protocol.d.ts +52 -11
  57. package/lib/types/tool-surface.d.ts +1 -0
  58. package/locale/en.json +6 -0
  59. package/locale/zh.json +6 -0
  60. package/package.json +36 -29
  61. package/src/client/CardDefaultPresetField.tsx +101 -0
  62. package/src/client/PluginSettingsCard.tsx +385 -111
  63. package/src/client/RangeBubble.tsx +164 -0
  64. package/src/client/SegmentGroup.tsx +93 -0
  65. package/src/client/TaskBoardSettingsCard.tsx +332 -37
  66. package/src/client/board/AttachmentField.tsx +383 -0
  67. package/src/client/board/EditTaskModal.tsx +63 -0
  68. package/src/client/board/ExecutionLog.tsx +154 -0
  69. package/src/client/board/LinkSubtaskModal.tsx +1 -1
  70. package/src/client/board/NewTaskModal.tsx +154 -45
  71. package/src/client/board/ReasoningEffortField.tsx +50 -0
  72. package/src/client/board/TagManagerModal.tsx +151 -2
  73. package/src/client/board/TaskBoard.tsx +47 -10
  74. package/src/client/board/TaskCard.tsx +45 -23
  75. package/src/client/board/TaskDetail.tsx +468 -258
  76. package/src/client/board/TaskForm.tsx +19 -4
  77. package/src/client/board/VerificationReport.tsx +143 -104
  78. package/src/client/board/model-options.ts +208 -0
  79. package/src/client/board/preset-label.ts +32 -0
  80. package/src/client/board/preset-roster.ts +58 -0
  81. package/src/client/board/source-group.ts +94 -0
  82. package/src/client/board/task-markdown.module.css +11 -8
  83. package/src/client/board-settings.module.css +35 -7
  84. package/src/client/board.module.css +1044 -105
  85. package/src/client/body-mutations.ts +133 -0
  86. package/src/client/host-api.ts +70 -0
  87. package/src/client/index.ts +109 -95
  88. package/src/client/locales.ts +205 -48
  89. package/src/client/pending-verify.ts +90 -0
  90. package/src/client/plugin-card-seat.ts +8 -2
  91. package/src/client/service.ts +24 -0
  92. package/src/client/settings-card.module.css +466 -89
  93. package/src/client/settings-entry-form.ts +0 -1
  94. package/src/client/settings-form.ts +102 -60
  95. package/src/core/attachment.ts +287 -0
  96. package/src/core/card-defaults.ts +132 -0
  97. package/src/core/controller.ts +90 -11
  98. package/src/core/execution-summary.ts +96 -0
  99. package/src/core/extension.ts +120 -0
  100. package/src/core/launch-width.ts +38 -0
  101. package/src/core/reasoning-effort.ts +92 -0
  102. package/src/core/session-reuse.ts +7 -1
  103. package/src/core/spend-budget.ts +35 -0
  104. package/src/core/store.ts +19 -1
  105. package/src/core/subtask.ts +144 -68
  106. package/src/core/tasks.ts +117 -10
  107. package/src/core/use-cases/task-create.ts +27 -16
  108. package/src/core/use-cases/task-tag.ts +56 -0
  109. package/src/core/use-cases/task-update.ts +33 -5
  110. package/src/core/wire-projection.ts +81 -0
  111. package/src/core/workspace-target.ts +27 -3
  112. package/src/host/agent-tools.ts +33 -21
  113. package/src/host/attachments.ts +650 -0
  114. package/src/host/extension-registry.ts +150 -5
  115. package/src/host/launch-admission.ts +139 -0
  116. package/src/host-ledger.ts +248 -117
  117. package/src/host-routes.ts +233 -15
  118. package/src/host-runner.ts +395 -61
  119. package/src/host-service.ts +512 -139
  120. package/src/host-spend.ts +105 -0
  121. package/src/index.ts +312 -92
  122. package/src/loopback.ts +57 -1
  123. package/src/protocol.ts +83 -18
  124. package/src/tool-surface.ts +1 -0
  125. package/icon.svg +0 -3
@@ -1,18 +1,19 @@
1
1
  // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
2
  /**
3
- * Staged form model behind the plugin settings card. A card stages what the
4
- * user types and writes it only when they save — the settings write is a
5
- * durable, revision-fenced document mutation, so staging keeps what is on
6
- * screen exactly what a save would store. Family-shared slice inlined into
7
- * each plugin's client bundle; mirrors the official ui-plugin-config
8
- * card-store pattern.
3
+ * Form model behind the plugin settings card. Every control applies itself:
4
+ * a pick (a segment, a select option, a reset) writes the moment it is made,
5
+ * and typed text writes once typing pauses or the reader leaves the field.
6
+ * Between the edit and the write the edit is held here as a draft, so what is
7
+ * on screen is exactly what the write will store; a write the Host refuses
8
+ * puts a pick back to the stored value and keeps typed text for correcting.
9
+ * Family-shared slice inlined into each plugin's client bundle.
9
10
  */
10
11
 
11
12
  import type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'
12
13
  import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
13
14
  import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
14
15
 
15
- /** The write one field's staged text performs when the card is saved. */
16
+ /** The write one field's draft text performs when it is applied. */
16
17
  export type FieldWrite =
17
18
  | { kind: 'set'; value: unknown }
18
19
  | { kind: 'clear' }
@@ -21,6 +22,12 @@ export type FieldWrite =
21
22
  export interface FieldSpec {
22
23
  /** Field name inside the namespace section. */
23
24
  field: string
25
+ /**
26
+ * How the reader enters a value, which decides when it is written: a `pick`
27
+ * is a whole value at once and applies immediately; `type` is text arriving
28
+ * a keystroke at a time and applies once typing pauses or the field is left.
29
+ */
30
+ entry: 'pick' | 'type'
24
31
  /**
25
32
  * Whether the Host treats this field as a secret and redacts its value from
26
33
  * the read-back (role('secret') in the section schema). Redacted secrets are
@@ -34,8 +41,9 @@ export interface FieldSpec {
34
41
  /** Render a stored value as draft text; the empty string when the section carries none. */
35
42
  format: (value: unknown) => string
36
43
  /**
37
- * The write this draft text stages, or undefined when the text is not a
38
- * value this field accepts — which blocks the save rather than discarding it.
44
+ * The write this draft text performs, or undefined when the text is not a
45
+ * value this field accepts — which holds the draft unwritten rather than
46
+ * discarding it.
39
47
  */
40
48
  parse: (text: string) => FieldWrite | undefined
41
49
  }
@@ -44,9 +52,9 @@ export interface FieldSpec {
44
52
  export interface FieldState {
45
53
  /** Draft text the control renders. */
46
54
  text: string
47
- /** Whether saving would leave a user-layer entry for this field. */
55
+ /** Whether the field leaves (or will leave) a user-layer entry. */
48
56
  overridden: boolean
49
- /** Whether the draft is not a value this field accepts, which blocks saving. */
57
+ /** Whether the draft is not a value this field accepts, which holds it unwritten. */
50
58
  invalid: boolean
51
59
  }
52
60
 
@@ -64,13 +72,13 @@ export interface CardShell {
64
72
  exposed: boolean
65
73
  /** Whether the Host document accepts writes. */
66
74
  writable: boolean
67
- /** Whether the form holds edits that a save would write. */
75
+ /** Whether the form holds drafts not yet written (typed text waiting for its pause). */
68
76
  dirty: boolean
69
- /** Whether any staged draft is invalid, which blocks the save. */
77
+ /** Whether any draft is invalid, which holds it unwritten. */
70
78
  invalid: boolean
71
- /** Whether a save is crossing the wire. */
79
+ /** Whether a write is crossing the wire. */
72
80
  saving: boolean
73
- /** Whether the last save did not land as staged; cleared by the next edit or save. */
81
+ /** Whether the last write did not land; cleared by the next edit or write. */
74
82
  failed: boolean
75
83
  /**
76
84
  * The rejection code/message the Host returned for the last failed save,
@@ -82,16 +90,19 @@ export interface CardShell {
82
90
 
83
91
  /** The write actions the card's slot entry injects. */
84
92
  export interface CardActions {
85
- /** Stage draft text for one field. */
93
+ /** Take draft text for one field; a pick writes at once, typed text after a pause. */
86
94
  edit: (field: string, text: string) => void
87
- /** Stage a clear, so saving lets the field re-inherit the composition layer. */
95
+ /** Clear one field at once, so it re-inherits the composition layer. */
88
96
  resetField: (field: string) => void
89
- /** Write every staged edit, then re-seed from what the Host accepted. */
97
+ /** Write every pending draft now (a text field's Enter or blur), then re-seed from what the Host accepted. */
90
98
  save: () => void
91
- /** Drop every staged edit. */
99
+ /** Drop every pending draft, putting each control back to the stored value (a text field's Escape). */
92
100
  discard: () => void
93
101
  }
94
102
 
103
+ /** How long typed text rests before it is written. */
104
+ export const TYPE_PAUSE_MS = 600
105
+
95
106
  /** One field's staged edit. */
96
107
  interface StagedEdit {
97
108
  /** Draft text the control renders. */
@@ -132,11 +143,12 @@ export interface NumberConstraints {
132
143
  min?: number
133
144
  }
134
145
 
135
- /** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints blocks the save. */
146
+ /** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints stays unwritten. */
136
147
  export function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {
137
148
  const { integer = false, min } = constraints
138
149
  return {
139
150
  field,
151
+ entry: 'type',
140
152
  format: value => typeof value === 'number' ? String(value) : '',
141
153
  parse: (text) => {
142
154
  const trimmed = text.trim()
@@ -150,10 +162,14 @@ export function numberField(field: string, constraints: NumberConstraints = {}):
150
162
  }
151
163
  }
152
164
 
153
- /** A free-text field. An empty draft clears the field. */
154
- export function textField(field: string): FieldSpec {
165
+ /**
166
+ * A free-text field. An empty draft clears the field. `entry` is `pick` when
167
+ * the text arrives whole from a picker (a preset or a reasoning level).
168
+ */
169
+ export function textField(field: string, entry: FieldSpec['entry'] = 'type'): FieldSpec {
155
170
  return {
156
171
  field,
172
+ entry,
157
173
  format: value => typeof value === 'string' ? value : '',
158
174
  parse: (text) => {
159
175
  const trimmed = text.trim()
@@ -176,6 +192,7 @@ export function secretField(field: string): FieldSpec {
176
192
  export function booleanField(field: string): FieldSpec {
177
193
  return {
178
194
  field,
195
+ entry: 'pick',
179
196
  format: value => typeof value === 'boolean' ? String(value) : '',
180
197
  parse: (text) => {
181
198
  const trimmed = text.trim()
@@ -191,6 +208,7 @@ export function booleanField(field: string): FieldSpec {
191
208
  export function choiceField(field: string, choices: readonly string[]): FieldSpec {
192
209
  return {
193
210
  field,
211
+ entry: 'pick',
194
212
  format: value => typeof value === 'string' && choices.includes(value) ? value : '',
195
213
  parse: (text) => {
196
214
  if (text === '') return { kind: 'clear' }
@@ -200,12 +218,14 @@ export function choiceField(field: string, choices: readonly string[]): FieldSpe
200
218
  }
201
219
 
202
220
  /**
203
- * Stages one card's edits over one settings namespace and writes them on save.
221
+ * Applies one card's edits to one settings namespace as the reader makes them.
204
222
  *
205
223
  * The Host is the only authority on whether a value was accepted — its
206
224
  * validators own the constraints no schema can express — so the outcome is
207
- * read back from the section rather than predicted here. A save that did not
208
- * land keeps its drafts, so the user can correct them instead of retyping.
225
+ * read back from the section rather than predicted here. A write that did not
226
+ * land puts each pick back to the stored value, the way a switch that could not
227
+ * flip springs back, and keeps typed text so the reader can correct it instead
228
+ * of retyping.
209
229
  */
210
230
  export class CardForm<T> {
211
231
  private readonly specs: Map<string, FieldSpec>
@@ -214,6 +234,8 @@ export class CardForm<T> {
214
234
  /** The form subscription installed in the constructor; released by dispose(). */
215
235
  private readonly disposeForm: () => void
216
236
  private disposed = false
237
+ /** The pending write of typed text, waiting for typing to pause. */
238
+ private typePause: ReturnType<typeof setTimeout> | undefined
217
239
  private saving = false
218
240
  /** A save asked for while one was in flight; it runs once the first settles (#1754). */
219
241
  private saveQueued = false
@@ -236,6 +258,7 @@ export class CardForm<T> {
236
258
  dispose(): void {
237
259
  if (this.disposed) return
238
260
  this.disposed = true
261
+ clearTimeout(this.typePause)
239
262
  this.disposeForm()
240
263
  this.listeners.clear()
241
264
  }
@@ -247,7 +270,7 @@ export class CardForm<T> {
247
270
  return store
248
271
  }
249
272
 
250
- /** Read the card-level state: what the Host serves, and what a save would do. */
273
+ /** Read the card-level state: what the Host serves, and what is still waiting to be written. */
251
274
  shell(): CardShell {
252
275
  const snapshot = this.scope.getSnapshot()
253
276
  const plan = this.plan()
@@ -285,8 +308,9 @@ export class CardForm<T> {
285
308
  resetField: (field) => {
286
309
  this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true })
287
310
  },
288
- save: () => { void this.requestSave() },
311
+ save: () => { this.applyNow() },
289
312
  discard: () => {
313
+ clearTimeout(this.typePause)
290
314
  if (this.staged.size === 0 && !this.failed) return
291
315
  this.staged.clear()
292
316
  this.failed = false
@@ -297,32 +321,14 @@ export class CardForm<T> {
297
321
  }
298
322
 
299
323
  /**
300
- * Write every staged edit in one atomic form mutation, then re-seed from
301
- * what the Host accepted.
302
- *
303
- * The whole batch rides one mutate, so cross-field validate hooks
304
- * (baseURL+model) judge it as a unit: the Host either applies every write
305
- * or refuses the batch. The form contract answers a refusal or a skipped
306
- * write with `false` (it recovers with a fresh Host view instead of
307
- * throwing), so the outcome is judged twice: the answer itself, and then the
308
- * settled snapshot read back one planned write at a time. One missed write
309
- * fails the whole save. A transport that rejects instead (the dsh-web bridge
310
- * controller on a dead connection) reports through the same failure path
311
- * with its rejection message. A save that did not land keeps its drafts, so
312
- * the user can correct them instead of retyping.
313
- * @returns settlement after the mutation and the read-back.
314
- */
315
- /**
316
- * Run one save, and re-run it once if another was asked for while this one
324
+ * Run one write, and re-run it once if another was asked for while this one
317
325
  * was still in flight.
318
326
  *
319
- * A save is a Host round trip that also drives the profile reconcile, and
320
- * the Host runs that write inside one exclusive transaction. Answering a
321
- * press that arrives mid-flight by returning immediately dropped the edit
322
- * with no explanation, which is the "the save button stops working after a
323
- * few rounds" report (#1754). Serializing instead means a save pressed while
324
- * another is still settling runs against the settled state - which is what
325
- * the operator meant by pressing it again.
327
+ * A write is a Host round trip that also drives the profile reconcile, and
328
+ * the Host runs it inside one exclusive transaction. Answering an edit that
329
+ * arrives mid-flight by returning immediately dropped it with no explanation
330
+ * (#1754). Serializing instead means an edit made while another write is
331
+ * still settling is written against the settled state.
326
332
  * @returns settlement after the mutation and the read-back.
327
333
  */
328
334
  async requestSave(): Promise<void> {
@@ -336,15 +342,32 @@ export class CardForm<T> {
336
342
  await this.requestSave()
337
343
  }
338
344
 
345
+ /**
346
+ * Write every valid draft in one atomic form mutation, then re-seed from
347
+ * what the Host accepted. A draft the field does not accept stays on screen,
348
+ * unwritten, without holding the others back.
349
+ *
350
+ * The batch rides one mutate, so cross-field validate hooks (baseURL+model)
351
+ * judge it as a unit: the Host either applies every write or refuses the
352
+ * batch. The form contract answers a refusal or a skipped write with `false`
353
+ * (it recovers with a fresh Host view instead of throwing), so the outcome is
354
+ * judged twice: the answer itself, and then the settled snapshot read back
355
+ * one planned write at a time. One missed write fails the whole batch. A
356
+ * transport that rejects instead (the dsh-web bridge controller on a dead
357
+ * connection) reports through the same failure path with its rejection
358
+ * message. A batch that did not land puts its picks and clears back to the
359
+ * stored value and keeps its typed text, so the reader can correct it.
360
+ * @returns settlement after the mutation and the read-back.
361
+ */
339
362
  async save(): Promise<void> {
340
363
  const plan = this.plan()
341
364
  const valid = plan.filter((item): item is PlannedWrite & { judge: () => boolean } => item.judge !== undefined)
342
- if (plan.length === 0 || this.saving || valid.length !== plan.length) return
343
- // Snapshot the staged entries this save writes, so an edit staged while it
344
- // is in flight (which replaces the same key) survives: only delete the key
345
- // when the entry is still the one this save started from.
365
+ if (valid.length === 0 || this.saving) return
366
+ // Snapshot the staged entries this write carries, so an edit staged while
367
+ // it is in flight (which replaces the same key) survives: only settle the
368
+ // key when the entry is still the one this write started from.
346
369
  const pending = new Map<string, StagedEdit | undefined>()
347
- for (const item of plan) pending.set(item.field, this.staged.get(item.field))
370
+ for (const item of valid) pending.set(item.field, this.staged.get(item.field))
348
371
  this.saving = true
349
372
  this.failed = false
350
373
  this.failedReason = undefined
@@ -369,7 +392,8 @@ export class CardForm<T> {
369
392
  // whole save and keeps the drafts.
370
393
  const landed = accepted && failedReason === undefined && valid.every(item => item.judge())
371
394
  for (const [field, before] of pending) {
372
- if (landed && this.staged.get(field) === before) this.staged.delete(field)
395
+ if (this.staged.get(field) !== before) continue
396
+ if (landed || before === undefined || before.clear || this.specOf(field).entry === 'pick') this.staged.delete(field)
373
397
  }
374
398
  this.saving = false
375
399
  this.failed = !landed
@@ -381,9 +405,9 @@ export class CardForm<T> {
381
405
  }
382
406
 
383
407
  /**
384
- * Every staged edit a save would write. An entry whose draft is not a value
385
- * its field accepts carries no write: the form is still dirty, and the save
386
- * refuses rather than dropping the edit. A staged edit that matches the
408
+ * Every staged edit a write would carry. An entry whose draft is not a value
409
+ * its field accepts carries no write: the form is still dirty, and the draft
410
+ * stays on screen rather than being dropped. A staged edit that matches the
387
411
  * effective section is not a write at all.
388
412
  * @returns the planned writes, in the order the fields were staged.
389
413
  */
@@ -426,11 +450,29 @@ export class CardForm<T> {
426
450
  return !this.stored(field)
427
451
  }
428
452
 
453
+ /**
454
+ * Take one edit and schedule its write: a pick or a clear is written now,
455
+ * typed text once typing has rested for TYPE_PAUSE_MS.
456
+ */
429
457
  private stage(field: string, edit: StagedEdit): void {
430
458
  this.staged.set(field, edit)
431
459
  this.failed = false
432
460
  this.failedReason = undefined
433
461
  this.publish()
462
+ if (edit.clear || this.specOf(field).entry === 'pick') {
463
+ this.applyNow()
464
+ return
465
+ }
466
+ clearTimeout(this.typePause)
467
+ this.typePause = setTimeout(() => { this.applyNow() }, TYPE_PAUSE_MS)
468
+ }
469
+
470
+ /** Write every pending draft now, taking the place of a waiting pause. */
471
+ private applyNow(): void {
472
+ clearTimeout(this.typePause)
473
+ this.typePause = undefined
474
+ if (this.disposed) return
475
+ void this.requestSave()
434
476
  }
435
477
 
436
478
  private specOf(field: string): FieldSpec {
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Card attachments: the durable metadata a card keeps about the files and
3
+ * images it carries.
4
+ *
5
+ * The ledger stores METADATA only — never bytes, never base64, never a data
6
+ * URL, never an upload timestamp. The bytes live in the official attachment
7
+ * storage; this record says WHICH object, how large it is, and what it is, so
8
+ * an execution can resolve the object and the Host can prove the recorded
9
+ * claim against the storage before the claim reaches the ledger.
10
+ *
11
+ * The module is pure (no cordis, no runtime imports) so both halves — the Host
12
+ * ledger and the browser form — share one vocabulary and one set of limits.
13
+ */
14
+
15
+ /** What one attachment holds: a raster image or an arbitrary file. */
16
+ export type TaskAttachmentKind = 'image' | 'file'
17
+
18
+ /**
19
+ * One attachment of a card: identity, size and type, plus the digest of the
20
+ * exact bytes the Host stored.
21
+ *
22
+ * An image carries its intrinsic pixel size; a file carries neither. The
23
+ * display name is always the CANONICAL form (see
24
+ * {@link canonicalAttachmentName}): single-line, without any path part, so a
25
+ * name can never break the prompt an execution reads.
26
+ */
27
+ export interface TaskAttachment {
28
+ /** Whether the object is a raster image or an arbitrary file. */
29
+ kind: TaskAttachmentKind
30
+ /** Opaque storage identifier of the stored object; never a path or a URL. */
31
+ attachmentId: string
32
+ /** Canonical display name; never a local path, never multi-line. */
33
+ name: string
34
+ /** Exact stored byte length. */
35
+ bytes: number
36
+ /** Media type of the stored bytes. */
37
+ mediaType: string
38
+ /** Lowercase hex sha256 digest of the exact stored bytes. */
39
+ sha256: string
40
+ /** Intrinsic pixel width; images only, always positive. */
41
+ width?: number
42
+ /** Intrinsic pixel height; images only, always positive. */
43
+ height?: number
44
+ }
45
+
46
+ /** Maximum number of attachments one card may carry. */
47
+ export const TASK_ATTACHMENT_LIMIT = 8
48
+ /** Maximum byte length of one attachment (10 MiB). */
49
+ export const TASK_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024
50
+ /** Maximum byte length of all attachments of one card together (32 MiB). */
51
+ export const TASK_ATTACHMENT_TOTAL_MAX_BYTES = 32 * 1024 * 1024
52
+ /** Raster media types the official image path accepts. */
53
+ export const TASK_ATTACHMENT_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'] as const
54
+
55
+ /** Longest accepted display name of an attachment. */
56
+ const ATTACHMENT_NAME_MAX_LENGTH = 255
57
+ /** Longest accepted media type of an attachment. */
58
+ const ATTACHMENT_MEDIA_TYPE_MAX_LENGTH = 255
59
+ /** Longest accepted storage identifier of an attachment. */
60
+ const ATTACHMENT_ID_MAX_LENGTH = 512
61
+
62
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/
63
+ const MEDIA_TYPE_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/
64
+
65
+ /** Every key one attachment may carry. */
66
+ const ATTACHMENT_KEYS = ['kind', 'attachmentId', 'name', 'bytes', 'mediaType', 'sha256', 'width', 'height'] as const
67
+
68
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
69
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
70
+ }
71
+
72
+ /** Whether a value is a well-formed positive pixel count. */
73
+ function isPixelCount(value: unknown): value is number {
74
+ return typeof value === 'number' && Number.isInteger(value) && value > 0
75
+ }
76
+
77
+ /**
78
+ * The canonical display name of an attachment.
79
+ *
80
+ * A name reaches the ledger from two directions: the browser picks it, and an
81
+ * execution prompt reads it. Both make one form mandatory — the name must be
82
+ * a single line without any path part, so it can neither break out of the
83
+ * prompt line nor point at a directory.
84
+ *
85
+ * The canonical form is therefore: the LEAF of whatever path-like text was
86
+ * offered, every control character (a newline included) turned into a space,
87
+ * whitespace runs collapsed into one space, the result trimmed and bounded.
88
+ * An empty result becomes a fixed placeholder.
89
+ *
90
+ * The Host upload path canonicalizes the name BEFORE publishing it, and the
91
+ * wire gate accepts only a name that already IS canonical — so the name the
92
+ * ledger holds and the name the storage holds are the same string.
93
+ * @param value - the offered name.
94
+ * @returns the canonical name.
95
+ */
96
+ export function canonicalAttachmentName(value: unknown): string {
97
+ const raw = typeof value === 'string' ? value : ''
98
+ const leaf = raw.split(/[\\/]/).pop() ?? ''
99
+ const cleaned = leaf
100
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
101
+ .replace(/\s+/g, ' ')
102
+ .trim()
103
+ if (cleaned === '') return 'attachment'
104
+ return cleaned.slice(0, ATTACHMENT_NAME_MAX_LENGTH)
105
+ }
106
+
107
+ /**
108
+ * Whether an unknown value is a well-formed attachment (the STRICT gate: the
109
+ * wire path uses it, so a hand-written payload cannot smuggle an extra field
110
+ * onto the ledger, a path-like name, or an image without its pixel size).
111
+ * @param value - the candidate attachment.
112
+ * @returns whether the value is a usable attachment.
113
+ */
114
+ export function isTaskAttachment(value: unknown): value is TaskAttachment {
115
+ if (!isPlainObject(value)) return false
116
+ if (Object.keys(value).some(key => !(ATTACHMENT_KEYS as readonly string[]).includes(key))) return false
117
+ if (value.kind !== 'image' && value.kind !== 'file') return false
118
+ if (typeof value.attachmentId !== 'string') return false
119
+ const id = value.attachmentId
120
+ if (id === '' || id.length > ATTACHMENT_ID_MAX_LENGTH) return false
121
+ // A storage identifier is opaque: a value that looks like a path or a URL is
122
+ // refused rather than stored, so no consumer can mistake it for one.
123
+ if (id.includes('/') || id.includes('\\') || id.includes('..')) return false
124
+ if (typeof value.name !== 'string') return false
125
+ // The name must ALREADY be canonical: a payload that carries a path, a
126
+ // newline or a control character is refused rather than repaired, because
127
+ // the client and the Host must agree on one name.
128
+ if (value.name !== canonicalAttachmentName(value.name)) return false
129
+ if (typeof value.bytes !== 'number' || !Number.isInteger(value.bytes) || value.bytes < 0) return false
130
+ if (typeof value.mediaType !== 'string' || value.mediaType.length > ATTACHMENT_MEDIA_TYPE_MAX_LENGTH) return false
131
+ if (!MEDIA_TYPE_PATTERN.test(value.mediaType)) return false
132
+ // The media type is stored lowercased by the Host upload path, so the gate
133
+ // requires the same form the Host produces.
134
+ if (value.mediaType !== value.mediaType.toLowerCase()) return false
135
+ if (typeof value.sha256 !== 'string' || !SHA256_PATTERN.test(value.sha256)) return false
136
+ if (value.kind === 'image') {
137
+ if (!TASK_ATTACHMENT_IMAGE_MEDIA_TYPES.includes(value.mediaType.toLowerCase() as typeof TASK_ATTACHMENT_IMAGE_MEDIA_TYPES[number])) return false
138
+ // An image always carries its intrinsic pixel size: a record without one
139
+ // cannot address the stored object, so it is refused rather than
140
+ // completed with a manufactured 0x0.
141
+ if (!isPixelCount(value.width) || !isPixelCount(value.height)) return false
142
+ } else {
143
+ // A file carries no pixel size: the fields exist for images only.
144
+ if (value.width !== undefined || value.height !== undefined) return false
145
+ }
146
+ return true
147
+ }
148
+
149
+ /**
150
+ * Repair one persisted attachment entry: canonicalize its name and keep the
151
+ * fields that are usable. An entry that cannot be repaired — an unknown kind,
152
+ * a malformed identifier, an image without its pixel size — is dropped.
153
+ * @param value - the persisted entry.
154
+ * @returns the repaired attachment, or undefined when it cannot be repaired.
155
+ */
156
+ export function repairAttachment(value: unknown): TaskAttachment | undefined {
157
+ if (!isPlainObject(value)) return undefined
158
+ if (value.kind !== 'image' && value.kind !== 'file') return undefined
159
+ if (typeof value.attachmentId !== 'string') return undefined
160
+ const id = value.attachmentId
161
+ if (id === '' || id.length > ATTACHMENT_ID_MAX_LENGTH) return undefined
162
+ if (id.includes('/') || id.includes('\\') || id.includes('..')) return undefined
163
+ if (typeof value.bytes !== 'number' || !Number.isInteger(value.bytes) || value.bytes < 0) return undefined
164
+ if (typeof value.mediaType !== 'string' || !MEDIA_TYPE_PATTERN.test(value.mediaType)) return undefined
165
+ if (typeof value.sha256 !== 'string' || !SHA256_PATTERN.test(value.sha256)) return undefined
166
+ const name = canonicalAttachmentName(value.name)
167
+ if (value.kind === 'image') {
168
+ if (!TASK_ATTACHMENT_IMAGE_MEDIA_TYPES.includes(value.mediaType.toLowerCase() as typeof TASK_ATTACHMENT_IMAGE_MEDIA_TYPES[number])) return undefined
169
+ if (!isPixelCount(value.width) || !isPixelCount(value.height)) return undefined
170
+ return {
171
+ kind: 'image',
172
+ attachmentId: id,
173
+ name,
174
+ bytes: value.bytes,
175
+ mediaType: value.mediaType.toLowerCase(),
176
+ sha256: value.sha256,
177
+ width: value.width,
178
+ height: value.height,
179
+ }
180
+ }
181
+ if (value.width !== undefined || value.height !== undefined) return undefined
182
+ return {
183
+ kind: 'file',
184
+ attachmentId: id,
185
+ name,
186
+ bytes: value.bytes,
187
+ mediaType: value.mediaType.toLowerCase(),
188
+ sha256: value.sha256,
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Whether a list satisfies the card-wide attachment limits: the count, the
194
+ * per-item byte cap, and the total byte cap.
195
+ * @param attachments - the candidate list.
196
+ * @returns whether the list fits every limit.
197
+ */
198
+ export function attachmentsWithinLimits(attachments: readonly TaskAttachment[]): boolean {
199
+ if (attachments.length > TASK_ATTACHMENT_LIMIT) return false
200
+ let total = 0
201
+ for (const attachment of attachments) {
202
+ if (attachment.bytes > TASK_ATTACHMENT_MAX_BYTES) return false
203
+ total += attachment.bytes
204
+ }
205
+ return total <= TASK_ATTACHMENT_TOTAL_MAX_BYTES
206
+ }
207
+
208
+ /**
209
+ * Drop the repeated storage identifiers of a list, keeping the FIRST entry of
210
+ * each identifier.
211
+ *
212
+ * The storage is content-addressed, so the same bytes uploaded twice produce
213
+ * the same identifier. A list that carried the identifier twice would render
214
+ * two rows for one object and claim it twice against the card's limits, so the
215
+ * list is deduplicated at the boundary that can produce it.
216
+ * @param attachments - the candidate list.
217
+ * @returns the deduplicated list, in the original order.
218
+ */
219
+ export function dedupeAttachments(attachments: readonly TaskAttachment[]): TaskAttachment[] {
220
+ const seen = new Set<string>()
221
+ const unique: TaskAttachment[] = []
222
+ for (const attachment of attachments) {
223
+ if (seen.has(attachment.attachmentId)) continue
224
+ seen.add(attachment.attachmentId)
225
+ unique.push(attachment)
226
+ }
227
+ return unique
228
+ }
229
+
230
+ /**
231
+ * Whether an unknown value is a well-formed attachment LIST (the strict wire
232
+ * gate). The list must be non-empty: clearing attachments is expressed by
233
+ * omitting the field (create) or by an explicit null (update), never by an
234
+ * empty array. A list that repeats one storage identifier is refused: one
235
+ * object cannot be claimed twice.
236
+ * @param value - the candidate list.
237
+ * @returns whether the list may reach the ledger.
238
+ */
239
+ export function isTaskAttachmentList(value: unknown): value is TaskAttachment[] {
240
+ if (!Array.isArray(value)) return false
241
+ if (value.length === 0 || value.length > TASK_ATTACHMENT_LIMIT) return false
242
+ if (!value.every(isTaskAttachment)) return false
243
+ const list = value as TaskAttachment[]
244
+ if (new Set(list.map(attachment => attachment.attachmentId)).size !== list.length) return false
245
+ return attachmentsWithinLimits(list)
246
+ }
247
+
248
+ /**
249
+ * Repair a persisted attachment list: canonicalize the names, drop the
250
+ * entries that cannot be repaired, deduplicate the storage identifiers, and
251
+ * cap the count and the byte totals. Returns undefined when nothing usable
252
+ * remains, so the caller clears the field instead of storing an empty list —
253
+ * the same policy the tag and schedule repairs follow.
254
+ * @param value - the persisted value.
255
+ * @returns the repaired list, or undefined when nothing survives.
256
+ */
257
+ export function normalizeAttachments(value: unknown): TaskAttachment[] | undefined {
258
+ if (!Array.isArray(value)) return undefined
259
+ const repaired: TaskAttachment[] = []
260
+ const seen = new Set<string>()
261
+ let total = 0
262
+ for (const entry of value) {
263
+ const attachment = repairAttachment(entry)
264
+ if (attachment === undefined) continue
265
+ if (attachment.bytes > TASK_ATTACHMENT_MAX_BYTES) continue
266
+ if (total + attachment.bytes > TASK_ATTACHMENT_TOTAL_MAX_BYTES) continue
267
+ if (seen.has(attachment.attachmentId)) continue
268
+ seen.add(attachment.attachmentId)
269
+ total += attachment.bytes
270
+ repaired.push(attachment)
271
+ if (repaired.length >= TASK_ATTACHMENT_LIMIT) break
272
+ }
273
+ return repaired.length === 0 ? undefined : repaired
274
+ }
275
+
276
+ /**
277
+ * The attachment of a list whose storage identifier matches, or undefined.
278
+ * @param attachments - the list to search.
279
+ * @param attachmentId - the storage identifier to find.
280
+ * @returns the matching attachment, or undefined.
281
+ */
282
+ export function findAttachment(
283
+ attachments: readonly TaskAttachment[] | undefined,
284
+ attachmentId: string,
285
+ ): TaskAttachment | undefined {
286
+ return attachments?.find(attachment => attachment.attachmentId === attachmentId)
287
+ }