@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
@@ -9,6 +9,7 @@ import type { TaskBoardExtension } from './core/extension.ts';
9
9
  import { type ScheduleMode } from './core/tasks.ts';
10
10
  import { type ModelCatalogView, type VerificationContract, type VerificationSettings } from './core/verification.ts';
11
11
  import type { TaskPermission } from './core/handover.ts';
12
+ import { type ModelInfoResolver, type TaskBoardAttachmentStore } from './host/attachments.ts';
12
13
  /**
13
14
  * Why an enforced goal execution settled failed while its acceptance DID run:
14
15
  * attempts were recorded and none of them passed. The judge answered about the
@@ -61,6 +62,8 @@ export declare class TaskBoardHostService {
61
62
  readonly ledger: HostTaskLedger;
62
63
  readonly runner: HostExecutionRunner;
63
64
  readonly power: PowerInhibitor;
65
+ /** The official attachment storage, read live so a late mount is honoured. */
66
+ private readonly attachmentStore;
64
67
  private readonly listeners;
65
68
  /** The one recurring timer: the session-roster poll. */
66
69
  private pollTimer;
@@ -182,6 +185,18 @@ export declare class TaskBoardHostService {
182
185
  * no readable usage ledger. Defaults to the family usage ledger reader.
183
186
  */
184
187
  spendUsedToday?: (now: number) => number | undefined;
188
+ /**
189
+ * The official attachment storage, read at request time. Absent means the
190
+ * deployment stores no attachments: every attachment action is then
191
+ * refused and the board publishes no attachment limits.
192
+ */
193
+ attachments?: () => TaskBoardAttachmentStore | undefined;
194
+ /**
195
+ * The model-info reader the image preflight uses. Absent means the
196
+ * deployment serves no model information, and a route whose modalities are
197
+ * unknown is allowed.
198
+ */
199
+ modelInfo?: () => ModelInfoResolver | undefined;
185
200
  });
186
201
  start(): void;
187
202
  /**
@@ -194,6 +209,15 @@ export declare class TaskBoardHostService {
194
209
  * @param sessionPollSeconds - roster-poll cadence in seconds (clamped).
195
210
  */
196
211
  setConfiguration(active: boolean, preventIdleSleep: boolean, sessionPollSeconds?: number): void;
212
+ /**
213
+ * The board's published snapshot.
214
+ *
215
+ * Every read path serializes this object — the HTTP `state` answer, the
216
+ * `action` answer through {@link apply}, and the remote bridge's
217
+ * `board.snapshot` — so a provider's integration credentials are stripped
218
+ * once, here, instead of at each exit. The ledger keeps them verbatim for the
219
+ * provider's own in-process read.
220
+ */
197
221
  snapshot(): TaskBoardSnapshot;
198
222
  /**
199
223
  * Admit one external provider. Idempotent by extension id; the returned
@@ -235,6 +259,25 @@ export declare class TaskBoardHostService {
235
259
  * @returns the action, with an inherited workspace on a root creation.
236
260
  */
237
261
  private withInheritedWorkspace;
262
+ /**
263
+ * Apply an action whose attachments the Host proved against the official
264
+ * storage first.
265
+ *
266
+ * This is the board's trust boundary for attachment metadata: the browser
267
+ * asserts the size, the type and the digest of every object it uploaded, and
268
+ * the Host reads the stored objects back (an image is compared, a file is
269
+ * streamed and its digest recomputed) before the ledger commits the claim.
270
+ * An attachment the storage cannot prove is refused, so a spoofed client
271
+ * claim never becomes a stored fact.
272
+ */
273
+ applyVerified(requestId: string, action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot>;
274
+ /**
275
+ * Prove every attachment of an action against the official storage.
276
+ *
277
+ * An action without attachments is untouched: the board keeps working in a
278
+ * deployment that serves no attachment storage at all.
279
+ */
280
+ private verifyActionAttachments;
238
281
  apply(requestId: string, action: Extract<TaskBoardAction, {
239
282
  kind: 'extension-action';
240
283
  }>, initiator?: string): Promise<TaskBoardSnapshot>;
@@ -311,9 +354,25 @@ export declare class TaskBoardHostService {
311
354
  * reads no roster at all, and a read that fails mints a fresh conversation
312
355
  * exactly as an unknown roster always did.
313
356
  * @param task - the task about to run.
357
+ * @param force - continue the settled session regardless of the card's own
358
+ * opt-in (a rework), which the reuse rule accepts without waiving any of its
359
+ * evidence conditions.
314
360
  * @returns the session id to continue in, or undefined for a fresh session.
315
361
  */
316
362
  private reuseSessionFor;
363
+ /**
364
+ * The session a rework continues, or the refusal that says why it cannot.
365
+ *
366
+ * A rework exists for one conversation — the one the reviewer read before
367
+ * sending the work back — so the evidence that this Host still reaches it is
368
+ * required, exactly as it is for a card that opted into reuse. What a rework
369
+ * does NOT get is the fresh-conversation fallback: launching there would hand
370
+ * the reviewer's instructions to an agent that never saw the work, so the run
371
+ * fails with a readable reason instead.
372
+ * @param task - the card being reworked.
373
+ * @returns the session id this rework continues in.
374
+ */
375
+ private reworkSessionFor;
317
376
  /** Reuse the session list this poll already fetched: one list RPC per tick, not 1 + E. */
318
377
  private reconcileExecutions;
319
378
  /**
@@ -12,6 +12,7 @@ import type { LlmRuntime } from '@deepseek-ai/dsh-llm';
12
12
  import { type HostTimerFace } from './host-service.ts';
13
13
  import { type TaskPermission } from './core/tasks.ts';
14
14
  import { type TaskBoardConnectionTrust } from './host-routes.ts';
15
+ import type { ModelInfoResolver, TaskBoardAttachmentStore } from './host/attachments.ts';
15
16
  /** Default environment variable holding the authenticated proxy token. */
16
17
  export declare const DEFAULT_PROXY_TOKEN_ENV = "DSH_TASK_BOARD_PROXY_TOKEN";
17
18
  export declare const inject: string[];
@@ -361,6 +362,28 @@ export declare function resolveHostDefaultPermission(ctx: Context): TaskPermissi
361
362
  * @returns the llm service, or undefined when this deployment serves none.
362
363
  */
363
364
  export declare function resolveLlmRuntime(ctx: Context): LlmRuntime | undefined;
365
+ /**
366
+ * Resolve the optional attachment storage.
367
+ *
368
+ * The board does not inject the service: a deployment without one must still
369
+ * mount the board, and every attachment surface then answers with a typed
370
+ * "storage unavailable" failure instead of the plugin failing to load.
371
+ * @param ctx - the plugin context.
372
+ * @returns the attachment storage, or undefined when this deployment serves none.
373
+ */
374
+ export declare function resolveAttachmentStore(ctx: Context): TaskBoardAttachmentStore | undefined;
375
+ /**
376
+ * The model-info reader the image preflight uses.
377
+ *
378
+ * It asks the OFFICIAL model service about one exact route. The model catalog
379
+ * the board already publishes carries no modality information and must not be
380
+ * used to answer that question: only the model's own declared input
381
+ * modalities can refuse an image route, and a route whose modalities cannot be
382
+ * read is UNKNOWN and therefore allowed.
383
+ * @param ctx - the plugin context.
384
+ * @returns the reader, or undefined when the deployment serves no model service.
385
+ */
386
+ export declare function resolveModelInfoReader(ctx: Context): ModelInfoResolver | undefined;
364
387
  /**
365
388
  * The subset of `sessionController` the board uses to wake a cold persisted
366
389
  * session before running a slash command on it (issue #1861).
@@ -3,9 +3,11 @@ import type { SetSchedulePatch } from './core/use-cases/task-schedule.ts';
3
3
  import { type NewTaskInput, type TaskPermission, type TaskRecord, type TaskStatus } from './core/tasks.ts';
4
4
  import { type TaskBoardExtensionPayload } from './core/extension.ts';
5
5
  import { type ModelCatalogView, type VerificationContract, type VerificationSettings } from './core/verification.ts';
6
- export declare const TASK_BOARD_SCHEMA_VERSION: 6;
7
- /** Ledger documents written before v6; loaded once and migrated on startup. */
8
- export declare const TASK_BOARD_LEGACY_SCHEMA_VERSION: 5;
6
+ export declare const TASK_BOARD_SCHEMA_VERSION: 7;
7
+ /** Ledger documents written before v7; loaded once and migrated on startup. */
8
+ export declare const TASK_BOARD_LEGACY_SCHEMA_VERSION: 6;
9
+ /** Ledger documents written before v6 (the scheduling mode and run budget). */
10
+ export declare const TASK_BOARD_PRE_RUN_BUDGET_SCHEMA_VERSION: 5;
9
11
  /** Ledger documents written before v5; migrated through the v5 normalization too. */
10
12
  export declare const TASK_BOARD_PRE_ACCEPTANCE_SCHEMA_VERSION: 4;
11
13
  /** Ledger documents written before v4; migrated through the v4 normalization too. */
@@ -21,9 +23,10 @@ export declare const TASK_BOARD_OLDEST_SCHEMA_VERSION: 2;
21
23
  export declare const TASK_BOARD_ZONE_STAMP_SCHEMA_VERSION: 4;
22
24
  /**
23
25
  * Every older generation the loader migrates in place. v5 only added the
24
- * per-execution acceptance block and v6 only added the scheduling mode and run
25
- * budget, so the migration is the normalization pass that re-validates each
26
- * row; a document from any listed generation upgrades losslessly.
26
+ * per-execution acceptance block, v6 only added the scheduling mode and run
27
+ * budget, and v7 only added the card attachment metadata, so the migration is
28
+ * the normalization pass that re-validates each row; a document from any
29
+ * listed generation upgrades losslessly.
27
30
  */
28
31
  export declare const TASK_BOARD_MIGRATABLE_SCHEMA_VERSIONS: readonly number[];
29
32
  export declare const TASK_BOARD_API_PREFIX = "/api/task-board";
@@ -87,6 +90,26 @@ export interface TaskBoardSnapshot {
87
90
  * The board forwards them verbatim; it never interprets their shape.
88
91
  */
89
92
  extensions?: Record<string, unknown>;
93
+ /**
94
+ * The attachment limits this deployment enforces, so the browser can refuse
95
+ * an oversized selection before it uploads anything. The board's own caps
96
+ * are the ceiling; a deployment whose attachment storage publishes stricter
97
+ * image limits lowers the bounds it publishes here.
98
+ */
99
+ attachmentLimits?: {
100
+ /** Maximum number of attachments one card may carry. */
101
+ maxAttachments: number;
102
+ /** Maximum byte length of one attachment. */
103
+ maxBytes: number;
104
+ /** Maximum byte length of all attachments of one card together. */
105
+ maxTotalBytes: number;
106
+ /** Maximum number of IMAGES one card may carry (the official per-message budget). */
107
+ maxImages: number;
108
+ /** Maximum byte length of one image. */
109
+ maxImageBytes: number;
110
+ /** Maximum byte length of all images of one card together (the official per-message budget). */
111
+ maxMessageImageBytes: number;
112
+ };
90
113
  }
91
114
  /**
92
115
  * Body of `GET {TASK_BOARD_API_PREFIX}/verification`: the acceptance settings the
@@ -184,6 +207,16 @@ export type TaskBoardAction = {
184
207
  } | {
185
208
  kind: 'rerun';
186
209
  taskId: string;
210
+ }
211
+ /**
212
+ * Re-run an executed card in its own session, carrying rework instructions as
213
+ * this run's additional input. Every run gate applies exactly as it does to
214
+ * `rerun`, and the card's frozen content is never rewritten.
215
+ */
216
+ | {
217
+ kind: 'rework';
218
+ taskId: string;
219
+ instructions: string;
187
220
  } | {
188
221
  kind: 'confirm-permission';
189
222
  taskId: string;
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Task Board",
4
+ "description": "Drag tasks across columns; cron runs them for real."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "任务看板",
4
+ "description": "拖拽管理任务并按 Cron 真实执行"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-client-ui-task-board",
3
3
  "description": "Host-authoritative task board for the DSH Web GUI with real session execution, Host cron scheduling, and optional cross-platform idle-sleep protection; mounted without DSH source changes.",
4
- "version": "0.4.12",
4
+ "version": "0.4.14",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -16,6 +16,8 @@
16
16
  "default": "./lib/client.js"
17
17
  },
18
18
  "./src/*": "./src/*",
19
+ "./locale/en.json": "./locale/en.json",
20
+ "./locale/zh.json": "./locale/zh.json",
19
21
  "./package.json": "./package.json"
20
22
  },
21
23
  "dsh": {
@@ -51,6 +53,7 @@
51
53
  "@deepseek-ai/cordis": "^4.0.5",
52
54
  "@deepseek-ai/dsh-agent": "^0.2.1-rc.3",
53
55
  "@deepseek-ai/dsh-agent-preset-registry": "^0.2.1-rc.3",
56
+ "@deepseek-ai/dsh-attachment": "^0.2.1-rc.3",
54
57
  "@deepseek-ai/dsh-api-gateway": "^0.2.1-rc.3",
55
58
  "@deepseek-ai/dsh-api-remotes": "^0.2.1-rc.3",
56
59
  "@deepseek-ai/dsh-api-session-controller": "^0.2.1-rc.3",
@@ -89,7 +92,8 @@
89
92
  "lib/**/*.d.ts.map",
90
93
  "src",
91
94
  "cordis.patch.yml",
92
- "icon.svg"
95
+ "icon.svg",
96
+ "locale"
93
97
  ],
94
98
  "license": "Apache-2.0",
95
99
  "repository": {
@@ -18,6 +18,7 @@ import { CardDefaultPresetField } from './CardDefaultPresetField.tsx'
18
18
  import { PluginSettingsCard, BooleanField, ChoiceField, ValueField } from './PluginSettingsCard.tsx'
19
19
  import {
20
20
  modelChoiceRows,
21
+ modelDisplayLabel,
21
22
  modelOptionsFromCatalog,
22
23
  reasoningEffortsFor,
23
24
  reasoningHintKey,
@@ -416,7 +417,16 @@ export function TaskBoardSettingsCard(props: TaskBoardSettingsCardProps) {
416
417
  },
417
418
  ...catalog.groups.flatMap(group => group.models.map(model => ({
418
419
  value: group.id + '/' + model.id,
419
- label: (group.name ?? group.id) + ' · ' + (model.name ?? model.id),
420
+ // The shared display form: the model name first, then the provider
421
+ // that publishes it, so two providers offering one model name stay
422
+ // tellable apart.
423
+ label: modelDisplayLabel({
424
+ id: group.id + '/' + model.id,
425
+ name: model.name ?? model.id,
426
+ // The provider is the group id — the same token the route pins,
427
+ // and the one every other model picker names.
428
+ provider: group.id,
429
+ }),
420
430
  }))),
421
431
  ]
422
432
  const stagedRoute = parseModelRoute(stagedSettings.model) ?? (inheritRoute === undefined ? undefined : { provider: inheritRoute.provider, model: inheritRoute.model })
@@ -0,0 +1,383 @@
1
+ /**
2
+ * The attachment field of the create and edit forms.
3
+ *
4
+ * A file the user picks is STAGED locally first: the form shows a preview,
5
+ * the name and the size, and nothing leaves the browser until the card is
6
+ * saved. The upload therefore happens on save, not on selection — a card the
7
+ * user abandons never leaves a stored object behind.
8
+ *
9
+ * Three input modes are supported: drag and drop, paste, and the file picker.
10
+ * All three end in the same staged list.
11
+ */
12
+ import { useEffect, useRef, useState } from 'react'
13
+ import {
14
+ TASK_ATTACHMENT_IMAGE_MEDIA_TYPES,
15
+ TASK_ATTACHMENT_LIMIT,
16
+ TASK_ATTACHMENT_MAX_BYTES,
17
+ TASK_ATTACHMENT_TOTAL_MAX_BYTES,
18
+ type TaskAttachment,
19
+ type TaskAttachmentKind,
20
+ } from '../../core/attachment.ts'
21
+ import { attachmentImageUrl } from '../host-api.ts'
22
+ import { t } from '../locales.ts'
23
+ import css from '../board.module.css'
24
+ import { IconClose } from './icons.tsx'
25
+
26
+ /** One file the user staged locally; it is uploaded when the card is saved. */
27
+ export interface StagedAttachment {
28
+ /** Stable id of the staged row (a monotonic counter, never a clock reading). */
29
+ id: string
30
+ /** The picked file. */
31
+ file: File
32
+ /** Whether the file is uploaded as an image or as a verbatim file. */
33
+ kind: TaskAttachmentKind
34
+ /** Display name of the file. */
35
+ name: string
36
+ /** Byte length of the file. */
37
+ bytes: number
38
+ /** Declared media type of the file. */
39
+ mediaType: string
40
+ /** Local object URL of the preview; images only. */
41
+ previewUrl?: string
42
+ /** True while the file is being uploaded. */
43
+ pending?: boolean
44
+ /** Why the upload failed, when it did. */
45
+ error?: string
46
+ }
47
+
48
+ /** What the card will carry once the form is saved. */
49
+ export interface AttachmentSelection {
50
+ /** The attachments already stored on the card and kept by the user. */
51
+ persisted: TaskAttachment[]
52
+ /** The files staged locally and uploaded on save. */
53
+ staged: StagedAttachment[]
54
+ }
55
+
56
+ /** The limits the deployment publishes for attachments. */
57
+ export interface AttachmentLimits {
58
+ maxAttachments: number
59
+ maxBytes: number
60
+ maxTotalBytes: number
61
+ /** Maximum number of IMAGES one card may carry (the official per-message budget). */
62
+ maxImages: number
63
+ /** Maximum byte length of one image. */
64
+ maxImageBytes: number
65
+ /** Maximum byte length of all images of one card together. */
66
+ maxMessageImageBytes: number
67
+ }
68
+
69
+ /** The board's own limits, used when the deployment publishes none. */
70
+ export const DEFAULT_ATTACHMENT_LIMITS: AttachmentLimits = {
71
+ maxAttachments: TASK_ATTACHMENT_LIMIT,
72
+ maxBytes: TASK_ATTACHMENT_MAX_BYTES,
73
+ maxTotalBytes: TASK_ATTACHMENT_TOTAL_MAX_BYTES,
74
+ maxImages: TASK_ATTACHMENT_LIMIT,
75
+ maxImageBytes: TASK_ATTACHMENT_MAX_BYTES,
76
+ maxMessageImageBytes: TASK_ATTACHMENT_TOTAL_MAX_BYTES,
77
+ }
78
+
79
+ /** A human-readable byte size. */
80
+ export function formatAttachmentBytes(bytes: number): string {
81
+ if (bytes < 1024) return `${bytes} B`
82
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
83
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`
84
+ }
85
+
86
+ /**
87
+ * Whether a picked file is uploaded as an image.
88
+ *
89
+ * Only the raster types the official image path accepts are images; every
90
+ * other file is stored verbatim.
91
+ */
92
+ export function attachmentKindOf(file: File): TaskAttachmentKind {
93
+ const type = file.type.toLowerCase()
94
+ return TASK_ATTACHMENT_IMAGE_MEDIA_TYPES.includes(type as typeof TASK_ATTACHMENT_IMAGE_MEDIA_TYPES[number])
95
+ ? 'image'
96
+ : 'file'
97
+ }
98
+
99
+ /** One row of the attachment list: a stored attachment or a staged file. */
100
+ interface AttachmentRow {
101
+ /** Stable key of the row. */
102
+ key: string
103
+ /** The stored attachment, when the row shows one. */
104
+ attachment?: TaskAttachment
105
+ /** The staged file, when the row shows one. */
106
+ staged?: StagedAttachment
107
+ }
108
+
109
+ /** The byte total of a selection: the stored attachments plus the staged files. */
110
+ function totalBytesOf(selection: AttachmentSelection): number {
111
+ return selection.persisted.reduce((sum, attachment) => sum + attachment.bytes, 0)
112
+ + selection.staged.reduce((sum, staged) => sum + staged.bytes, 0)
113
+ }
114
+
115
+ /** The byte total of the IMAGES of a selection. */
116
+ function imageBytesOf(selection: AttachmentSelection): number {
117
+ return selection.persisted
118
+ .filter(attachment => attachment.kind === 'image')
119
+ .reduce((sum, attachment) => sum + attachment.bytes, 0)
120
+ + selection.staged
121
+ .filter(staged => staged.kind === 'image')
122
+ .reduce((sum, staged) => sum + staged.bytes, 0)
123
+ }
124
+
125
+ /** The number of IMAGES of a selection. */
126
+ function imageCountOf(selection: AttachmentSelection): number {
127
+ return selection.persisted.filter(attachment => attachment.kind === 'image').length
128
+ + selection.staged.filter(staged => staged.kind === 'image').length
129
+ }
130
+
131
+ /**
132
+ * The staged files the form already holds.
133
+ *
134
+ * The identity is the File OBJECT, never its metadata: two different files can
135
+ * share a name, a size, a type and a modification time, and inferring byte
136
+ * identity from those four would silently discard one of them. The form
137
+ * therefore stages every distinct File it is handed.
138
+ *
139
+ * The content identity that actually matters — the storage identifier the Host
140
+ * answers with — is applied AFTER the upload, where it is authoritative
141
+ * (see the core dedupe). The only case the form skips is the very same File
142
+ * object handed over twice, which is the same row twice.
143
+ */
144
+ function stagedFileSet(staged: readonly StagedAttachment[]): Set<File> {
145
+ return new Set(staged.map(entry => entry.file))
146
+ }
147
+
148
+ /**
149
+ * The attachment field of a card form.
150
+ *
151
+ * The component owns the local staging only: the selection it reports is what
152
+ * the card will carry, and the parent uploads the staged files on save.
153
+ */
154
+ export function AttachmentField({
155
+ selection,
156
+ onChange,
157
+ limits,
158
+ disabled = false,
159
+ onError,
160
+ }: {
161
+ /** What the card currently carries and what is staged on top of it. */
162
+ selection: AttachmentSelection
163
+ /** Receives the new selection after every change. */
164
+ onChange: (selection: AttachmentSelection) => void
165
+ /** The deployment limits; the board's own limits are used when absent. */
166
+ limits?: AttachmentLimits
167
+ /** Whether the field refuses new input. */
168
+ disabled?: boolean
169
+ /** Receives the reason a selection was refused. */
170
+ onError?: (message: string) => void
171
+ }) {
172
+ const effective = limits ?? DEFAULT_ATTACHMENT_LIMITS
173
+ const inputRef = useRef<HTMLInputElement | null>(null)
174
+ const objectUrls = useRef<string[]>([])
175
+ const counter = useRef(0)
176
+ const [dragging, setDragging] = useState(false)
177
+
178
+ // The object URLs belong to this component: they are released when the form
179
+ // closes, so a discarded card leaves no preview behind.
180
+ useEffect(() => () => {
181
+ for (const url of objectUrls.current) URL.revokeObjectURL(url)
182
+ objectUrls.current = []
183
+ }, [])
184
+
185
+ const addFiles = (files: readonly File[]): void => {
186
+ if (disabled || files.length === 0) return
187
+ const staged = [...selection.staged]
188
+ // Only the very same File object is skipped: the browser hands the same
189
+ // object again when a picker reports one selection twice, and that is the
190
+ // one case where a second row would duplicate the first. Two DIFFERENT
191
+ // files that merely share their metadata are two files, and both stage.
192
+ const seen = stagedFileSet(staged)
193
+ let total = totalBytesOf(selection)
194
+ let imageBytes = imageBytesOf(selection)
195
+ let imageCount = imageCountOf(selection)
196
+ let added = 0
197
+ for (const file of files) {
198
+ if (seen.has(file)) continue
199
+ if (selection.persisted.length + staged.length >= effective.maxAttachments) {
200
+ onError?.(t('new.attachments.limitCount', { count: String(effective.maxAttachments) }))
201
+ break
202
+ }
203
+ const kind = attachmentKindOf(file)
204
+ const limit = kind === 'image'
205
+ ? Math.min(effective.maxBytes, effective.maxImageBytes ?? effective.maxBytes)
206
+ : effective.maxBytes
207
+ if (file.size > limit) {
208
+ onError?.(t('new.attachments.limitSize', { name: file.name, size: formatAttachmentBytes(limit) }))
209
+ continue
210
+ }
211
+ if (total + file.size > effective.maxTotalBytes) {
212
+ onError?.(t('new.attachments.limitTotal', { size: formatAttachmentBytes(effective.maxTotalBytes) }))
213
+ break
214
+ }
215
+ // The official per-message image budget: the count of images and their
216
+ // total bytes are what one prompt carries.
217
+ if (kind === 'image') {
218
+ if (imageCount + 1 > effective.maxImages) {
219
+ onError?.(t('new.attachments.limitImages', { count: String(effective.maxImages) }))
220
+ break
221
+ }
222
+ if (imageBytes + file.size > effective.maxMessageImageBytes) {
223
+ onError?.(t('new.attachments.limitImageBytes', { size: formatAttachmentBytes(effective.maxMessageImageBytes) }))
224
+ break
225
+ }
226
+ }
227
+ const previewUrl = kind === 'image' && typeof URL.createObjectURL === 'function'
228
+ ? URL.createObjectURL(file)
229
+ : undefined
230
+ if (previewUrl !== undefined) objectUrls.current.push(previewUrl)
231
+ counter.current += 1
232
+ seen.add(file)
233
+ staged.push({
234
+ id: `staged-${counter.current}`,
235
+ file,
236
+ kind,
237
+ name: file.name,
238
+ bytes: file.size,
239
+ mediaType: file.type,
240
+ ...(previewUrl === undefined ? {} : { previewUrl }),
241
+ })
242
+ total += file.size
243
+ if (kind === 'image') {
244
+ imageBytes += file.size
245
+ imageCount += 1
246
+ }
247
+ added += 1
248
+ }
249
+ if (added > 0) onChange({ ...selection, staged })
250
+ }
251
+
252
+ const removeStaged = (id: string): void => {
253
+ const target = selection.staged.find(staged => staged.id === id)
254
+ if (target?.previewUrl !== undefined) {
255
+ URL.revokeObjectURL(target.previewUrl)
256
+ objectUrls.current = objectUrls.current.filter(url => url !== target.previewUrl)
257
+ }
258
+ onChange({ ...selection, staged: selection.staged.filter(staged => staged.id !== id) })
259
+ }
260
+
261
+ const removePersisted = (attachmentId: string): void => {
262
+ onChange({
263
+ ...selection,
264
+ persisted: selection.persisted.filter(attachment => attachment.attachmentId !== attachmentId),
265
+ })
266
+ }
267
+
268
+ // One row per attachment: the stored ones and the staged files, in the
269
+ // order the user sees them.
270
+ const rows: AttachmentRow[] = [
271
+ ...selection.persisted.map(attachment => ({ key: attachment.attachmentId, attachment })),
272
+ ...selection.staged.map(staged => ({ key: staged.id, staged })),
273
+ ]
274
+
275
+ return (
276
+ <div className={css.field} data-dsh-part="form-section">
277
+ <span className={css.fieldLabel}>{t('new.attachments')}</span>
278
+ <span className={css.fieldHint}>{t('new.attachmentsHint')}</span>
279
+ <div
280
+ className={css.attachmentDrop}
281
+ // A disabled field is not styled as a drop target: the drag state is
282
+ // the field's own, and a field that refuses input must not invite it.
283
+ data-state={dragging && !disabled ? 'active' : undefined}
284
+ data-disabled={disabled ? 'true' : undefined}
285
+ // The region is focusable and keyboard-operable: Enter or Space opens
286
+ // the picker. The button inside it owns its own activation, so a key
287
+ // press there is not handled twice. A DISABLED field leaves the tab
288
+ // order and says so, instead of staying focusable and inert.
289
+ tabIndex={disabled ? -1 : 0}
290
+ aria-disabled={disabled ? true : undefined}
291
+ aria-label={t('new.attachments.drop')}
292
+ onKeyDown={event => {
293
+ if (disabled) return
294
+ if (event.target !== event.currentTarget) return
295
+ if (event.key !== 'Enter' && event.key !== ' ') return
296
+ event.preventDefault()
297
+ inputRef.current?.click()
298
+ }}
299
+ onDragOver={event => {
300
+ event.preventDefault()
301
+ if (disabled) return
302
+ setDragging(true)
303
+ }}
304
+ onDragLeave={() => { if (!disabled) setDragging(false) }}
305
+ onDrop={event => {
306
+ event.preventDefault()
307
+ setDragging(false)
308
+ addFiles(Array.from(event.dataTransfer?.files ?? []))
309
+ }}
310
+ onPaste={event => {
311
+ const files = Array.from(event.clipboardData?.files ?? [])
312
+ if (files.length === 0) return
313
+ event.preventDefault()
314
+ addFiles(files)
315
+ }}
316
+ >
317
+ <span className={css.attachmentDropHint}>{t('new.attachments.drop')}</span>
318
+ <input
319
+ ref={inputRef}
320
+ type="file"
321
+ multiple
322
+ hidden
323
+ // A disabled field cannot be opened, so the picker itself is
324
+ // disabled: the region never opens a picker it must not open.
325
+ disabled={disabled}
326
+ onChange={event => {
327
+ addFiles(Array.from(event.target.files ?? []))
328
+ event.target.value = ''
329
+ }}
330
+ />
331
+ <button
332
+ type="button"
333
+ className={css.ghostButton}
334
+ disabled={disabled}
335
+ onClick={() => {
336
+ if (disabled) return
337
+ inputRef.current?.click()
338
+ }}
339
+ >
340
+ {t('new.attachments.pick')}
341
+ </button>
342
+ </div>
343
+ {rows.length > 0 && (
344
+ <ul className={css.attachmentList}>
345
+ {rows.map(row => (
346
+ <li className={css.attachmentRow} key={row.key}>
347
+ {row.attachment !== undefined && row.attachment.kind === 'image'
348
+ ? <img className={css.attachmentThumb} src={attachmentImageUrl(row.attachment.attachmentId)} alt={row.attachment.name} />
349
+ : null}
350
+ {row.staged !== undefined && row.staged.kind === 'image' && row.staged.previewUrl !== undefined
351
+ ? <img className={css.attachmentThumb} src={row.staged.previewUrl} alt={row.staged.name} />
352
+ : null}
353
+ <span className={css.attachmentName}>
354
+ {row.attachment?.name ?? row.staged?.name}
355
+ <span className={css.attachmentMeta}>
356
+ {' '}
357
+ {formatAttachmentBytes(row.attachment?.bytes ?? row.staged?.bytes ?? 0)}
358
+ {row.staged?.pending === true ? ` · ${t('new.attachments.uploading')}` : ''}
359
+ {row.staged?.error !== undefined ? ` · ${row.staged.error}` : ''}
360
+ </span>
361
+ </span>
362
+ <button
363
+ type="button"
364
+ className={css.iconButton}
365
+ // A pending submission owns the set it is about to send: the
366
+ // removal controls are disabled while it is in flight, so the
367
+ // submitted set cannot race a user edit.
368
+ disabled={disabled}
369
+ aria-label={t('new.attachments.remove', { name: row.attachment?.name ?? row.staged?.name ?? '' })}
370
+ onClick={() => {
371
+ if (row.attachment !== undefined) removePersisted(row.attachment.attachmentId)
372
+ else if (row.staged !== undefined) removeStaged(row.staged.id)
373
+ }}
374
+ >
375
+ <IconClose size={14} />
376
+ </button>
377
+ </li>
378
+ ))}
379
+ </ul>
380
+ )}
381
+ </div>
382
+ )
383
+ }