dsh-taskbridge 1.7.0 → 1.8.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 (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -21
  3. package/README.md +150 -289
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -627
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +13 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +6 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +12 -5
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -53
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -1,862 +1,862 @@
1
- // dsh-delegate — native left navigation: the TaskBridge task entry and its panel.
2
- //
3
- // This file is the ONLY thing in the bundle that touches the host's main/sidebar
4
- // slot names. It is deliberately small: the panel it registers reads the task data
5
- // the bundle already fetched, and its own collapse state is local. It draws no
6
- // second task tree and performs no navigation of its own beyond asking DSH's own
7
- // Workspace service to open a session whose identity TaskBridge recorded.
8
- //
9
- // What is registered, and against WHAT CONTRACT
10
- // --------------------------------------------
11
- // Two registrations, both through `ctx.slots.inject(name, register)`, matching the
12
- // host exactly (0.2.2-rc.5,
13
- // `@deepseek-ai/dsh-client-ui-plugin-manager/src/client/index.ts`):
14
- //
15
- // * `main` — the FULL CONTENT PANEL,
16
- // `{ name: 'main', key }`, registered with the panel
17
- // component. The host hands the owner `size`/`active`.
18
- // * `sidebar.panellist`— the SMALL ICON,
19
- // `{ name: 'sidebar.panellist', id, order, label }`,
20
- // registered with the icon component. `label` is a FUNCTION
21
- // the host calls for the row's text.
22
- // The two share one id (`TASKS_NAV_KEY`), which is how the row selects the panel.
23
- //
24
- // Both slots belong to the host's own shell. They are OPTIONAL here: a host (or a
25
- // shell rebuild) that never declares them simply never runs the registrations, and
26
- // `inject` disposes them on the way out. That matters because the bundle's existing
27
- // `plugins.bundle.config` page must keep working on a host without a sidebar — so
28
- // nothing in this module is a prerequisite for the settings page.
29
- //
30
- // The shell's own workspace/session browsing region belongs to DSH: THIS module never
31
- // registers there, and no TaskBridge task view replaces it. The grouped workspaces
32
- // browser is a SEPARATE registration (`workspaces-browser.jsx`, `sidebar.workspaces`,
33
- // lower priority than the shipped entry) whose identity rules are stated there and in
34
- // `docs/workspace-grouping.md`; it keeps ordinary Workspaces, and it falls back to the
35
- // shipped browser whenever it cannot prove what belongs to which project.
36
- //
37
- // What the panel may and may not do
38
- // ---------------------------------
39
- // * It reads records from the SAME page store `apply` already built, so opening it
40
- // never duplicates a read. The initial load runs in an effect (never in render);
41
- // there is no per-row request and no timer.
42
- // * A session is offered for navigation only when the record carries the host's
43
- // real session id AND the host's own `workspaces` snapshot can vouch for it.
44
- // * It never renames, moves, archives or deletes a session. Archiving stays a DSH
45
- // action performed in DSH's own UI.
46
- //
47
- // Rendering rules worth keeping:
48
- // * same-titled projects stay separate entries (identity is the host's project
49
- // key, never the title);
50
- // * a record whose source could not be confirmed is shown as such, in its own
51
- // group, and is never folded into a real project;
52
- // * a historical record without a navigation identifier stays listed, with the
53
- // reason stated, rather than disappearing.
54
-
55
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
56
-
57
- import { taskOutcome, TREE_STATUS_LABELS, TREE_STATUS_TONES } from './api.js';
58
-
59
- // ---------------------------------------------------------------------------
60
- // Slot names and registration keys
61
- // ---------------------------------------------------------------------------
62
-
63
- /** The host's registry slot: main-area entries (the sidebar icon). */
64
- export const MAIN_SLOT = 'main';
65
-
66
- /** The host's registry slot: the left sidebar's panel list (the row). */
67
- export const SIDEBAR_PANEL_SLOT = 'sidebar.panellist';
68
-
69
- /**
70
- * One id for both registrations.
71
- *
72
- * The icon in `main` and the row in `sidebar.panellist` are two halves of the same
73
- * entry, so they share an identity. It is namespaced because the sidebar is shared
74
- * with other plugins.
75
- */
76
- export const TASKS_NAV_KEY = 'dsh-taskbridge:taskbridge-tasks';
77
-
78
- /** Smallest order that keeps this entry at the front without taking part 100. */
79
- export const TASKS_NAV_ORDER = 20;
80
-
81
- /** Operator-facing label of the entry. */
82
- export const TASKS_NAV_LABEL = 'TaskBridge 任务';
83
-
84
- // ---------------------------------------------------------------------------
85
- // Pure helpers (exported so a test can drive them without a browser)
86
- // ---------------------------------------------------------------------------
87
-
88
- /**
89
- * The host Workspace service, if this host has one.
90
- *
91
- * `ctx.get` is the Cordis lookup; a host that does not compose Workspace answering
92
- * with nothing here is the documented degradation, not an error.
93
- * @param {object | null | undefined} ctx - client context.
94
- * @returns {object | null} service exposing `openSession`.
95
- */
96
- export function resolveUiWorkspace(ctx) {
97
- const get = ctx !== null && typeof ctx === 'object' ? ctx.get : null;
98
- if (typeof get !== 'function') return null;
99
- let service = null;
100
- try {
101
- service = get.call(ctx, 'uiWorkspace');
102
- } catch {
103
- service = null;
104
- }
105
- if (service === null || typeof service !== 'object') return null;
106
- return typeof service.openSession === 'function' ? service : null;
107
- }
108
-
109
- /**
110
- * The host's `workspaces` service, if this host has one.
111
- *
112
- * It is a separate service from `uiWorkspace`: `uiWorkspace` opens a session, while
113
- * `workspaces.list` is the subscribable source (`{ getSnapshot, subscribe }`) whose
114
- * snapshot says which sessions exist and which are archived. Both are looked up
115
- * lazily, because the host may compose them after this plugin mounts.
116
- * @param {object | null | undefined} ctx - client context.
117
- * @returns {object | null} service exposing `list.getSnapshot`.
118
- */
119
- export function resolveWorkspaces(ctx) {
120
- const get = ctx !== null && typeof ctx === 'object' ? ctx.get : null;
121
- if (typeof get !== 'function') return null;
122
- let service = null;
123
- try {
124
- service = get.call(ctx, 'workspaces');
125
- } catch {
126
- service = null;
127
- }
128
- if (service === null || typeof service !== 'object') return null;
129
- return typeof service.list?.getSnapshot === 'function' ? service : null;
130
- }
131
-
132
- /**
133
- * Resolve one service that may be a value or a lazy getter.
134
- *
135
- * `apply` passes getters so a host service composed AFTER this plugin mounts is still
136
- * found when it is finally used; a plain value (a test double, or a host that had it
137
- * ready) is returned as-is.
138
- * @param {unknown} value - service, getter, or nothing.
139
- * @returns {object | null} the service.
140
- */
141
- export function resolveService(value) {
142
- if (typeof value === 'function') {
143
- try {
144
- const resolved = value();
145
- return resolved !== null && typeof resolved === 'object' ? resolved : null;
146
- } catch {
147
- return null;
148
- }
149
- }
150
- return value !== null && typeof value === 'object' ? value : null;
151
- }
152
-
153
- /**
154
- * Register the entry on a client context.
155
- *
156
- * The split matches the host exactly (0.2.2-rc.5,
157
- * `dsh-client-ui-plugin-manager/src/client/index.ts`):
158
- * * `main` — the FULL CONTENT PANEL, `{ name: 'main', key: PANEL_ID }`,
159
- * registered with the page component. The host gives the
160
- * owner its `size`/`active` seats.
161
- * * `sidebar.panellist` — the SMALL ICON, `{ name: 'sidebar.panellist', id, order,
162
- * label }`, registered with the icon component. `label` is
163
- * a function the host calls for the row's text.
164
- * The two share one id, which is how the row selects the panel.
165
- *
166
- * Exactly ONE store instance is passed in and used by both halves, so opening the
167
- * entry never issues a second read for records the page already holds.
168
- *
169
- * Split out from `apply` so a test can hand it a fake `ctx` and assert the exact
170
- * registration shape without a browser. A missing `slots` service is a host without
171
- * the sidebar: both registrations are skipped and this returns a no-op.
172
- * @param {object} ctx - client Cordis context.
173
- * @param {object} options - `store`, `uiWorkspace`, `workspaces`.
174
- * @returns {() => void} disposer releasing both registrations.
175
- */
176
- export function registerTasksNavigation(ctx, options = {}) {
177
- const slots = ctx?.slots;
178
- if (slots === null || slots === undefined || typeof slots.inject !== 'function') return () => {};
179
- const { store = null, uiWorkspace = null, workspaces = null } = options;
180
-
181
- const panel = () => TaskbridgeNavPanel({ store, uiWorkspace, workspaces });
182
- const icon = TaskbridgeSidebarIcon;
183
-
184
- const registerPanel = options.registerPanel ?? (() => slots.inject(MAIN_SLOT, () => slots.register({
185
- name: MAIN_SLOT,
186
- key: TASKS_NAV_KEY,
187
- }, panel)));
188
-
189
- const registerIcon = options.registerIcon ?? (() => slots.inject(SIDEBAR_PANEL_SLOT, () => slots.register({
190
- name: SIDEBAR_PANEL_SLOT,
191
- id: TASKS_NAV_KEY,
192
- order: TASKS_NAV_ORDER,
193
- label: () => TASKS_NAV_LABEL,
194
- }, icon)));
195
-
196
- const disposers = [];
197
- // Each registration stands on its own: a host that declares only one of the two
198
- // slots still gets the half it declares, and a refusal of one never cancels the
199
- // other. `inject` itself only defers; nothing here throws for a missing slot.
200
- for (const register of [registerPanel, registerIcon]) {
201
- try {
202
- const dispose = register();
203
- if (typeof dispose === 'function') disposers.push(dispose);
204
- } catch {
205
- // A host whose slot API refuses this registration keeps working; the entry
206
- // simply does not appear. Nothing else in the bundle depends on it.
207
- }
208
- }
209
- return () => {
210
- for (const dispose of disposers) {
211
- try {
212
- dispose();
213
- } catch {
214
- // Disposal is best-effort: a disposer that already ran must not fail twice.
215
- }
216
- }
217
- };
218
- }
219
-
220
- /** The label a session id is shown with: shortened, never guessed. */
221
- export function shortSessionId(sessionId) {
222
- if (typeof sessionId !== 'string' || sessionId === '') return '';
223
- return sessionId.length <= 12 ? sessionId : `${sessionId.slice(0, 6)}…${sessionId.slice(-4)}`;
224
- }
225
-
226
- /**
227
- * The navigation identifier TaskBridge recorded for ONE task, or null.
228
- *
229
- * Only a host-recorded identity counts. Order of evidence, strongest first:
230
- * 1. the record's OWN top-level `sessionId` — a historical (restored) record keeps
231
- * its thread there, and that is the record alive in the current host;
232
- * 2. the run's `execution.sessionId`;
233
- * 3. the conversation's own `sessionId`.
234
- * Nothing is derived from the task id, a title, a workspace path or a position,
235
- * because none of those identify a native session.
236
- * @param {object | null | undefined} task - one `/tasks` row.
237
- * @returns {string | null} session id.
238
- */
239
- export function taskSessionId(task) {
240
- if (task === null || task === undefined || typeof task !== 'object') return null;
241
- for (const candidate of [task.sessionId, task.execution?.sessionId, task.conversation?.sessionId]) {
242
- if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();
243
- }
244
- return null;
245
- }
246
-
247
- /**
248
- * Read the host's Workspaces snapshot, or null when it cannot be read synchronously.
249
- *
250
- * The host service is `{ getSnapshot, subscribe }`; its snapshot is
251
- * `{ phase, items: [{ workspaceId, sessionIds, ... }], archivedSessionIds }`. Anything
252
- * else (an absent service, a throwing/suspending source) yields null, which the caller
253
- * treats as "cannot check" rather than guessing.
254
- * @param {object | null | undefined} workspaces - host `workspaces` service.
255
- * @returns {object | null} the snapshot.
256
- */
257
- export function workspacesSnapshot(workspaces) {
258
- const source = workspaces?.list;
259
- if (source === null || source === undefined || typeof source.getSnapshot !== 'function') return null;
260
- let snapshot = null;
261
- try {
262
- snapshot = source.getSnapshot();
263
- } catch {
264
- return null;
265
- }
266
- if (snapshot === null || typeof snapshot !== 'object' || Array.isArray(snapshot)) return null;
267
- return snapshot;
268
- }
269
-
270
- /**
271
- * Every session id the host's snapshot knows, with the workspace it belongs to.
272
- * @param {object | null} snapshot - `workspacesSnapshot(...)`.
273
- * @returns {Map<string, string>} session id → workspace id.
274
- */
275
- export function knownSessionIds(snapshot) {
276
- const index = new Map();
277
- for (const item of Array.isArray(snapshot?.items) ? snapshot.items : []) {
278
- if (item === null || typeof item !== 'object') continue;
279
- const workspaceId = typeof item.workspaceId === 'string' ? item.workspaceId : '';
280
- for (const sessionId of Array.isArray(item.sessionIds) ? item.sessionIds : []) {
281
- if (typeof sessionId === 'string' && sessionId !== '' && !index.has(sessionId)) index.set(sessionId, workspaceId);
282
- }
283
- }
284
- return index;
285
- }
286
-
287
- /**
288
- * Where an id sits among the host's own Workspaces.
289
- *
290
- * Read from `workspaces.list.getSnapshot()`. The answers are kept apart on purpose,
291
- * because each calls for a different action:
292
- * * `pending` — the snapshot is not ready yet (a phase other than ready, or no
293
- * snapshot). Nothing can be verified, so the operator is told to
294
- * retry later rather than sent somewhere unverified.
295
- * * `present` — the host lists this session in a workspace, and it is not archived.
296
- * This is the only state that may be opened.
297
- * * `archived` — the id is in the host's own `archivedSessionIds`. Refused, and NOT
298
- * reported as missing: DSH archived it, and only DSH can put it back.
299
- * * `missing` — the snapshot is ready and lists neither, so the id is not a live
300
- * session here. Refused explicitly instead of opened on faith.
301
- * * `unknown` — no service at all (a host without Workspaces).
302
- * @param {string | null} sessionId - host session id.
303
- * @param {object | null | undefined} workspaces - host Workspace service.
304
- * @returns {{ state: 'unknown'|'pending'|'present'|'archived'|'missing', label: string | null, workspaceId: string | null }} placement.
305
- */
306
- export function sessionPlacement(sessionId, workspaces) {
307
- const label = () => (typeof sessionId === 'string' && sessionId !== '' ? shortSessionId(sessionId) : null);
308
- const snapshot = workspacesSnapshot(workspaces);
309
- if (snapshot === null) return { state: 'unknown', label: label(), workspaceId: null };
310
- // The host publishes its own readiness; anything but `ready` means "cannot tell yet".
311
- if (snapshot.phase !== 'ready') return { state: 'pending', label: label(), workspaceId: null };
312
- if (typeof sessionId !== 'string' || sessionId === '') return { state: 'missing', label: null, workspaceId: null };
313
- const archived = Array.isArray(snapshot.archivedSessionIds) ? snapshot.archivedSessionIds : [];
314
- if (archived.includes(sessionId)) return { state: 'archived', label: label(), workspaceId: null };
315
- const workspaceId = knownSessionIds(snapshot).get(sessionId) ?? null;
316
- if (workspaceId === null) return { state: 'missing', label: label(), workspaceId: null };
317
- return { state: 'present', label: label(), workspaceId };
318
- }
319
-
320
- /** Use the task page's status, including whether its review was saved. */
321
- function statusOf(row) {
322
- const key = typeof row.nodeStatus === 'string' ? row.nodeStatus : (typeof row.state === 'string' ? row.state : 'unknown');
323
- const { label, tone } = taskOutcome(row);
324
- if (label !== '') return { key, label, tone };
325
- return { key, label: TREE_STATUS_LABELS[key] ?? key, tone: TREE_STATUS_TONES[key] ?? 'off' };
326
- }
327
-
328
- /**
329
- * The panel's model: projects, their sessions, and what may be opened.
330
- *
331
- * Groups are keyed by the host's project key — never by a title — so two projects
332
- * with the same name stay two entries; `tree.projects` carries the host's own
333
- * display name and short path for each key, and a key it does not name falls back to
334
- * the key itself. `unverified` (the projection's "来源未确认") is its own group and is
335
- * never merged into a named one.
336
- *
337
- * A session row is a task the host recorded. Its navigation identity is only ever
338
- * the host-recorded session id; a row without one is still listed, marked, and its
339
- * locate control is disabled — a historical record must not vanish just because it
340
- * cannot be opened.
341
- *
342
- * Archived records come from the OPTIONAL `displayArchived` boolean G07 adds to each
343
- * tree node. That flag is read, never written: toggling this list cannot archive,
344
- * rename or move anything in DSH. A record's own `archived` field is NOT this flag —
345
- * it marks a record recovered from durable history, which is a live record and stays
346
- * in the active list. When G07 has not published the flag, every record is treated as
347
- * an ordinary historical one.
348
- * @param {object} snapshot - page store snapshot.
349
- * @returns {object} `{ groups, archivedGroups, activeCount, archivedCount, total, available, projectName }`.
350
- */
351
- export function navViewModel(snapshot) {
352
- const tree = snapshot?.tree ?? null;
353
- const rows = Array.isArray(snapshot?.tasks) ? snapshot.tasks : [];
354
-
355
- // The host's project summaries, by key: display name, short path and order.
356
- const meta = new Map();
357
- for (const project of Array.isArray(tree?.projects) ? tree.projects : []) {
358
- if (project === null || typeof project !== 'object') continue;
359
- const key = typeof project.projectKey === 'string' && project.projectKey !== '' ? project.projectKey : null;
360
- if (key === null || meta.has(key)) continue;
361
- meta.set(key, {
362
- name: typeof project.name === 'string' && project.name !== '' ? project.name : null,
363
- shortPath: typeof project.shortPath === 'string' && project.shortPath !== '' ? project.shortPath : null,
364
- unverified: project.unverified === true,
365
- nodeCount: Number.isFinite(project.nodeCount) ? project.nodeCount : 0,
366
- });
367
- }
368
- const groupOf = (groups, key) => {
369
- if (!groups.has(key)) groups.set(key, { key, sessions: [], archived: [] });
370
- return groups.get(key);
371
- };
372
-
373
- const archivedTasks = new Set();
374
- const nodeProjects = new Map();
375
- const walk = (node, parentArchived = false) => {
376
- if (node === null || typeof node !== 'object') return;
377
- const archived = parentArchived || node.displayArchived === true;
378
- const chains = node.kind === 'plan' ? (node.executions ?? []) : (node.chain ? [node.chain] : []);
379
- const taskIds = chains.flatMap((chain) => chain.taskIds ?? []);
380
- if (node.kind === 'task' && taskIds.length === 0) taskIds.push(node.nodeId);
381
- for (const id of [node.nodeId, ...taskIds]) {
382
- if (typeof id === 'string' && typeof node.projectKey === 'string' && node.projectKey !== '') {
383
- nodeProjects.set(id, node.projectKey);
384
- }
385
- }
386
- if (archived) for (const taskId of taskIds) archivedTasks.add(taskId);
387
- for (const child of Array.isArray(node.children) ? node.children : []) walk(child, archived);
388
- };
389
- for (const root of Array.isArray(tree?.roots) ? tree.roots : []) walk(root);
390
- // A flat-only projection (the execution plane's `/plans list` shape) is read the
391
- // same way: each entry names its own project key.
392
- for (const node of Array.isArray(tree?.flatNodes) ? tree.flatNodes : []) {
393
- if (node !== null && typeof node === 'object' && typeof node.nodeId === 'string'
394
- && typeof node.projectKey === 'string' && node.projectKey !== '' && !nodeProjects.has(node.nodeId)) {
395
- nodeProjects.set(node.nodeId, node.projectKey);
396
- }
397
- }
398
-
399
- const active = new Map();
400
- const archived = new Map();
401
- for (const row of rows) {
402
- if (row === null || typeof row !== 'object') continue;
403
- const taskId = typeof row.taskId === 'string' ? row.taskId : '';
404
- // ONLY the G07 flag counts as TaskBridge-archived. A record's own `archived`
405
- // field means "recovered from durable history" — a live historical record, NOT an
406
- // archive — so it must stay in the active list and remain openable.
407
- const isArchived = taskId !== '' && (row.displayArchived === true || archivedTasks.has(taskId));
408
- // The project of a row comes from the HOST's projection: a `/tasks` row carries
409
- // no project key of its own, so its key is the one the tree node with the same
410
- // identity has. A row the projection no longer contains (an evicted or
411
- // history-only record) falls back to its own recorded source, which is a fact the
412
- // record states — never a guess.
413
- const key = projectKeyOfRow(row, nodeProjects);
414
- const entry = {
415
- taskId,
416
- title: typeof row.title === 'string' && row.title !== '' ? row.title : '未记录标题',
417
- sessionId: taskSessionId(row),
418
- status: statusOf(row),
419
- archived: isArchived,
420
- };
421
- groupOf(isArchived ? archived : active, key).sessions.push(entry);
422
- }
423
-
424
- // A project the host named is shown even when none of its nodes has executed yet,
425
- // so "planned, nothing dispatched" and "no such project" read differently. The
426
- // `unverified` bucket is NOT created here: it appears only when a record really has
427
- // an unconfirmed source, so an empty "来源未确认" group is never invented.
428
- for (const [key, info] of meta) {
429
- if (info.nodeCount > 0 && key !== 'unverified') groupOf(active, key);
430
- }
431
-
432
- const order = (left, right) => {
433
- const leftInfo = meta.get(left.key) ?? null;
434
- const rightInfo = meta.get(right.key) ?? null;
435
- const leftUnverified = left.key === 'unverified' || leftInfo?.unverified === true;
436
- const rightUnverified = right.key === 'unverified' || rightInfo?.unverified === true;
437
- if (leftUnverified !== rightUnverified) return leftUnverified ? 1 : -1;
438
- const leftName = leftInfo?.name ?? projectLabel(left.key);
439
- const rightName = rightInfo?.name ?? projectLabel(right.key);
440
- if (leftName !== rightName) return leftName < rightName ? -1 : 1;
441
- return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
442
- };
443
-
444
- const groups = [...active.values()].sort(order);
445
- const archivedGroups = [...archived.values()].sort(order);
446
- const activeCount = groups.reduce((total, group) => total + group.sessions.length, 0);
447
- const archivedCount = archivedGroups.reduce((total, group) => total + group.sessions.length, 0);
448
- return {
449
- groups,
450
- archivedGroups,
451
- activeCount,
452
- archivedCount,
453
- /// Live rounds plus archived rows: everything the record holds.
454
- total: rows.length,
455
- available: tree !== null && (Array.isArray(tree.roots) || Array.isArray(tree.flatNodes)),
456
- meta,
457
- };
458
- }
459
-
460
- /**
461
- * One record's project key, from the host's own statements.
462
- *
463
- * Order of evidence, strongest first:
464
- * 1. the projection's key for the node with this row's identity (the host already
465
- * resolved the project for it);
466
- * 2. the row's own recorded digest, which is the key the projection uses for a
467
- * verified source;
468
- * 3. the row's own recorded path, for a legacy record without a digest;
469
- * 4. `unverified` when the row recorded a source at all, else `unconfirmed`.
470
- * A row is never attributed by title, position or a path guess; `unverified` and
471
- * `unconfirmed` stay their own groups precisely so nothing is invented.
472
- * @param {object} row - one `/tasks` row.
473
- * @param {Map<string, string>} nodeProjects - projected node id → project key.
474
- * @returns {string} project key.
475
- */
476
- function projectKeyOfRow(row, nodeProjects) {
477
- const taskId = typeof row?.taskId === 'string' ? row.taskId : '';
478
- if (taskId !== '' && nodeProjects instanceof Map) {
479
- const projected = nodeProjects.get(taskId);
480
- if (typeof projected === 'string' && projected !== '') return projected;
481
- }
482
- if (typeof row?.projectKey === 'string' && row.projectKey !== '') return row.projectKey;
483
- const digest = typeof row?.sourcePathDigest === 'string' ? row.sourcePathDigest.trim() : '';
484
- if (digest !== '') return digest;
485
- const sourcePath = typeof row?.sourcePath === 'string' ? row.sourcePath.trim() : '';
486
- if (sourcePath !== '') return `path:${sourcePath.replace(/[\\/]+$/u, '')}`;
487
- return 'unconfirmed';
488
- }
489
-
490
- /**
491
- * Where the archived rows came from, in operator words.
492
- * @param {object} snapshot - page store snapshot.
493
- * @returns {string | null} a short reason, or null when there is nothing to explain.
494
- */
495
- export function archivedSourceNote(snapshot) {
496
- const total = navViewModel(snapshot).archivedCount;
497
- if (total === 0) return null;
498
- return snapshot?.tree !== null && snapshot?.tree !== undefined
499
- ? '这些记录带 TaskBridge 的归档标记(displayArchived)。这里只是把它们单独列出,DSH 的归档状态没有改变。从历史恢复出来的记录不算归档,仍在上方的列表里。'
500
- : '宿主没有返回任务树,已归档标记无法核实;这里只按记录自身的归档状态列出。';
501
- }
502
-
503
- /**
504
- * The human-readable label of one project group, when the host did not name it.
505
- * @param {string} key - host project key.
506
- * @returns {string} label.
507
- */
508
- export function projectLabel(key) {
509
- if (key === 'unverified') return '来源未确认的记录';
510
- if (key === 'unconfirmed') return '没有项目信息的记录';
511
- if (key.startsWith('path:')) {
512
- const parts = key.slice(5).split(/[\\/]+/u).filter(Boolean);
513
- return parts.slice(-2).join('/') || key;
514
- }
515
- if (key.startsWith('sha256:')) return `项目 ${key.slice(-6)}`;
516
- return key.length <= 28 ? key : `${key.slice(0, 24)}…`;
517
- }
518
-
519
- /**
520
- * A group's title: the host's own project name first, then the key itself.
521
- * @param {object} group - one `navViewModel` group.
522
- * @param {Map} meta - the view's project metadata.
523
- * @returns {string} title.
524
- */
525
- export function groupTitle(group, meta) {
526
- const info = meta instanceof Map ? meta.get(group.key) : null;
527
- if (typeof info?.name === 'string' && info.name !== '') {
528
- return info.shortPath !== null && info.shortPath !== undefined && info.shortPath !== info.name
529
- ? `${info.name}(${info.shortPath})`
530
- : info.name;
531
- }
532
- return projectLabel(group.key);
533
- }
534
-
535
- // ---------------------------------------------------------------------------
536
- // Navigation through DSH's own Workspace service
537
- // ---------------------------------------------------------------------------
538
-
539
- /**
540
- * Open one recorded session in DSH, if and only if the host can vouch for it.
541
- *
542
- * The order is deliberate: VERIFY, then call `openSession` EXACTLY ONCE. A plugin that
543
- * opened first and apologised later could move the operator into another
544
- * conversation, and a retry loop around `openSession` could open it twice.
545
- *
546
- * Every refusal is stated, and none of them is a navigation attempt:
547
- * * no `uiWorkspace` → the host cannot navigate at all;
548
- * * no recorded id → nothing to open;
549
- * * snapshot not ready → "retry later", because nothing is verified yet;
550
- * * id in `archivedSessionIds` → DSH archived it; only DSH can bring it back;
551
- * * id absent from a ready snapshot → refused explicitly, not opened on faith;
552
- * * no `workspaces` service → DSH cannot verify it, so it does not open it.
553
- * @param {object | null} uiWorkspace - `ctx.get('uiWorkspace')`, or null.
554
- * @param {string | null} sessionId - the host-recorded session id.
555
- * @param {object | null} workspaces - the host `workspaces` service (its own source).
556
- * @returns {Promise<{ ok: boolean, message: string }>} outcome with readable copy.
557
- */
558
- export async function locateSession(uiWorkspace, sessionId, workspaces = null) {
559
- if (uiWorkspace === null || uiWorkspace === undefined || typeof uiWorkspace.openSession !== 'function') {
560
- return { ok: false, message: '当前宿主没有提供会话定位能力(uiWorkspace),只显示记录,不跳转。' };
561
- }
562
- if (typeof sessionId !== 'string' || sessionId === '') {
563
- return { ok: false, message: '这条记录没有可核实的会话标识,无法定位到原生会话。' };
564
- }
565
- const placement = sessionPlacement(sessionId, workspaces);
566
- const short = shortSessionId(sessionId);
567
- if (placement.state === 'pending') {
568
- return { ok: false, message: 'DSH 的会话列表还没准备好,请稍后重试。' };
569
- }
570
- if (placement.state === 'archived') {
571
- return { ok: false, message: `会话 ${short} 已在 DSH 中归档,请到 DSH 的归档里打开。` };
572
- }
573
- if (placement.state === 'missing') {
574
- return { ok: false, message: `DSH 当前的会话列表里没有 ${short},不打开它。` };
575
- }
576
- if (placement.state === 'unknown') {
577
- // No verification is possible on this host, so the plugin does not guess at an
578
- // identity it cannot check. This is the documented degradation, stated plainly.
579
- return { ok: false, message: '当前宿主没有提供会话列表(workspaces),无法核实这条记录,未跳转。' };
580
- }
581
- try {
582
- const result = uiWorkspace.openSession(sessionId);
583
- if (result !== null && typeof result?.then === 'function') await result;
584
- } catch (error) {
585
- const detail = typeof error?.message === 'string' && error.message !== '' ? error.message : '';
586
- return { ok: false, message: `定位会话失败:${detail === '' ? '宿主没有接受这次定位' : detail.slice(0, 160)}` };
587
- }
588
- return { ok: true, message: `已在 DSH 中定位会话 ${short}。` };
589
- }
590
-
591
- // ---------------------------------------------------------------------------
592
- // Components
593
- // ---------------------------------------------------------------------------
594
-
595
- /**
596
- * Decorative icon rendered inside the host’s sidebar button.
597
- *
598
- * Decorative on purpose: the row in `sidebar.panellist` carries the label, so the
599
- * icon is hidden from assistive technology rather than announcing the entry twice.
600
- * @returns {object} an inline SVG.
601
- */
602
- export function TaskbridgeSidebarIcon({ size = 16 } = {}) {
603
- return (
604
- <svg
605
- className="dshdg-nav-icon"
606
- width={size}
607
- height={size}
608
- viewBox="0 0 16 16"
609
- fill="none"
610
- stroke="currentColor"
611
- strokeWidth="1.4"
612
- strokeLinecap="round"
613
- strokeLinejoin="round"
614
- aria-hidden="true"
615
- focusable="false"
616
- data-dshdg-nav-icon=""
617
- >
618
- <path d="M2.5 4.2h4.2l1.2 1.4h5.6v6.6a1 1 0 0 1-1 1H3.5a1 1 0 0 1-1-1z" />
619
- <path d="M5.4 9.1l1.5 1.5 2.7-2.9" />
620
- </svg>
621
- );
622
- }
623
-
624
- /** One session row. */
625
- function SessionRow({ entry, onLocate, locating }) {
626
- const verified = typeof entry.sessionId === 'string' && entry.sessionId !== '';
627
- return (
628
- <li className="dshdg-nav-session" data-dshdg-nav-session={entry.taskId}>
629
- <span className="dshdg-nav-session-title" title={entry.title}>{entry.title}</span>
630
- <span className={`dshdg-badge dshdg-badge-${entry.status.tone}`}>{entry.status.label}</span>
631
- <span className="dshdg-spacer" />
632
- {verified ? (
633
- <span className="dshdg-faint dshdg-mono" title={entry.sessionId}>{shortSessionId(entry.sessionId)}</span>
634
- ) : (
635
- <span className="dshdg-faint" data-dshdg-nav-unverified="">无原生会话标识</span>
636
- )}
637
- <button
638
- type="button"
639
- data-dshdg-nav-locate={entry.taskId}
640
- disabled={!verified || locating}
641
- title={verified ? '在 DSH 中打开这条记录对应的原生会话' : '这条历史记录没有记录会话标识,无法定位'}
642
- onClick={() => { void onLocate(entry); }}
643
- >
644
- 定位
645
- </button>
646
- </li>
647
- );
648
- }
649
-
650
- /** One project group, collapsible. */
651
- function ProjectGroup({ group, meta, open, onToggle, onLocate, locating }) {
652
- const key = group.key;
653
- const title = groupTitle(group, meta);
654
- const controlId = `dshdg-nav-body-${key}`;
655
- const unverified = key === 'unverified';
656
- return (
657
- <li className="dshdg-nav-project" data-dshdg-nav-project={key}>
658
- <div className="dshdg-nav-project-head">
659
- <button
660
- type="button"
661
- className="dshdg-tree-toggle"
662
- data-dshdg-nav-toggle={key}
663
- aria-expanded={open}
664
- aria-controls={controlId}
665
- onClick={() => onToggle(key)}
666
- >
667
- {open ? '收起' : '展开'}
668
- </button>
669
- <span className="dshdg-nav-project-title" title={key}>{title}</span>
670
- {unverified ? <span className="dshdg-badge dshdg-badge-warn">来源未确认</span> : null}
671
- <span className="dshdg-spacer" />
672
- <span className="dshdg-faint">{`${group.sessions.length} 个会话`}</span>
673
- </div>
674
- {open ? (
675
- <ul id={controlId} className="dshdg-nav-sessions" role="group" aria-label={`${title} 的会话`}>
676
- {group.sessions.map((entry) => (
677
- <SessionRow key={entry.taskId} entry={entry} onLocate={onLocate} locating={locating} />
678
- ))}
679
- </ul>
680
- ) : null}
681
- </li>
682
- );
683
- }
684
-
685
- /**
686
- * The panel registered in `sidebar.panellist`.
687
- *
688
- * Its clock is the page store it is handed (`inject` face). Opening the panel does
689
- * not read anything on its own beyond that store's own subscription; the explicit
690
- * refresh button is the only thing here that asks the host for a list.
691
- *
692
- * A panel rendered without a store (a host that hands the slot no props) says so
693
- * instead of throwing, so a slot-shape change can never take the shell down.
694
- * @param {object} props - `store`, `uiWorkspace`, `workspaces`.
695
- * @returns {object} the panel.
696
- */
697
- export function TaskbridgeNavPanel(props) {
698
- const store = props?.store ?? null;
699
- const uiWorkspace = props?.uiWorkspace ?? null;
700
- const workspaces = props?.workspaces ?? null;
701
- const [showArchived, setShowArchived] = useState(false);
702
- const [collapsed, setCollapsed] = useState(() => new Set());
703
- const [locating, setLocating] = useState(false);
704
- const [feedback, setFeedback] = useState(null);
705
- const requested = useRef(false);
706
-
707
- const subscribe = useCallback(
708
- (listener) => (typeof store?.subscribe === 'function' ? store.subscribe(listener) : () => {}),
709
- [store],
710
- );
711
- // `useSyncExternalStore` requires getSnapshot to be REFERENTIALLY stable between
712
- // renders while nothing changed: a new object per call re-renders forever. The page
713
- // store returns its own state object (stable), so the identity is reused as-is; a
714
- // store-less panel returns the module's frozen empty snapshot; anything else that
715
- // hands back a fresh object is cached until its `revision` moves.
716
- const stable = useRef({ raw: EMPTY_SNAPSHOT, value: EMPTY_SNAPSHOT, revision: null });
717
- const getSnapshot = useCallback(() => {
718
- const raw = store === null ? EMPTY_SNAPSHOT : (typeof store?.getSnapshot === 'function' ? store.getSnapshot() : EMPTY_SNAPSHOT);
719
- const cache = stable.current;
720
- if (raw === cache.raw) return cache.value;
721
- // A store that already hands out stable objects (the page store does) is used
722
- // directly; a `revision` counter, when present, is the store's own promise that
723
- // an unchanged number means unchanged data.
724
- const revision = typeof raw?.revision === 'number' ? raw.revision : null;
725
- if (revision !== null && revision === cache.revision && cache.raw !== EMPTY_SNAPSHOT) {
726
- cache.raw = raw;
727
- return cache.value;
728
- }
729
- cache.raw = raw;
730
- cache.value = raw;
731
- cache.revision = revision;
732
- return raw;
733
- }, [store]);
734
- const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
735
-
736
- // The initial read happens in an EFFECT, never during render: writing to the store
737
- // while rendering would be a side effect on another component's state. It runs at
738
- // most once per panel instance, and only when the shared store holds no records yet
739
- // (the settings page, or a G07 refresh, may already have read them).
740
- useEffect(() => {
741
- if (requested.current) return;
742
- if (store === null || typeof store.loadTasks !== 'function') return;
743
- const loaded = Array.isArray(snapshot.tasks) && snapshot.tasks.length > 0;
744
- if (loaded) {
745
- requested.current = true;
746
- return;
747
- }
748
- requested.current = true;
749
- void Promise.resolve(store.loadTasks()).catch(() => {});
750
- // `snapshot.tasks` is read once at mount on purpose; later refreshes are explicit.
751
- // eslint-disable-next-line react-hooks/exhaustive-deps
752
- }, [store]);
753
-
754
- const view = useMemo(() => navViewModel(snapshot), [snapshot]);
755
- const archivedNote = useMemo(() => archivedSourceNote(snapshot), [snapshot]);
756
- // Records exist but none of them is live: the empty line below must not claim the
757
- // host has no records at all.
758
- const liveEmpty = view.activeCount === 0 && view.archivedCount > 0;
759
- const onToggle = useCallback((key) => {
760
- setCollapsed((previous) => {
761
- const next = new Set(previous);
762
- if (next.has(key)) next.delete(key);
763
- else next.add(key);
764
- return next;
765
- });
766
- }, []);
767
- const onLocate = useCallback(async (entry) => {
768
- setLocating(true);
769
- try {
770
- // Resolved here, not at render: the host services may mount after the panel.
771
- const outcome = await locateSession(resolveService(uiWorkspace), entry.sessionId, resolveService(workspaces));
772
- setFeedback({ ok: outcome.ok, message: outcome.message });
773
- } finally {
774
- setLocating(false);
775
- }
776
- }, [uiWorkspace, workspaces]);
777
- const onRefresh = useCallback(() => { void Promise.resolve(store?.loadTasks?.()).catch(() => {}); }, [store]);
778
-
779
- return (
780
- <section className="dshdg-nav" aria-labelledby="dshdg-nav-title" data-dshdg-nav-panel="">
781
- <div className="dshdg-nav-head">
782
- <h3 id="dshdg-nav-title">{TASKS_NAV_LABEL}</h3>
783
- <span className="dshdg-spacer" />
784
- <button type="button" data-dshdg-nav-refresh="" onClick={onRefresh}>刷新</button>
785
- </div>
786
- <p className="dshdg-faint dshdg-nav-note">
787
- {`按项目列出 TaskBridge 的逻辑任务与它们的原生会话(${view.activeCount} 个会话${view.archivedCount > 0 ? `,另有 ${view.archivedCount} 条已归档` : ''})。这里只读 TaskBridge 记录,不改名、不移动、不归档 DSH 会话。`}
788
- </p>
789
- {snapshot.tasksError !== null && snapshot.tasksError !== undefined ? (
790
- <p className="dshdg-warn" data-dshdg-nav-error="">任务记录这次没有读到;下方显示的是已有的内容。</p>
791
- ) : null}
792
- {view.total === 0 ? (
793
- <p className="dshdg-faint" data-dshdg-nav-empty="">还没有执行记录。</p>
794
- ) : (
795
- <ul className="dshdg-nav-projects">
796
- {liveEmpty ? (
797
- <li className="dshdg-faint" data-dshdg-nav-all-archived="">没有进行中的记录;已归档的记录在下方。</li>
798
- ) : null}
799
- {view.groups.map((group) => (
800
- <ProjectGroup
801
- key={group.key}
802
- group={group}
803
- meta={view.meta}
804
- open={!collapsed.has(group.key)}
805
- onToggle={onToggle}
806
- onLocate={onLocate}
807
- locating={locating}
808
- />
809
- ))}
810
- </ul>
811
- )}
812
- {view.archivedCount > 0 ? (
813
- <div className="dshdg-nav-archived">
814
- <label className="dshdg-nav-toggle-row">
815
- <input
816
- type="checkbox"
817
- data-dshdg-nav-archived-toggle=""
818
- checked={showArchived}
819
- onChange={(event) => setShowArchived(event.target.checked)}
820
- />
821
- <span>{`显示 TaskBridge 已归档的记录(${view.archivedCount})`}</span>
822
- </label>
823
- <p className="dshdg-faint">{archivedNote}</p>
824
- {showArchived ? (
825
- <ul className="dshdg-nav-projects">
826
- {view.archivedGroups.map((group) => (
827
- <li className="dshdg-nav-project" key={group.key} data-dshdg-nav-archived-project={group.key}>
828
- <div className="dshdg-nav-project-head">
829
- <span className="dshdg-nav-project-title" title={group.key}>{groupTitle(group, view.meta)}</span>
830
- <span className="dshdg-faint">{`${group.sessions.length} 条已归档`}</span>
831
- </div>
832
- <ul className="dshdg-nav-sessions">
833
- {group.sessions.map((entry) => (
834
- <li className="dshdg-nav-session" key={entry.taskId} data-dshdg-nav-archived-session={entry.taskId}>
835
- <span className="dshdg-nav-session-title" title={entry.title}>{entry.title}</span>
836
- <span className={`dshdg-badge dshdg-badge-${entry.status.tone}`}>{entry.status.label}</span>
837
- <span className="dshdg-faint">已归档</span>
838
- </li>
839
- ))}
840
- </ul>
841
- </li>
842
- ))}
843
- </ul>
844
- ) : null}
845
- </div>
846
- ) : null}
847
- {feedback === null ? null : (
848
- <p
849
- className={feedback.ok ? 'dshdg-hint' : 'dshdg-warn'}
850
- role="status"
851
- aria-live="polite"
852
- data-dshdg-nav-feedback={feedback.ok ? 'ok' : 'refused'}
853
- >
854
- {feedback.message}
855
- </p>
856
- )}
857
- </section>
858
- );
859
- }
860
-
861
- /** Stable empty snapshot, so a store-less panel never allocates per render. */
862
- const EMPTY_SNAPSHOT = Object.freeze({ tasks: [], tree: null, tasksError: null });
1
+ // dsh-delegate — native left navigation: the TaskBridge task entry and its panel.
2
+ //
3
+ // This file is the ONLY thing in the bundle that touches the host's main/sidebar
4
+ // slot names. It is deliberately small: the panel it registers reads the task data
5
+ // the bundle already fetched, and its own collapse state is local. It draws no
6
+ // second task tree and performs no navigation of its own beyond asking DSH's own
7
+ // Workspace service to open a session whose identity TaskBridge recorded.
8
+ //
9
+ // What is registered, and against WHAT CONTRACT
10
+ // --------------------------------------------
11
+ // Two registrations, both through `ctx.slots.inject(name, register)`, matching the
12
+ // host exactly (0.2.2-rc.5,
13
+ // `@deepseek-ai/dsh-client-ui-plugin-manager/src/client/index.ts`):
14
+ //
15
+ // * `main` — the FULL CONTENT PANEL,
16
+ // `{ name: 'main', key }`, registered with the panel
17
+ // component. The host hands the owner `size`/`active`.
18
+ // * `sidebar.panellist`— the SMALL ICON,
19
+ // `{ name: 'sidebar.panellist', id, order, label }`,
20
+ // registered with the icon component. `label` is a FUNCTION
21
+ // the host calls for the row's text.
22
+ // The two share one id (`TASKS_NAV_KEY`), which is how the row selects the panel.
23
+ //
24
+ // Both slots belong to the host's own shell. They are OPTIONAL here: a host (or a
25
+ // shell rebuild) that never declares them simply never runs the registrations, and
26
+ // `inject` disposes them on the way out. That matters because the bundle's existing
27
+ // `plugins.bundle.config` page must keep working on a host without a sidebar — so
28
+ // nothing in this module is a prerequisite for the settings page.
29
+ //
30
+ // The shell's own workspace/session browsing region belongs to DSH: THIS module never
31
+ // registers there, and no TaskBridge task view replaces it. The grouped workspaces
32
+ // browser is a SEPARATE registration (`workspaces-browser.jsx`, `sidebar.workspaces`,
33
+ // lower priority than the shipped entry) whose identity rules are stated there and in
34
+ // `docs/workspace-grouping.md`; it keeps ordinary Workspaces, and it falls back to the
35
+ // shipped browser whenever it cannot prove what belongs to which project.
36
+ //
37
+ // What the panel may and may not do
38
+ // ---------------------------------
39
+ // * It reads records from the SAME page store `apply` already built, so opening it
40
+ // never duplicates a read. The initial load runs in an effect (never in render);
41
+ // there is no per-row request and no timer.
42
+ // * A session is offered for navigation only when the record carries the host's
43
+ // real session id AND the host's own `workspaces` snapshot can vouch for it.
44
+ // * It never renames, moves, archives or deletes a session. Archiving stays a DSH
45
+ // action performed in DSH's own UI.
46
+ //
47
+ // Rendering rules worth keeping:
48
+ // * same-titled projects stay separate entries (identity is the host's project
49
+ // key, never the title);
50
+ // * a record whose source could not be confirmed is shown as such, in its own
51
+ // group, and is never folded into a real project;
52
+ // * a historical record without a navigation identifier stays listed, with the
53
+ // reason stated, rather than disappearing.
54
+
55
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
56
+
57
+ import { taskOutcome, TREE_STATUS_LABELS, TREE_STATUS_TONES } from './api.js';
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Slot names and registration keys
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /** The host's registry slot: main-area entries (the sidebar icon). */
64
+ export const MAIN_SLOT = 'main';
65
+
66
+ /** The host's registry slot: the left sidebar's panel list (the row). */
67
+ export const SIDEBAR_PANEL_SLOT = 'sidebar.panellist';
68
+
69
+ /**
70
+ * One id for both registrations.
71
+ *
72
+ * The icon in `main` and the row in `sidebar.panellist` are two halves of the same
73
+ * entry, so they share an identity. It is namespaced because the sidebar is shared
74
+ * with other plugins.
75
+ */
76
+ export const TASKS_NAV_KEY = 'dsh-taskbridge:taskbridge-tasks';
77
+
78
+ /** Smallest order that keeps this entry at the front without taking part 100. */
79
+ export const TASKS_NAV_ORDER = 20;
80
+
81
+ /** Operator-facing label of the entry. */
82
+ export const TASKS_NAV_LABEL = 'TaskBridge 任务';
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Pure helpers (exported so a test can drive them without a browser)
86
+ // ---------------------------------------------------------------------------
87
+
88
+ /**
89
+ * The host Workspace service, if this host has one.
90
+ *
91
+ * `ctx.get` is the Cordis lookup; a host that does not compose Workspace answering
92
+ * with nothing here is the documented degradation, not an error.
93
+ * @param {object | null | undefined} ctx - client context.
94
+ * @returns {object | null} service exposing `openSession`.
95
+ */
96
+ export function resolveUiWorkspace(ctx) {
97
+ const get = ctx !== null && typeof ctx === 'object' ? ctx.get : null;
98
+ if (typeof get !== 'function') return null;
99
+ let service = null;
100
+ try {
101
+ service = get.call(ctx, 'uiWorkspace');
102
+ } catch {
103
+ service = null;
104
+ }
105
+ if (service === null || typeof service !== 'object') return null;
106
+ return typeof service.openSession === 'function' ? service : null;
107
+ }
108
+
109
+ /**
110
+ * The host's `workspaces` service, if this host has one.
111
+ *
112
+ * It is a separate service from `uiWorkspace`: `uiWorkspace` opens a session, while
113
+ * `workspaces.list` is the subscribable source (`{ getSnapshot, subscribe }`) whose
114
+ * snapshot says which sessions exist and which are archived. Both are looked up
115
+ * lazily, because the host may compose them after this plugin mounts.
116
+ * @param {object | null | undefined} ctx - client context.
117
+ * @returns {object | null} service exposing `list.getSnapshot`.
118
+ */
119
+ export function resolveWorkspaces(ctx) {
120
+ const get = ctx !== null && typeof ctx === 'object' ? ctx.get : null;
121
+ if (typeof get !== 'function') return null;
122
+ let service = null;
123
+ try {
124
+ service = get.call(ctx, 'workspaces');
125
+ } catch {
126
+ service = null;
127
+ }
128
+ if (service === null || typeof service !== 'object') return null;
129
+ return typeof service.list?.getSnapshot === 'function' ? service : null;
130
+ }
131
+
132
+ /**
133
+ * Resolve one service that may be a value or a lazy getter.
134
+ *
135
+ * `apply` passes getters so a host service composed AFTER this plugin mounts is still
136
+ * found when it is finally used; a plain value (a test double, or a host that had it
137
+ * ready) is returned as-is.
138
+ * @param {unknown} value - service, getter, or nothing.
139
+ * @returns {object | null} the service.
140
+ */
141
+ export function resolveService(value) {
142
+ if (typeof value === 'function') {
143
+ try {
144
+ const resolved = value();
145
+ return resolved !== null && typeof resolved === 'object' ? resolved : null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ return value !== null && typeof value === 'object' ? value : null;
151
+ }
152
+
153
+ /**
154
+ * Register the entry on a client context.
155
+ *
156
+ * The split matches the host exactly (0.2.2-rc.5,
157
+ * `dsh-client-ui-plugin-manager/src/client/index.ts`):
158
+ * * `main` — the FULL CONTENT PANEL, `{ name: 'main', key: PANEL_ID }`,
159
+ * registered with the page component. The host gives the
160
+ * owner its `size`/`active` seats.
161
+ * * `sidebar.panellist` — the SMALL ICON, `{ name: 'sidebar.panellist', id, order,
162
+ * label }`, registered with the icon component. `label` is
163
+ * a function the host calls for the row's text.
164
+ * The two share one id, which is how the row selects the panel.
165
+ *
166
+ * Exactly ONE store instance is passed in and used by both halves, so opening the
167
+ * entry never issues a second read for records the page already holds.
168
+ *
169
+ * Split out from `apply` so a test can hand it a fake `ctx` and assert the exact
170
+ * registration shape without a browser. A missing `slots` service is a host without
171
+ * the sidebar: both registrations are skipped and this returns a no-op.
172
+ * @param {object} ctx - client Cordis context.
173
+ * @param {object} options - `store`, `uiWorkspace`, `workspaces`.
174
+ * @returns {() => void} disposer releasing both registrations.
175
+ */
176
+ export function registerTasksNavigation(ctx, options = {}) {
177
+ const slots = ctx?.slots;
178
+ if (slots === null || slots === undefined || typeof slots.inject !== 'function') return () => {};
179
+ const { store = null, uiWorkspace = null, workspaces = null } = options;
180
+
181
+ const panel = () => TaskbridgeNavPanel({ store, uiWorkspace, workspaces });
182
+ const icon = TaskbridgeSidebarIcon;
183
+
184
+ const registerPanel = options.registerPanel ?? (() => slots.inject(MAIN_SLOT, () => slots.register({
185
+ name: MAIN_SLOT,
186
+ key: TASKS_NAV_KEY,
187
+ }, panel)));
188
+
189
+ const registerIcon = options.registerIcon ?? (() => slots.inject(SIDEBAR_PANEL_SLOT, () => slots.register({
190
+ name: SIDEBAR_PANEL_SLOT,
191
+ id: TASKS_NAV_KEY,
192
+ order: TASKS_NAV_ORDER,
193
+ label: () => TASKS_NAV_LABEL,
194
+ }, icon)));
195
+
196
+ const disposers = [];
197
+ // Each registration stands on its own: a host that declares only one of the two
198
+ // slots still gets the half it declares, and a refusal of one never cancels the
199
+ // other. `inject` itself only defers; nothing here throws for a missing slot.
200
+ for (const register of [registerPanel, registerIcon]) {
201
+ try {
202
+ const dispose = register();
203
+ if (typeof dispose === 'function') disposers.push(dispose);
204
+ } catch {
205
+ // A host whose slot API refuses this registration keeps working; the entry
206
+ // simply does not appear. Nothing else in the bundle depends on it.
207
+ }
208
+ }
209
+ return () => {
210
+ for (const dispose of disposers) {
211
+ try {
212
+ dispose();
213
+ } catch {
214
+ // Disposal is best-effort: a disposer that already ran must not fail twice.
215
+ }
216
+ }
217
+ };
218
+ }
219
+
220
+ /** The label a session id is shown with: shortened, never guessed. */
221
+ export function shortSessionId(sessionId) {
222
+ if (typeof sessionId !== 'string' || sessionId === '') return '';
223
+ return sessionId.length <= 12 ? sessionId : `${sessionId.slice(0, 6)}…${sessionId.slice(-4)}`;
224
+ }
225
+
226
+ /**
227
+ * The navigation identifier TaskBridge recorded for ONE task, or null.
228
+ *
229
+ * Only a host-recorded identity counts. Order of evidence, strongest first:
230
+ * 1. the record's OWN top-level `sessionId` — a historical (restored) record keeps
231
+ * its thread there, and that is the record alive in the current host;
232
+ * 2. the run's `execution.sessionId`;
233
+ * 3. the conversation's own `sessionId`.
234
+ * Nothing is derived from the task id, a title, a workspace path or a position,
235
+ * because none of those identify a native session.
236
+ * @param {object | null | undefined} task - one `/tasks` row.
237
+ * @returns {string | null} session id.
238
+ */
239
+ export function taskSessionId(task) {
240
+ if (task === null || task === undefined || typeof task !== 'object') return null;
241
+ for (const candidate of [task.sessionId, task.execution?.sessionId, task.conversation?.sessionId]) {
242
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();
243
+ }
244
+ return null;
245
+ }
246
+
247
+ /**
248
+ * Read the host's Workspaces snapshot, or null when it cannot be read synchronously.
249
+ *
250
+ * The host service is `{ getSnapshot, subscribe }`; its snapshot is
251
+ * `{ phase, items: [{ workspaceId, sessionIds, ... }], archivedSessionIds }`. Anything
252
+ * else (an absent service, a throwing/suspending source) yields null, which the caller
253
+ * treats as "cannot check" rather than guessing.
254
+ * @param {object | null | undefined} workspaces - host `workspaces` service.
255
+ * @returns {object | null} the snapshot.
256
+ */
257
+ export function workspacesSnapshot(workspaces) {
258
+ const source = workspaces?.list;
259
+ if (source === null || source === undefined || typeof source.getSnapshot !== 'function') return null;
260
+ let snapshot = null;
261
+ try {
262
+ snapshot = source.getSnapshot();
263
+ } catch {
264
+ return null;
265
+ }
266
+ if (snapshot === null || typeof snapshot !== 'object' || Array.isArray(snapshot)) return null;
267
+ return snapshot;
268
+ }
269
+
270
+ /**
271
+ * Every session id the host's snapshot knows, with the workspace it belongs to.
272
+ * @param {object | null} snapshot - `workspacesSnapshot(...)`.
273
+ * @returns {Map<string, string>} session id → workspace id.
274
+ */
275
+ export function knownSessionIds(snapshot) {
276
+ const index = new Map();
277
+ for (const item of Array.isArray(snapshot?.items) ? snapshot.items : []) {
278
+ if (item === null || typeof item !== 'object') continue;
279
+ const workspaceId = typeof item.workspaceId === 'string' ? item.workspaceId : '';
280
+ for (const sessionId of Array.isArray(item.sessionIds) ? item.sessionIds : []) {
281
+ if (typeof sessionId === 'string' && sessionId !== '' && !index.has(sessionId)) index.set(sessionId, workspaceId);
282
+ }
283
+ }
284
+ return index;
285
+ }
286
+
287
+ /**
288
+ * Where an id sits among the host's own Workspaces.
289
+ *
290
+ * Read from `workspaces.list.getSnapshot()`. The answers are kept apart on purpose,
291
+ * because each calls for a different action:
292
+ * * `pending` — the snapshot is not ready yet (a phase other than ready, or no
293
+ * snapshot). Nothing can be verified, so the operator is told to
294
+ * retry later rather than sent somewhere unverified.
295
+ * * `present` — the host lists this session in a workspace, and it is not archived.
296
+ * This is the only state that may be opened.
297
+ * * `archived` — the id is in the host's own `archivedSessionIds`. Refused, and NOT
298
+ * reported as missing: DSH archived it, and only DSH can put it back.
299
+ * * `missing` — the snapshot is ready and lists neither, so the id is not a live
300
+ * session here. Refused explicitly instead of opened on faith.
301
+ * * `unknown` — no service at all (a host without Workspaces).
302
+ * @param {string | null} sessionId - host session id.
303
+ * @param {object | null | undefined} workspaces - host Workspace service.
304
+ * @returns {{ state: 'unknown'|'pending'|'present'|'archived'|'missing', label: string | null, workspaceId: string | null }} placement.
305
+ */
306
+ export function sessionPlacement(sessionId, workspaces) {
307
+ const label = () => (typeof sessionId === 'string' && sessionId !== '' ? shortSessionId(sessionId) : null);
308
+ const snapshot = workspacesSnapshot(workspaces);
309
+ if (snapshot === null) return { state: 'unknown', label: label(), workspaceId: null };
310
+ // The host publishes its own readiness; anything but `ready` means "cannot tell yet".
311
+ if (snapshot.phase !== 'ready') return { state: 'pending', label: label(), workspaceId: null };
312
+ if (typeof sessionId !== 'string' || sessionId === '') return { state: 'missing', label: null, workspaceId: null };
313
+ const archived = Array.isArray(snapshot.archivedSessionIds) ? snapshot.archivedSessionIds : [];
314
+ if (archived.includes(sessionId)) return { state: 'archived', label: label(), workspaceId: null };
315
+ const workspaceId = knownSessionIds(snapshot).get(sessionId) ?? null;
316
+ if (workspaceId === null) return { state: 'missing', label: label(), workspaceId: null };
317
+ return { state: 'present', label: label(), workspaceId };
318
+ }
319
+
320
+ /** Use the task page's status, including whether its review was saved. */
321
+ function statusOf(row) {
322
+ const key = typeof row.nodeStatus === 'string' ? row.nodeStatus : (typeof row.state === 'string' ? row.state : 'unknown');
323
+ const { label, tone } = taskOutcome(row);
324
+ if (label !== '') return { key, label, tone };
325
+ return { key, label: TREE_STATUS_LABELS[key] ?? key, tone: TREE_STATUS_TONES[key] ?? 'off' };
326
+ }
327
+
328
+ /**
329
+ * The panel's model: projects, their sessions, and what may be opened.
330
+ *
331
+ * Groups are keyed by the host's project key — never by a title — so two projects
332
+ * with the same name stay two entries; `tree.projects` carries the host's own
333
+ * display name and short path for each key, and a key it does not name falls back to
334
+ * the key itself. `unverified` (the projection's "来源未确认") is its own group and is
335
+ * never merged into a named one.
336
+ *
337
+ * A session row is a task the host recorded. Its navigation identity is only ever
338
+ * the host-recorded session id; a row without one is still listed, marked, and its
339
+ * locate control is disabled — a historical record must not vanish just because it
340
+ * cannot be opened.
341
+ *
342
+ * Archived records come from the OPTIONAL `displayArchived` boolean G07 adds to each
343
+ * tree node. That flag is read, never written: toggling this list cannot archive,
344
+ * rename or move anything in DSH. A record's own `archived` field is NOT this flag —
345
+ * it marks a record recovered from durable history, which is a live record and stays
346
+ * in the active list. When G07 has not published the flag, every record is treated as
347
+ * an ordinary historical one.
348
+ * @param {object} snapshot - page store snapshot.
349
+ * @returns {object} `{ groups, archivedGroups, activeCount, archivedCount, total, available, projectName }`.
350
+ */
351
+ export function navViewModel(snapshot) {
352
+ const tree = snapshot?.tree ?? null;
353
+ const rows = Array.isArray(snapshot?.tasks) ? snapshot.tasks : [];
354
+
355
+ // The host's project summaries, by key: display name, short path and order.
356
+ const meta = new Map();
357
+ for (const project of Array.isArray(tree?.projects) ? tree.projects : []) {
358
+ if (project === null || typeof project !== 'object') continue;
359
+ const key = typeof project.projectKey === 'string' && project.projectKey !== '' ? project.projectKey : null;
360
+ if (key === null || meta.has(key)) continue;
361
+ meta.set(key, {
362
+ name: typeof project.name === 'string' && project.name !== '' ? project.name : null,
363
+ shortPath: typeof project.shortPath === 'string' && project.shortPath !== '' ? project.shortPath : null,
364
+ unverified: project.unverified === true,
365
+ nodeCount: Number.isFinite(project.nodeCount) ? project.nodeCount : 0,
366
+ });
367
+ }
368
+ const groupOf = (groups, key) => {
369
+ if (!groups.has(key)) groups.set(key, { key, sessions: [], archived: [] });
370
+ return groups.get(key);
371
+ };
372
+
373
+ const archivedTasks = new Set();
374
+ const nodeProjects = new Map();
375
+ const walk = (node, parentArchived = false) => {
376
+ if (node === null || typeof node !== 'object') return;
377
+ const archived = parentArchived || node.displayArchived === true;
378
+ const chains = node.kind === 'plan' ? (node.executions ?? []) : (node.chain ? [node.chain] : []);
379
+ const taskIds = chains.flatMap((chain) => chain.taskIds ?? []);
380
+ if (node.kind === 'task' && taskIds.length === 0) taskIds.push(node.nodeId);
381
+ for (const id of [node.nodeId, ...taskIds]) {
382
+ if (typeof id === 'string' && typeof node.projectKey === 'string' && node.projectKey !== '') {
383
+ nodeProjects.set(id, node.projectKey);
384
+ }
385
+ }
386
+ if (archived) for (const taskId of taskIds) archivedTasks.add(taskId);
387
+ for (const child of Array.isArray(node.children) ? node.children : []) walk(child, archived);
388
+ };
389
+ for (const root of Array.isArray(tree?.roots) ? tree.roots : []) walk(root);
390
+ // A flat-only projection (the execution plane's `/plans list` shape) is read the
391
+ // same way: each entry names its own project key.
392
+ for (const node of Array.isArray(tree?.flatNodes) ? tree.flatNodes : []) {
393
+ if (node !== null && typeof node === 'object' && typeof node.nodeId === 'string'
394
+ && typeof node.projectKey === 'string' && node.projectKey !== '' && !nodeProjects.has(node.nodeId)) {
395
+ nodeProjects.set(node.nodeId, node.projectKey);
396
+ }
397
+ }
398
+
399
+ const active = new Map();
400
+ const archived = new Map();
401
+ for (const row of rows) {
402
+ if (row === null || typeof row !== 'object') continue;
403
+ const taskId = typeof row.taskId === 'string' ? row.taskId : '';
404
+ // ONLY the G07 flag counts as TaskBridge-archived. A record's own `archived`
405
+ // field means "recovered from durable history" — a live historical record, NOT an
406
+ // archive — so it must stay in the active list and remain openable.
407
+ const isArchived = taskId !== '' && (row.displayArchived === true || archivedTasks.has(taskId));
408
+ // The project of a row comes from the HOST's projection: a `/tasks` row carries
409
+ // no project key of its own, so its key is the one the tree node with the same
410
+ // identity has. A row the projection no longer contains (an evicted or
411
+ // history-only record) falls back to its own recorded source, which is a fact the
412
+ // record states — never a guess.
413
+ const key = projectKeyOfRow(row, nodeProjects);
414
+ const entry = {
415
+ taskId,
416
+ title: typeof row.title === 'string' && row.title !== '' ? row.title : '未记录标题',
417
+ sessionId: taskSessionId(row),
418
+ status: statusOf(row),
419
+ archived: isArchived,
420
+ };
421
+ groupOf(isArchived ? archived : active, key).sessions.push(entry);
422
+ }
423
+
424
+ // A project the host named is shown even when none of its nodes has executed yet,
425
+ // so "planned, nothing dispatched" and "no such project" read differently. The
426
+ // `unverified` bucket is NOT created here: it appears only when a record really has
427
+ // an unconfirmed source, so an empty "来源未确认" group is never invented.
428
+ for (const [key, info] of meta) {
429
+ if (info.nodeCount > 0 && key !== 'unverified') groupOf(active, key);
430
+ }
431
+
432
+ const order = (left, right) => {
433
+ const leftInfo = meta.get(left.key) ?? null;
434
+ const rightInfo = meta.get(right.key) ?? null;
435
+ const leftUnverified = left.key === 'unverified' || leftInfo?.unverified === true;
436
+ const rightUnverified = right.key === 'unverified' || rightInfo?.unverified === true;
437
+ if (leftUnverified !== rightUnverified) return leftUnverified ? 1 : -1;
438
+ const leftName = leftInfo?.name ?? projectLabel(left.key);
439
+ const rightName = rightInfo?.name ?? projectLabel(right.key);
440
+ if (leftName !== rightName) return leftName < rightName ? -1 : 1;
441
+ return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
442
+ };
443
+
444
+ const groups = [...active.values()].sort(order);
445
+ const archivedGroups = [...archived.values()].sort(order);
446
+ const activeCount = groups.reduce((total, group) => total + group.sessions.length, 0);
447
+ const archivedCount = archivedGroups.reduce((total, group) => total + group.sessions.length, 0);
448
+ return {
449
+ groups,
450
+ archivedGroups,
451
+ activeCount,
452
+ archivedCount,
453
+ /// Live rounds plus archived rows: everything the record holds.
454
+ total: rows.length,
455
+ available: tree !== null && (Array.isArray(tree.roots) || Array.isArray(tree.flatNodes)),
456
+ meta,
457
+ };
458
+ }
459
+
460
+ /**
461
+ * One record's project key, from the host's own statements.
462
+ *
463
+ * Order of evidence, strongest first:
464
+ * 1. the projection's key for the node with this row's identity (the host already
465
+ * resolved the project for it);
466
+ * 2. the row's own recorded digest, which is the key the projection uses for a
467
+ * verified source;
468
+ * 3. the row's own recorded path, for a legacy record without a digest;
469
+ * 4. `unverified` when the row recorded a source at all, else `unconfirmed`.
470
+ * A row is never attributed by title, position or a path guess; `unverified` and
471
+ * `unconfirmed` stay their own groups precisely so nothing is invented.
472
+ * @param {object} row - one `/tasks` row.
473
+ * @param {Map<string, string>} nodeProjects - projected node id → project key.
474
+ * @returns {string} project key.
475
+ */
476
+ function projectKeyOfRow(row, nodeProjects) {
477
+ const taskId = typeof row?.taskId === 'string' ? row.taskId : '';
478
+ if (taskId !== '' && nodeProjects instanceof Map) {
479
+ const projected = nodeProjects.get(taskId);
480
+ if (typeof projected === 'string' && projected !== '') return projected;
481
+ }
482
+ if (typeof row?.projectKey === 'string' && row.projectKey !== '') return row.projectKey;
483
+ const digest = typeof row?.sourcePathDigest === 'string' ? row.sourcePathDigest.trim() : '';
484
+ if (digest !== '') return digest;
485
+ const sourcePath = typeof row?.sourcePath === 'string' ? row.sourcePath.trim() : '';
486
+ if (sourcePath !== '') return `path:${sourcePath.replace(/[\\/]+$/u, '')}`;
487
+ return 'unconfirmed';
488
+ }
489
+
490
+ /**
491
+ * Where the archived rows came from, in operator words.
492
+ * @param {object} snapshot - page store snapshot.
493
+ * @returns {string | null} a short reason, or null when there is nothing to explain.
494
+ */
495
+ export function archivedSourceNote(snapshot) {
496
+ const total = navViewModel(snapshot).archivedCount;
497
+ if (total === 0) return null;
498
+ return snapshot?.tree !== null && snapshot?.tree !== undefined
499
+ ? '这些记录带 TaskBridge 的归档标记(displayArchived)。这里只是把它们单独列出,DSH 的归档状态没有改变。从历史恢复出来的记录不算归档,仍在上方的列表里。'
500
+ : '宿主没有返回任务树,已归档标记无法核实;这里只按记录自身的归档状态列出。';
501
+ }
502
+
503
+ /**
504
+ * The human-readable label of one project group, when the host did not name it.
505
+ * @param {string} key - host project key.
506
+ * @returns {string} label.
507
+ */
508
+ export function projectLabel(key) {
509
+ if (key === 'unverified') return '来源未确认的记录';
510
+ if (key === 'unconfirmed') return '没有项目信息的记录';
511
+ if (key.startsWith('path:')) {
512
+ const parts = key.slice(5).split(/[\\/]+/u).filter(Boolean);
513
+ return parts.slice(-2).join('/') || key;
514
+ }
515
+ if (key.startsWith('sha256:')) return `项目 ${key.slice(-6)}`;
516
+ return key.length <= 28 ? key : `${key.slice(0, 24)}…`;
517
+ }
518
+
519
+ /**
520
+ * A group's title: the host's own project name first, then the key itself.
521
+ * @param {object} group - one `navViewModel` group.
522
+ * @param {Map} meta - the view's project metadata.
523
+ * @returns {string} title.
524
+ */
525
+ export function groupTitle(group, meta) {
526
+ const info = meta instanceof Map ? meta.get(group.key) : null;
527
+ if (typeof info?.name === 'string' && info.name !== '') {
528
+ return info.shortPath !== null && info.shortPath !== undefined && info.shortPath !== info.name
529
+ ? `${info.name}(${info.shortPath})`
530
+ : info.name;
531
+ }
532
+ return projectLabel(group.key);
533
+ }
534
+
535
+ // ---------------------------------------------------------------------------
536
+ // Navigation through DSH's own Workspace service
537
+ // ---------------------------------------------------------------------------
538
+
539
+ /**
540
+ * Open one recorded session in DSH, if and only if the host can vouch for it.
541
+ *
542
+ * The order is deliberate: VERIFY, then call `openSession` EXACTLY ONCE. A plugin that
543
+ * opened first and apologised later could move the operator into another
544
+ * conversation, and a retry loop around `openSession` could open it twice.
545
+ *
546
+ * Every refusal is stated, and none of them is a navigation attempt:
547
+ * * no `uiWorkspace` → the host cannot navigate at all;
548
+ * * no recorded id → nothing to open;
549
+ * * snapshot not ready → "retry later", because nothing is verified yet;
550
+ * * id in `archivedSessionIds` → DSH archived it; only DSH can bring it back;
551
+ * * id absent from a ready snapshot → refused explicitly, not opened on faith;
552
+ * * no `workspaces` service → DSH cannot verify it, so it does not open it.
553
+ * @param {object | null} uiWorkspace - `ctx.get('uiWorkspace')`, or null.
554
+ * @param {string | null} sessionId - the host-recorded session id.
555
+ * @param {object | null} workspaces - the host `workspaces` service (its own source).
556
+ * @returns {Promise<{ ok: boolean, message: string }>} outcome with readable copy.
557
+ */
558
+ export async function locateSession(uiWorkspace, sessionId, workspaces = null) {
559
+ if (uiWorkspace === null || uiWorkspace === undefined || typeof uiWorkspace.openSession !== 'function') {
560
+ return { ok: false, message: '当前宿主没有提供会话定位能力(uiWorkspace),只显示记录,不跳转。' };
561
+ }
562
+ if (typeof sessionId !== 'string' || sessionId === '') {
563
+ return { ok: false, message: '这条记录没有可核实的会话标识,无法定位到原生会话。' };
564
+ }
565
+ const placement = sessionPlacement(sessionId, workspaces);
566
+ const short = shortSessionId(sessionId);
567
+ if (placement.state === 'pending') {
568
+ return { ok: false, message: 'DSH 的会话列表还没准备好,请稍后重试。' };
569
+ }
570
+ if (placement.state === 'archived') {
571
+ return { ok: false, message: `会话 ${short} 已在 DSH 中归档,请到 DSH 的归档里打开。` };
572
+ }
573
+ if (placement.state === 'missing') {
574
+ return { ok: false, message: `DSH 当前的会话列表里没有 ${short},不打开它。` };
575
+ }
576
+ if (placement.state === 'unknown') {
577
+ // No verification is possible on this host, so the plugin does not guess at an
578
+ // identity it cannot check. This is the documented degradation, stated plainly.
579
+ return { ok: false, message: '当前宿主没有提供会话列表(workspaces),无法核实这条记录,未跳转。' };
580
+ }
581
+ try {
582
+ const result = uiWorkspace.openSession(sessionId);
583
+ if (result !== null && typeof result?.then === 'function') await result;
584
+ } catch (error) {
585
+ const detail = typeof error?.message === 'string' && error.message !== '' ? error.message : '';
586
+ return { ok: false, message: `定位会话失败:${detail === '' ? '宿主没有接受这次定位' : detail.slice(0, 160)}` };
587
+ }
588
+ return { ok: true, message: `已在 DSH 中定位会话 ${short}。` };
589
+ }
590
+
591
+ // ---------------------------------------------------------------------------
592
+ // Components
593
+ // ---------------------------------------------------------------------------
594
+
595
+ /**
596
+ * Decorative icon rendered inside the host’s sidebar button.
597
+ *
598
+ * Decorative on purpose: the row in `sidebar.panellist` carries the label, so the
599
+ * icon is hidden from assistive technology rather than announcing the entry twice.
600
+ * @returns {object} an inline SVG.
601
+ */
602
+ export function TaskbridgeSidebarIcon({ size = 16 } = {}) {
603
+ return (
604
+ <svg
605
+ className="dshdg-nav-icon"
606
+ width={size}
607
+ height={size}
608
+ viewBox="0 0 16 16"
609
+ fill="none"
610
+ stroke="currentColor"
611
+ strokeWidth="1.4"
612
+ strokeLinecap="round"
613
+ strokeLinejoin="round"
614
+ aria-hidden="true"
615
+ focusable="false"
616
+ data-dshdg-nav-icon=""
617
+ >
618
+ <path d="M2.5 4.2h4.2l1.2 1.4h5.6v6.6a1 1 0 0 1-1 1H3.5a1 1 0 0 1-1-1z" />
619
+ <path d="M5.4 9.1l1.5 1.5 2.7-2.9" />
620
+ </svg>
621
+ );
622
+ }
623
+
624
+ /** One session row. */
625
+ function SessionRow({ entry, onLocate, locating }) {
626
+ const verified = typeof entry.sessionId === 'string' && entry.sessionId !== '';
627
+ return (
628
+ <li className="dshdg-nav-session" data-dshdg-nav-session={entry.taskId}>
629
+ <span className="dshdg-nav-session-title" title={entry.title}>{entry.title}</span>
630
+ <span className={`dshdg-badge dshdg-badge-${entry.status.tone}`}>{entry.status.label}</span>
631
+ <span className="dshdg-spacer" />
632
+ {verified ? (
633
+ <span className="dshdg-faint dshdg-mono" title={entry.sessionId}>{shortSessionId(entry.sessionId)}</span>
634
+ ) : (
635
+ <span className="dshdg-faint" data-dshdg-nav-unverified="">无原生会话标识</span>
636
+ )}
637
+ <button
638
+ type="button"
639
+ data-dshdg-nav-locate={entry.taskId}
640
+ disabled={!verified || locating}
641
+ title={verified ? '在 DSH 中打开这条记录对应的原生会话' : '这条历史记录没有记录会话标识,无法定位'}
642
+ onClick={() => { void onLocate(entry); }}
643
+ >
644
+ 定位
645
+ </button>
646
+ </li>
647
+ );
648
+ }
649
+
650
+ /** One project group, collapsible. */
651
+ function ProjectGroup({ group, meta, open, onToggle, onLocate, locating }) {
652
+ const key = group.key;
653
+ const title = groupTitle(group, meta);
654
+ const controlId = `dshdg-nav-body-${key}`;
655
+ const unverified = key === 'unverified';
656
+ return (
657
+ <li className="dshdg-nav-project" data-dshdg-nav-project={key}>
658
+ <div className="dshdg-nav-project-head">
659
+ <button
660
+ type="button"
661
+ className="dshdg-tree-toggle"
662
+ data-dshdg-nav-toggle={key}
663
+ aria-expanded={open}
664
+ aria-controls={controlId}
665
+ onClick={() => onToggle(key)}
666
+ >
667
+ {open ? '收起' : '展开'}
668
+ </button>
669
+ <span className="dshdg-nav-project-title" title={key}>{title}</span>
670
+ {unverified ? <span className="dshdg-badge dshdg-badge-warn">来源未确认</span> : null}
671
+ <span className="dshdg-spacer" />
672
+ <span className="dshdg-faint">{`${group.sessions.length} 个会话`}</span>
673
+ </div>
674
+ {open ? (
675
+ <ul id={controlId} className="dshdg-nav-sessions" role="group" aria-label={`${title} 的会话`}>
676
+ {group.sessions.map((entry) => (
677
+ <SessionRow key={entry.taskId} entry={entry} onLocate={onLocate} locating={locating} />
678
+ ))}
679
+ </ul>
680
+ ) : null}
681
+ </li>
682
+ );
683
+ }
684
+
685
+ /**
686
+ * The panel registered in `sidebar.panellist`.
687
+ *
688
+ * Its clock is the page store it is handed (`inject` face). Opening the panel does
689
+ * not read anything on its own beyond that store's own subscription; the explicit
690
+ * refresh button is the only thing here that asks the host for a list.
691
+ *
692
+ * A panel rendered without a store (a host that hands the slot no props) says so
693
+ * instead of throwing, so a slot-shape change can never take the shell down.
694
+ * @param {object} props - `store`, `uiWorkspace`, `workspaces`.
695
+ * @returns {object} the panel.
696
+ */
697
+ export function TaskbridgeNavPanel(props) {
698
+ const store = props?.store ?? null;
699
+ const uiWorkspace = props?.uiWorkspace ?? null;
700
+ const workspaces = props?.workspaces ?? null;
701
+ const [showArchived, setShowArchived] = useState(false);
702
+ const [collapsed, setCollapsed] = useState(() => new Set());
703
+ const [locating, setLocating] = useState(false);
704
+ const [feedback, setFeedback] = useState(null);
705
+ const requested = useRef(false);
706
+
707
+ const subscribe = useCallback(
708
+ (listener) => (typeof store?.subscribe === 'function' ? store.subscribe(listener) : () => {}),
709
+ [store],
710
+ );
711
+ // `useSyncExternalStore` requires getSnapshot to be REFERENTIALLY stable between
712
+ // renders while nothing changed: a new object per call re-renders forever. The page
713
+ // store returns its own state object (stable), so the identity is reused as-is; a
714
+ // store-less panel returns the module's frozen empty snapshot; anything else that
715
+ // hands back a fresh object is cached until its `revision` moves.
716
+ const stable = useRef({ raw: EMPTY_SNAPSHOT, value: EMPTY_SNAPSHOT, revision: null });
717
+ const getSnapshot = useCallback(() => {
718
+ const raw = store === null ? EMPTY_SNAPSHOT : (typeof store?.getSnapshot === 'function' ? store.getSnapshot() : EMPTY_SNAPSHOT);
719
+ const cache = stable.current;
720
+ if (raw === cache.raw) return cache.value;
721
+ // A store that already hands out stable objects (the page store does) is used
722
+ // directly; a `revision` counter, when present, is the store's own promise that
723
+ // an unchanged number means unchanged data.
724
+ const revision = typeof raw?.revision === 'number' ? raw.revision : null;
725
+ if (revision !== null && revision === cache.revision && cache.raw !== EMPTY_SNAPSHOT) {
726
+ cache.raw = raw;
727
+ return cache.value;
728
+ }
729
+ cache.raw = raw;
730
+ cache.value = raw;
731
+ cache.revision = revision;
732
+ return raw;
733
+ }, [store]);
734
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
735
+
736
+ // The initial read happens in an EFFECT, never during render: writing to the store
737
+ // while rendering would be a side effect on another component's state. It runs at
738
+ // most once per panel instance, and only when the shared store holds no records yet
739
+ // (the settings page, or a G07 refresh, may already have read them).
740
+ useEffect(() => {
741
+ if (requested.current) return;
742
+ if (store === null || typeof store.loadTasks !== 'function') return;
743
+ const loaded = Array.isArray(snapshot.tasks) && snapshot.tasks.length > 0;
744
+ if (loaded) {
745
+ requested.current = true;
746
+ return;
747
+ }
748
+ requested.current = true;
749
+ void Promise.resolve(store.loadTasks()).catch(() => {});
750
+ // `snapshot.tasks` is read once at mount on purpose; later refreshes are explicit.
751
+ // eslint-disable-next-line react-hooks/exhaustive-deps
752
+ }, [store]);
753
+
754
+ const view = useMemo(() => navViewModel(snapshot), [snapshot]);
755
+ const archivedNote = useMemo(() => archivedSourceNote(snapshot), [snapshot]);
756
+ // Records exist but none of them is live: the empty line below must not claim the
757
+ // host has no records at all.
758
+ const liveEmpty = view.activeCount === 0 && view.archivedCount > 0;
759
+ const onToggle = useCallback((key) => {
760
+ setCollapsed((previous) => {
761
+ const next = new Set(previous);
762
+ if (next.has(key)) next.delete(key);
763
+ else next.add(key);
764
+ return next;
765
+ });
766
+ }, []);
767
+ const onLocate = useCallback(async (entry) => {
768
+ setLocating(true);
769
+ try {
770
+ // Resolved here, not at render: the host services may mount after the panel.
771
+ const outcome = await locateSession(resolveService(uiWorkspace), entry.sessionId, resolveService(workspaces));
772
+ setFeedback({ ok: outcome.ok, message: outcome.message });
773
+ } finally {
774
+ setLocating(false);
775
+ }
776
+ }, [uiWorkspace, workspaces]);
777
+ const onRefresh = useCallback(() => { void Promise.resolve(store?.loadTasks?.()).catch(() => {}); }, [store]);
778
+
779
+ return (
780
+ <section className="dshdg-nav" aria-labelledby="dshdg-nav-title" data-dshdg-nav-panel="">
781
+ <div className="dshdg-nav-head">
782
+ <h3 id="dshdg-nav-title">{TASKS_NAV_LABEL}</h3>
783
+ <span className="dshdg-spacer" />
784
+ <button type="button" data-dshdg-nav-refresh="" onClick={onRefresh}>刷新</button>
785
+ </div>
786
+ <p className="dshdg-faint dshdg-nav-note">
787
+ {`按项目列出 TaskBridge 的逻辑任务与它们的原生会话(${view.activeCount} 个会话${view.archivedCount > 0 ? `,另有 ${view.archivedCount} 条已归档` : ''})。这里只读 TaskBridge 记录,不改名、不移动、不归档 DSH 会话。`}
788
+ </p>
789
+ {snapshot.tasksError !== null && snapshot.tasksError !== undefined ? (
790
+ <p className="dshdg-warn" data-dshdg-nav-error="">任务记录这次没有读到;下方显示的是已有的内容。</p>
791
+ ) : null}
792
+ {view.total === 0 ? (
793
+ <p className="dshdg-faint" data-dshdg-nav-empty="">还没有执行记录。</p>
794
+ ) : (
795
+ <ul className="dshdg-nav-projects">
796
+ {liveEmpty ? (
797
+ <li className="dshdg-faint" data-dshdg-nav-all-archived="">没有进行中的记录;已归档的记录在下方。</li>
798
+ ) : null}
799
+ {view.groups.map((group) => (
800
+ <ProjectGroup
801
+ key={group.key}
802
+ group={group}
803
+ meta={view.meta}
804
+ open={!collapsed.has(group.key)}
805
+ onToggle={onToggle}
806
+ onLocate={onLocate}
807
+ locating={locating}
808
+ />
809
+ ))}
810
+ </ul>
811
+ )}
812
+ {view.archivedCount > 0 ? (
813
+ <div className="dshdg-nav-archived">
814
+ <label className="dshdg-nav-toggle-row">
815
+ <input
816
+ type="checkbox"
817
+ data-dshdg-nav-archived-toggle=""
818
+ checked={showArchived}
819
+ onChange={(event) => setShowArchived(event.target.checked)}
820
+ />
821
+ <span>{`显示 TaskBridge 已归档的记录(${view.archivedCount})`}</span>
822
+ </label>
823
+ <p className="dshdg-faint">{archivedNote}</p>
824
+ {showArchived ? (
825
+ <ul className="dshdg-nav-projects">
826
+ {view.archivedGroups.map((group) => (
827
+ <li className="dshdg-nav-project" key={group.key} data-dshdg-nav-archived-project={group.key}>
828
+ <div className="dshdg-nav-project-head">
829
+ <span className="dshdg-nav-project-title" title={group.key}>{groupTitle(group, view.meta)}</span>
830
+ <span className="dshdg-faint">{`${group.sessions.length} 条已归档`}</span>
831
+ </div>
832
+ <ul className="dshdg-nav-sessions">
833
+ {group.sessions.map((entry) => (
834
+ <li className="dshdg-nav-session" key={entry.taskId} data-dshdg-nav-archived-session={entry.taskId}>
835
+ <span className="dshdg-nav-session-title" title={entry.title}>{entry.title}</span>
836
+ <span className={`dshdg-badge dshdg-badge-${entry.status.tone}`}>{entry.status.label}</span>
837
+ <span className="dshdg-faint">已归档</span>
838
+ </li>
839
+ ))}
840
+ </ul>
841
+ </li>
842
+ ))}
843
+ </ul>
844
+ ) : null}
845
+ </div>
846
+ ) : null}
847
+ {feedback === null ? null : (
848
+ <p
849
+ className={feedback.ok ? 'dshdg-hint' : 'dshdg-warn'}
850
+ role="status"
851
+ aria-live="polite"
852
+ data-dshdg-nav-feedback={feedback.ok ? 'ok' : 'refused'}
853
+ >
854
+ {feedback.message}
855
+ </p>
856
+ )}
857
+ </section>
858
+ );
859
+ }
860
+
861
+ /** Stable empty snapshot, so a store-less panel never allocates per render. */
862
+ const EMPTY_SNAPSHOT = Object.freeze({ tasks: [], tree: null, tasksError: null });