@fish-under-sea/dsh-client-ui-task-board-fish 0.0.0-stage → 0.5.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 (165) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +202 -2
  4. package/README.zh.md +203 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +12941 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +10471 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +144 -0
  11. package/lib/types/client/TaskBoardSettingsCard.d.ts +92 -0
  12. package/lib/types/client/apply-guard.d.ts +25 -0
  13. package/lib/types/client/board/ClampedMarkdown.d.ts +3 -0
  14. package/lib/types/client/board/ConfirmDialog.d.ts +15 -0
  15. package/lib/types/client/board/EditTaskModal.d.ts +17 -0
  16. package/lib/types/client/board/LinkSubtaskModal.d.ts +14 -0
  17. package/lib/types/client/board/NewTaskModal.d.ts +26 -0
  18. package/lib/types/client/board/TagManagerModal.d.ts +26 -0
  19. package/lib/types/client/board/TaskBoard.d.ts +26 -0
  20. package/lib/types/client/board/TaskCard.d.ts +36 -0
  21. package/lib/types/client/board/TaskDetail.d.ts +9 -0
  22. package/lib/types/client/board/TaskForm.d.ts +72 -0
  23. package/lib/types/client/board/VerificationReport.d.ts +23 -0
  24. package/lib/types/client/board/card-view.d.ts +113 -0
  25. package/lib/types/client/board/icons.d.ts +32 -0
  26. package/lib/types/client/board/overlay.d.ts +69 -0
  27. package/lib/types/client/board/parse-model-pref.d.ts +4 -0
  28. package/lib/types/client/board/preset-label.d.ts +22 -0
  29. package/lib/types/client/board/status-key.d.ts +19 -0
  30. package/lib/types/client/board/task-markdown.d.ts +19 -0
  31. package/lib/types/client/host-api.d.ts +63 -0
  32. package/lib/types/client/index.d.ts +128 -0
  33. package/lib/types/client/locales.d.ts +443 -0
  34. package/lib/types/client/main-session.d.ts +32 -0
  35. package/lib/types/client/native-panel.d.ts +48 -0
  36. package/lib/types/client/plugin-card-seat.d.ts +108 -0
  37. package/lib/types/client/schedule-presets.d.ts +10 -0
  38. package/lib/types/client/schedule-zone.d.ts +97 -0
  39. package/lib/types/client/seats.d.ts +18 -0
  40. package/lib/types/client/service.d.ts +32 -0
  41. package/lib/types/client/settings-entry-form.d.ts +49 -0
  42. package/lib/types/client/settings-form.d.ts +213 -0
  43. package/lib/types/core/controller.d.ts +373 -0
  44. package/lib/types/core/degraded-reason.d.ts +46 -0
  45. package/lib/types/core/extension.d.ts +283 -0
  46. package/lib/types/core/freeze-snapshot.d.ts +71 -0
  47. package/lib/types/core/handover.d.ts +70 -0
  48. package/lib/types/core/issue-form.d.ts +16 -0
  49. package/lib/types/core/package-name.d.ts +9 -0
  50. package/lib/types/core/poll-cadence.d.ts +31 -0
  51. package/lib/types/core/schedule.d.ts +124 -0
  52. package/lib/types/core/session-reuse.d.ts +24 -0
  53. package/lib/types/core/store.d.ts +64 -0
  54. package/lib/types/core/subtask.d.ts +141 -0
  55. package/lib/types/core/tasks.d.ts +601 -0
  56. package/lib/types/core/use-cases/task-archive.d.ts +20 -0
  57. package/lib/types/core/use-cases/task-create.d.ts +27 -0
  58. package/lib/types/core/use-cases/task-delete.d.ts +27 -0
  59. package/lib/types/core/use-cases/task-parent.d.ts +21 -0
  60. package/lib/types/core/use-cases/task-schedule.d.ts +96 -0
  61. package/lib/types/core/use-cases/task-tag.d.ts +48 -0
  62. package/lib/types/core/use-cases/task-update.d.ts +56 -0
  63. package/lib/types/core/verification-budget.d.ts +52 -0
  64. package/lib/types/core/verification.d.ts +753 -0
  65. package/lib/types/core/workspace-target.d.ts +41 -0
  66. package/lib/types/dsh-home.d.ts +16 -0
  67. package/lib/types/host/agent-tools.d.ts +27 -0
  68. package/lib/types/host/extension-registry.d.ts +111 -0
  69. package/lib/types/host/llm-dispatch.d.ts +63 -0
  70. package/lib/types/host/verification-gate.d.ts +95 -0
  71. package/lib/types/host/verification-runner.d.ts +139 -0
  72. package/lib/types/host/workspace-evidence.d.ts +53 -0
  73. package/lib/types/host-ai.d.ts +51 -0
  74. package/lib/types/host-ledger.d.ts +385 -0
  75. package/lib/types/host-routes.d.ts +36 -0
  76. package/lib/types/host-runner.d.ts +252 -0
  77. package/lib/types/host-service.d.ts +379 -0
  78. package/lib/types/http.d.ts +59 -0
  79. package/lib/types/index.d.ts +322 -0
  80. package/lib/types/loopback.d.ts +24 -0
  81. package/lib/types/mount-once.d.ts +55 -0
  82. package/lib/types/power-inhibitor.d.ts +73 -0
  83. package/lib/types/protocol.d.ts +212 -0
  84. package/lib/types/tool-surface.d.ts +71 -0
  85. package/package.json +107 -4
  86. package/src/client/PluginSettingsCard.tsx +564 -0
  87. package/src/client/TaskBoardSettingsCard.tsx +539 -0
  88. package/src/client/apply-guard.ts +35 -0
  89. package/src/client/board/ClampedMarkdown.tsx +69 -0
  90. package/src/client/board/ConfirmDialog.tsx +44 -0
  91. package/src/client/board/EditTaskModal.tsx +110 -0
  92. package/src/client/board/LinkSubtaskModal.tsx +97 -0
  93. package/src/client/board/NewTaskModal.tsx +718 -0
  94. package/src/client/board/TagManagerModal.tsx +235 -0
  95. package/src/client/board/TaskBoard.tsx +558 -0
  96. package/src/client/board/TaskCard.tsx +315 -0
  97. package/src/client/board/TaskDetail.tsx +985 -0
  98. package/src/client/board/TaskForm.tsx +264 -0
  99. package/src/client/board/VerificationReport.tsx +322 -0
  100. package/src/client/board/card-view.ts +220 -0
  101. package/src/client/board/icons.tsx +89 -0
  102. package/src/client/board/overlay.tsx +189 -0
  103. package/src/client/board/parse-model-pref.ts +35 -0
  104. package/src/client/board/preset-label.ts +44 -0
  105. package/src/client/board/status-key.ts +41 -0
  106. package/src/client/board/task-markdown.module.css +137 -0
  107. package/src/client/board/task-markdown.tsx +106 -0
  108. package/src/client/board-settings.module.css +66 -0
  109. package/src/client/board.module.css +1837 -0
  110. package/src/client/css-modules.d.ts +5 -0
  111. package/src/client/host-api.ts +336 -0
  112. package/src/client/index.ts +501 -0
  113. package/src/client/locales.ts +905 -0
  114. package/src/client/main-session.ts +43 -0
  115. package/src/client/native-panel.tsx +140 -0
  116. package/src/client/plugin-card-seat.ts +199 -0
  117. package/src/client/schedule-presets.ts +13 -0
  118. package/src/client/schedule-zone.ts +233 -0
  119. package/src/client/seats.tsx +58 -0
  120. package/src/client/service.ts +94 -0
  121. package/src/client/settings-card.module.css +444 -0
  122. package/src/client/settings-entry-form.ts +142 -0
  123. package/src/client/settings-form.ts +468 -0
  124. package/src/core/controller.ts +871 -0
  125. package/src/core/degraded-reason.ts +81 -0
  126. package/src/core/extension.ts +376 -0
  127. package/src/core/freeze-snapshot.ts +213 -0
  128. package/src/core/handover.ts +132 -0
  129. package/src/core/issue-form.ts +19 -0
  130. package/src/core/package-name.ts +9 -0
  131. package/src/core/poll-cadence.ts +41 -0
  132. package/src/core/schedule.ts +363 -0
  133. package/src/core/session-reuse.ts +40 -0
  134. package/src/core/store.ts +371 -0
  135. package/src/core/subtask.ts +341 -0
  136. package/src/core/tasks.ts +843 -0
  137. package/src/core/use-cases/task-archive.ts +91 -0
  138. package/src/core/use-cases/task-create.ts +110 -0
  139. package/src/core/use-cases/task-delete.ts +43 -0
  140. package/src/core/use-cases/task-parent.ts +65 -0
  141. package/src/core/use-cases/task-schedule.ts +251 -0
  142. package/src/core/use-cases/task-tag.ts +110 -0
  143. package/src/core/use-cases/task-update.ts +126 -0
  144. package/src/core/verification-budget.ts +115 -0
  145. package/src/core/verification.ts +1594 -0
  146. package/src/core/workspace-target.ts +59 -0
  147. package/src/dsh-home.ts +42 -0
  148. package/src/host/agent-tools.ts +762 -0
  149. package/src/host/extension-registry.ts +509 -0
  150. package/src/host/llm-dispatch.ts +87 -0
  151. package/src/host/verification-gate.ts +487 -0
  152. package/src/host/verification-runner.ts +702 -0
  153. package/src/host/workspace-evidence.ts +176 -0
  154. package/src/host-ai.ts +158 -0
  155. package/src/host-ledger.ts +1826 -0
  156. package/src/host-routes.ts +306 -0
  157. package/src/host-runner.ts +755 -0
  158. package/src/host-service.ts +1112 -0
  159. package/src/http.ts +127 -0
  160. package/src/index.ts +722 -0
  161. package/src/loopback.ts +63 -0
  162. package/src/mount-once.ts +142 -0
  163. package/src/power-inhibitor.ts +321 -0
  164. package/src/protocol.ts +591 -0
  165. package/src/tool-surface.ts +95 -0
@@ -0,0 +1,5 @@
1
+ /** CSS Modules typing for the tsdown CSS-inline preset (hashed class map). */
2
+ declare module '*.module.css' {
3
+ const classes: Record<string, string>
4
+ export default classes
5
+ }
@@ -0,0 +1,336 @@
1
+ import { degradedRowOf, ledgerOwnerPid } from '../core/degraded-reason.ts'
2
+ import { TASK_BOARD_PACKAGE } from '../core/package-name.ts'
3
+ import type { TaskRecord } from '../core/tasks.ts'
4
+ import { t } from './locales.ts'
5
+ import {
6
+ isTaskParseDraft,
7
+ TASK_BOARD_API_PREFIX,
8
+ type TaskBoardAction,
9
+ type TaskBoardActionEnvelope,
10
+ type TaskBoardEventPayload,
11
+ type TaskBoardParseDraft,
12
+ type TaskBoardParseRequest,
13
+ type TaskBoardSnapshot,
14
+ } from '../protocol.ts'
15
+
16
+ /**
17
+ * Client-side base for the board's routes: DOCUMENT-RELATIVE (issue #1707).
18
+ *
19
+ * The host registers `TASK_BOARD_API_PREFIX` root-absolute; the page is served
20
+ * with `<base href="./">`, so the browser half must drop the leading slash or
21
+ * a sub-path deployment escapes its entry directory. Derived from the shared
22
+ * constant so host and client cannot drift.
23
+ */
24
+ const CLIENT_API_PREFIX = TASK_BOARD_API_PREFIX.slice(1)
25
+
26
+ const IMPORT_MARKER = 'dsh.taskBoard.v2.hostImported'
27
+ const SOURCE_KEY = 'dsh.taskBoard.v2.sourceId'
28
+ const IMPORT_REQUEST_KEY = 'dsh.taskBoard.v2.importRequestId'
29
+ const REQUEST_TIMEOUT_MS = 15_000
30
+ /** Re-notify the panel at most this often while the event stream stays broken. */
31
+ const STREAM_ERROR_NOTIFY_MS = 15_000
32
+ /** Mirrors the Host's own parse budget; only used to phrase the timeout. */
33
+ const TASK_PARSE_TIMEOUT_SECONDS = 45
34
+
35
+ /**
36
+ * Failure classes of the Host API, in the language the panel renders
37
+ * (issue #1528). The Host is the only part that knows whether a task-board
38
+ * route exists at all, so a raw fetch/parse error must never reach the user:
39
+ * "Unexpected token 'o', \"not found\" is not valid JSON" is what a missing
40
+ * Host half looks like today.
41
+ */
42
+ export type HostApiFailure =
43
+ /** The board's own routes are not registered and nothing explains why. */
44
+ | 'not-mounted'
45
+ /** Another live DSH process owns the ledger, so this instance registered no board routes (#1730). */
46
+ | 'ledger-locked'
47
+ /** This row degraded during start for some other reason the family health route reports (#1730). */
48
+ | 'degraded'
49
+ | 'unauthorized'
50
+ | 'forbidden'
51
+ | 'locked'
52
+ | 'rejected'
53
+ | 'timeout'
54
+ | 'unreachable'
55
+ | 'unexpected'
56
+
57
+ /** Transport failure carrying a stable class next to its user-facing message. */
58
+ export class HostApiError extends Error {
59
+ constructor(readonly failure: HostApiFailure, message: string, readonly status?: number) {
60
+ super(message)
61
+ this.name = 'HostApiError'
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Same-origin family health route served by the dsh-web-all shell: the
67
+ * degraded ledger, in which a family row that failed during apply appears WITH
68
+ * its reason. DOCUMENT-RELATIVE for the same reason as the board's own routes
69
+ * (issue #1707). A 404 here means the family shell is absent or older than the
70
+ * route, which is not itself a failure of the board.
71
+ */
72
+ const FAMILY_DEGRADED_ROUTE = 'api/dsh-web-all/degraded'
73
+
74
+ /** Health-route ceiling: an unresponsive family shell must not hold the board's first paint. */
75
+ const DEGRADED_LOOKUP_TIMEOUT_MS = 2_000
76
+
77
+ /**
78
+ * The failure text for a row this browser knows failed during start.
79
+ *
80
+ * A ledger lock is the one class with an owner the user can act on, so its
81
+ * reason is unpacked into the pid plus what to do about it; every other
82
+ * degraded row is reported with the shell's own reason verbatim. The raw
83
+ * reason rides along either way, because it is the only text that names the
84
+ * lock file or the recovery step when the pid is not the whole story.
85
+ * @param reason - the shell's one-line failure reason (never empty).
86
+ */
87
+ function degradedFailureMessage(reason: string): { failure: 'ledger-locked' | 'degraded'; message: string } {
88
+ const pid = ledgerOwnerPid(reason)
89
+ if (pid === undefined) return { failure: 'degraded', message: t('board.hostError.degraded', { detail: reason }) }
90
+ return { failure: 'ledger-locked', message: t('board.hostError.ledgerLocked', { pid: String(pid), detail: reason }) }
91
+ }
92
+
93
+ /**
94
+ * The degraded record the family shell holds for THIS board, or undefined when
95
+ * the row is healthy, the shell is absent, or the answer is unusable. The
96
+ * lookup is best-effort by contract: any uncertainty keeps the caller's own
97
+ * failure text instead of replacing it with a weaker one.
98
+ * @param fetchImpl - fetch implementation (injected for tests).
99
+ * @returns the ledger's reason for this row, or undefined when it names none.
100
+ */
101
+ async function fetchDegradedReason(fetchImpl: typeof fetch): Promise<string | undefined> {
102
+ const controller = new AbortController()
103
+ const timer = globalThis.setTimeout(() => { controller.abort() }, DEGRADED_LOOKUP_TIMEOUT_MS)
104
+ try {
105
+ const response = await fetchImpl(FAMILY_DEGRADED_ROUTE, { signal: controller.signal, headers: { accept: 'application/json' }, cache: 'no-store' })
106
+ if (!response.ok) return undefined
107
+ return degradedRowOf(await response.json(), TASK_BOARD_PACKAGE)?.reason
108
+ } catch {
109
+ return undefined
110
+ } finally {
111
+ globalThis.clearTimeout(timer)
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Name the real reason this board's routes are missing (issue #1730).
117
+ *
118
+ * The core webserver answers an unmounted route with a bare 404, which cannot
119
+ * distinguish "this deployment never loaded the plugin" from "this row
120
+ * degraded during start" — a second DSH process holding `ledger-v2.lock` is
121
+ * the case that matters, because the panel's advice ("restart the service")
122
+ * is then false: the lock belongs to the other process, and restarting cannot
123
+ * win it. The family health route knows the difference, so the 404 is
124
+ * disambiguated there before anything is shown.
125
+ * @param fallback - copy for the plain "routes are not there" failure, which
126
+ * is route-specific (the board's state route and the AI-parse route phrase
127
+ * their own absence); it is also what is shown when the ledger names nothing.
128
+ * @param fetchImpl - fetch implementation (injected for tests).
129
+ * @returns the HostApiError to throw for a missing board route.
130
+ */
131
+ export async function missingRouteFailure(
132
+ fallback: string = t('board.hostError.notMounted'),
133
+ fetchImpl: typeof fetch = fetch,
134
+ ): Promise<HostApiError> {
135
+ const absent = (): HostApiError => new HostApiError('not-mounted', fallback, 404)
136
+ const reason = await fetchDegradedReason(fetchImpl)
137
+ // A shell that predates the reason field (or recorded none) tells us the row
138
+ // is degraded but not why; the route's own wording is more honest than an
139
+ // empty "because".
140
+ if (reason === undefined || reason === '') return absent()
141
+ const described = degradedFailureMessage(reason)
142
+ return new HostApiError(described.failure, described.message, 404)
143
+ }
144
+
145
+ function uuid(): string {
146
+ return globalThis.crypto?.randomUUID?.() ?? `browser-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
147
+ }
148
+
149
+ /**
150
+ * Read one Host response without ever handing a non-JSON body to JSON.parse:
151
+ * the core webserver answers an unmounted `/api/*` path with the plain text
152
+ * "not found", which used to surface as a JavaScript parse error in the panel.
153
+ */
154
+ async function readJson<T>(response: Response): Promise<T> {
155
+ const text = await response.text()
156
+ let parsed: unknown
157
+ let readable = false
158
+ if (text.trim() !== '') {
159
+ try {
160
+ parsed = JSON.parse(text)
161
+ readable = true
162
+ } catch {
163
+ readable = false
164
+ }
165
+ }
166
+ const hostError = readable && typeof parsed === 'object' && parsed !== null && typeof (parsed as { error?: unknown }).error === 'string'
167
+ ? (parsed as { error: string }).error
168
+ : undefined
169
+ if (response.ok) {
170
+ if (!readable) throw new HostApiError('unexpected', t('board.hostError.unexpected', { status: String(response.status) }), response.status)
171
+ return parsed as T
172
+ }
173
+ if (hostError !== undefined) {
174
+ // The Host answered with a reason of its own. A ledger lock is the one
175
+ // class worth naming in the panel's words; the authentication fence and
176
+ // every other action rejection are reported as they arrive.
177
+ if (hostError === 'forbidden') throw new HostApiError('forbidden', t('board.hostError.forbidden'), response.status)
178
+ if (response.status === 503 || /lock/i.test(hostError)) {
179
+ throw new HostApiError('locked', t('board.hostError.locked', { detail: hostError }), response.status)
180
+ }
181
+ throw new HostApiError('rejected', hostError, response.status)
182
+ }
183
+ // A bare 404 is the ONLY signal that this board's routes are absent; the
184
+ // family health route is what turns it into the real reason when this row
185
+ // degraded during start (issue #1730).
186
+ if (response.status === 404) throw await missingRouteFailure()
187
+ if (response.status === 403) throw new HostApiError('forbidden', t('board.hostError.forbidden'), 403)
188
+ if (response.status === 401) throw new HostApiError('unauthorized', t('board.hostError.unauthorized'), 401)
189
+ throw new HostApiError('unexpected', t('board.hostError.unexpected', { status: String(response.status) }), response.status)
190
+ }
191
+
192
+ export interface TaskBoardHostTransport {
193
+ bootstrap(legacy: readonly TaskRecord[]): Promise<TaskBoardSnapshot>
194
+ state(): Promise<TaskBoardSnapshot>
195
+ action(action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot>
196
+ subscribe(listener: (event?: TaskBoardEventPayload) => void): () => void
197
+ /** One-shot model parse of pasted text (issue #1540). */
198
+ parseDraft(request: TaskBoardParseRequest, signal?: AbortSignal): Promise<TaskBoardParseDraft>
199
+ }
200
+
201
+ export class HttpTaskBoardHostTransport implements TaskBoardHostTransport {
202
+ constructor(private readonly storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage) {}
203
+
204
+ async bootstrap(legacy: readonly TaskRecord[]): Promise<TaskBoardSnapshot> {
205
+ const initial = await this.state()
206
+ const ledgerId = initial.scheduler.ledgerId
207
+ if (legacy.length > 0 && ledgerId !== undefined && this.storage?.getItem(IMPORT_MARKER) !== ledgerId) {
208
+ let sourceId = this.storage?.getItem(SOURCE_KEY)
209
+ if (sourceId === null || sourceId === undefined || sourceId === '') {
210
+ sourceId = uuid()
211
+ this.storage?.setItem(SOURCE_KEY, sourceId)
212
+ }
213
+ let requestId = this.storage?.getItem(IMPORT_REQUEST_KEY)
214
+ if (requestId === null || requestId === undefined || requestId === '') {
215
+ requestId = uuid()
216
+ this.storage?.setItem(IMPORT_REQUEST_KEY, requestId)
217
+ }
218
+ const snapshot = await this.post(requestId, { kind: 'import', sourceId, tasks: [...legacy] })
219
+ this.storage?.setItem(IMPORT_MARKER, snapshot.scheduler.ledgerId ?? ledgerId)
220
+ return snapshot
221
+ }
222
+ return initial
223
+ }
224
+
225
+ async state(): Promise<TaskBoardSnapshot> {
226
+ return await this.request(`${CLIENT_API_PREFIX}/state`, { cache: 'no-store' })
227
+ }
228
+
229
+ async action(action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot> {
230
+ return await this.post(uuid(), action, initiator)
231
+ }
232
+
233
+ private async post(requestId: string, action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot> {
234
+ const envelope: TaskBoardActionEnvelope = { requestId, action, ...(initiator === undefined || initiator === '' ? {} : { initiator }) }
235
+ return await this.request(`${CLIENT_API_PREFIX}/action`, {
236
+ method: 'POST',
237
+ headers: { 'content-type': 'application/json' },
238
+ body: JSON.stringify(envelope),
239
+ })
240
+ }
241
+
242
+ private async request(url: string, init: RequestInit): Promise<TaskBoardSnapshot> {
243
+ const controller = new AbortController()
244
+ const timeout = globalThis.setTimeout(() => { controller.abort() }, REQUEST_TIMEOUT_MS)
245
+ try {
246
+ return await readJson<TaskBoardSnapshot>(await fetch(url, { ...init, signal: controller.signal }))
247
+ } catch (error) {
248
+ if (error instanceof HostApiError) throw error
249
+ if (controller.signal.aborted) throw new HostApiError('timeout', t('board.hostError.timeout', { seconds: String(REQUEST_TIMEOUT_MS / 1_000) }))
250
+ // fetch itself failed (server stopped, connection reset, DNS): the panel
251
+ // says so in its own words instead of leaking "Failed to fetch".
252
+ throw new HostApiError('unreachable', t('board.hostError.unreachable'))
253
+ } finally {
254
+ globalThis.clearTimeout(timeout)
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Ask the Host to turn pasted text into task fields. The route answers a
260
+ * typed failure (no model, timeout, unparseable reply) already phrased for
261
+ * the form, so the UI never renders a raw status code (issue #1540).
262
+ */
263
+ async parseDraft(request: TaskBoardParseRequest, signal?: AbortSignal): Promise<TaskBoardParseDraft> {
264
+ let response: Response
265
+ try {
266
+ response = await fetch(`${CLIENT_API_PREFIX}/parse`, {
267
+ method: 'POST',
268
+ headers: { 'content-type': 'application/json' },
269
+ body: JSON.stringify(request),
270
+ ...(signal === undefined ? {} : { signal }),
271
+ })
272
+ } catch {
273
+ // A cancelled parse and a stopped Host look the same to fetch; the form
274
+ // checks its own abort flag before showing anything.
275
+ throw new HostApiError('unreachable', t('board.hostError.unreachable'))
276
+ }
277
+ const text = await response.text()
278
+ let parsed: unknown
279
+ let readable = false
280
+ if (text.trim() !== '') {
281
+ try {
282
+ parsed = JSON.parse(text)
283
+ readable = true
284
+ } catch {
285
+ readable = false
286
+ }
287
+ }
288
+ const record = readable && typeof parsed === 'object' && parsed !== null
289
+ ? parsed as { code?: unknown; error?: unknown; draft?: unknown }
290
+ : undefined
291
+ if (response.ok) {
292
+ if (record !== undefined && isTaskParseDraft(record.draft)) return record.draft
293
+ throw new HostApiError('unexpected', t('new.aiParseFailed', { error: t('board.hostError.unexpected', { status: String(response.status) }) }), response.status)
294
+ }
295
+ // The parse route lives beside the board's own routes, so a 404 means the
296
+ // same thing here: absent routes, with the same health-ledger detail and
297
+ // this route's own wording as the fallback.
298
+ if (response.status === 404) throw await missingRouteFailure(t('new.aiParseUnavailable'))
299
+ if (response.status === 403) throw new HostApiError('forbidden', t('board.hostError.forbidden'), 403)
300
+ if (response.status === 401) throw new HostApiError('unauthorized', t('board.hostError.unauthorized'), 401)
301
+ const code = typeof record?.code === 'string' ? record.code : undefined
302
+ if (code === 'no-model') throw new HostApiError('rejected', t('new.aiParseNoModel'), response.status)
303
+ if (code === 'timeout') throw new HostApiError('timeout', t('new.aiParseTimeout', { seconds: String(TASK_PARSE_TIMEOUT_SECONDS) }), response.status)
304
+ const detail = typeof record?.error === 'string' && record.error !== '' ? record.error : String(response.status)
305
+ throw new HostApiError('rejected', t('new.aiParseFailed', { error: detail }), response.status)
306
+ }
307
+
308
+ subscribe(listener: (event?: TaskBoardEventPayload) => void): () => void {
309
+ const events = new EventSource(`${CLIENT_API_PREFIX}/events`)
310
+ let lastStreamErrorNotify = 0
311
+ events.onmessage = (message: MessageEvent<string>): void => {
312
+ try {
313
+ const parsed = JSON.parse(message.data) as TaskBoardEventPayload
314
+ if (parsed === null || typeof parsed !== 'object' || typeof parsed.revision !== 'number') throw new Error('invalid event frame')
315
+ listener(parsed)
316
+ } catch {
317
+ listener()
318
+ }
319
+ }
320
+ // A stream that cannot connect at all (unmounted route, refused socket) is
321
+ // how a Host half that never mounted looks from the browser; nudge the
322
+ // panel into one state read so the failure becomes visible (#1528).
323
+ events.onerror = (): void => {
324
+ const now = Date.now()
325
+ if (now - lastStreamErrorNotify < STREAM_ERROR_NOTIFY_MS) return
326
+ lastStreamErrorNotify = now
327
+ listener()
328
+ }
329
+ const onVisible = (): void => { if (document.visibilityState === 'visible') listener() }
330
+ document.addEventListener('visibilitychange', onVisible)
331
+ return () => {
332
+ document.removeEventListener('visibilitychange', onVisible)
333
+ events.close()
334
+ }
335
+ }
336
+ }