dsh-taskbridge 1.5.4 → 1.7.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 (74) hide show
  1. package/CHANGELOG.md +80 -59
  2. package/README.md +51 -50
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/bin/dsh-delegate-mcp.d.ts +1 -0
  5. package/bin/dsh-delegate-mcp.js +1 -0
  6. package/codex/dsh-taskbridge.toml +148 -71
  7. package/docs/INTRODUCTION.md +44 -22
  8. package/docs/INTRODUCTION.zh.md +32 -26
  9. package/docs/codex-integration.md +99 -19
  10. package/docs/contracts-stage-b.md +4 -4
  11. package/docs/conversation-placement.md +25 -7
  12. package/docs/plugin-market.md +1 -1
  13. package/docs/releases/1.6.0.zh.md +11 -0
  14. package/docs/releases/1.7.0.zh.md +11 -0
  15. package/docs/runtime-compatibility.md +10 -11
  16. package/docs/silent-wait.md +69 -31
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +11 -21
  19. package/docs/workspace-grouping.md +126 -0
  20. package/lib/client.d.ts +581 -0
  21. package/lib/client.js +332 -3461
  22. package/locale/en.json +1 -1
  23. package/locale/zh.json +1 -1
  24. package/package.json +7 -19
  25. package/src/client/api.js +895 -90
  26. package/src/client/index.jsx +1363 -296
  27. package/src/client/sidebar.jsx +862 -0
  28. package/src/client/styles.js +340 -0
  29. package/src/client/task-cleanup.js +304 -0
  30. package/src/client/task-records-table.jsx +217 -0
  31. package/src/client/task-view.js +307 -0
  32. package/src/client/workspace-groups.js +482 -0
  33. package/src/client/workspaces-browser.jsx +770 -0
  34. package/src/codex/agent-ownership.js +270 -0
  35. package/src/codex/installer.js +528 -35
  36. package/src/codex/seam.js +5 -0
  37. package/src/config/defaults.js +63 -17
  38. package/src/config/settings.js +60 -62
  39. package/src/config/validate.js +126 -71
  40. package/src/http/execution-plane.js +200 -1
  41. package/src/http/respond.js +26 -2
  42. package/src/http/user-plane.js +566 -2
  43. package/src/index.d.ts +55 -0
  44. package/src/index.js +58 -42
  45. package/src/jobs/activity.js +968 -78
  46. package/src/jobs/engine.js +1010 -230
  47. package/src/jobs/history.js +224 -12
  48. package/src/jobs/plan-store.js +1020 -0
  49. package/src/jobs/record-cleanup.js +196 -0
  50. package/src/jobs/task-display.js +73 -0
  51. package/src/jobs/task-tree.js +786 -0
  52. package/src/jobs/title.js +129 -12
  53. package/src/mcp/server.js +206 -10
  54. package/src/mcp/wait.js +64 -5
  55. package/src/runtime/agent-runner.js +101 -15
  56. package/src/runtime/worker-prompt.js +53 -0
  57. package/src/workspace/locks.js +288 -167
  58. package/docs/assets/taskbridge-workflow.en.png +0 -0
  59. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  60. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  61. package/docs/releases/1.4.0.zh.md +0 -54
  62. package/docs/releases/1.4.1.zh.md +0 -59
  63. package/docs/releases/1.4.2.zh.md +0 -23
  64. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  65. package/docs/releases/1.5.0.zh.md +0 -51
  66. package/docs/releases/1.5.1.zh.md +0 -70
  67. package/docs/releases/1.5.2.zh.md +0 -30
  68. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  69. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  70. package/docs/releases/1.5.3.zh.md +0 -33
  71. package/docs/releases/1.5.4.zh.md +0 -25
  72. package/src/review/preset.js +0 -868
  73. package/src/review/prompts.js +0 -145
  74. package/src/review/reviewer.js +0 -933
package/src/client/api.js CHANGED
@@ -26,6 +26,38 @@
26
26
  // verbatim. The few checks below exist to keep the operator from submitting an
27
27
  // obviously broken form, and every one of them is re-checked server-side.
28
28
 
29
+ // Task-record cleanup helpers. The page draws the checkbox state from these and the
30
+ // store builds its request with them, so both sides share ONE projection. They are
31
+ // re-exported rather than imported so this module keeps exactly one import list; the
32
+ // store receives the same functions through `options.cleanup` (defaulted by
33
+ // `createStore`'s caller in `index.jsx` to `cleanupProjection()`).
34
+ export {
35
+ CLEANUP_BLOCKER_LABELS,
36
+ MAX_CLEANUP_CHAINS,
37
+ cleanupBlockerLabel,
38
+ cleanupCandidates,
39
+ cleanupOutcome,
40
+ cleanupProjection,
41
+ cleanupRequest,
42
+ cleanupSelectionKey,
43
+ cleanupSelectionSummary,
44
+ cleanupWarningText,
45
+ describeCleanupOutcome,
46
+ pruneCleanupSelection,
47
+ toggleCleanupSelection,
48
+ withSelectionState,
49
+ } from './task-cleanup.js';
50
+
51
+ /** @returns {object} the projection an unconfigured store uses: nothing removable. */
52
+ function emptyCleanupProjection() {
53
+ return {
54
+ candidates: () => [],
55
+ request: () => ({ body: { chains: [] }, problems: ['当前宿主未提供记录清理能力。'] }),
56
+ outcome: () => ({ chains: 0, rounds: 0, deletedTaskIds: [] }),
57
+ describe: () => '',
58
+ };
59
+ }
60
+
29
61
  /** User-plane prefix. Mirrors `USER_PLANE_PREFIX` in `src/http/user-plane.js`. */
30
62
  export const USER_PLANE_PREFIX = '/api/dsh-delegate';
31
63
 
@@ -46,6 +78,11 @@ export const ROUTES = Object.freeze({
46
78
  // One narrow, authenticated operator route for the two silence thresholds. It is
47
79
  // a browser-plane write only: the MCP surface never gains a settings write.
48
80
  monitoring: `${USER_PLANE_PREFIX}/monitoring`,
81
+ // One narrow, authenticated operator route for the operator's execution choices —
82
+ // today, whether a NEW task gets Agent Teams when its dispatcher states no choice.
83
+ // Browser-plane only: the MCP surface never gains a settings write, and this route
84
+ // cannot touch DSH's global agent-teams switch.
85
+ execution: `${USER_PLANE_PREFIX}/execution`,
49
86
  catalog: `${USER_PLANE_PREFIX}/catalog`,
50
87
  connections: `${USER_PLANE_PREFIX}/connections`,
51
88
  connectionsRevoke: `${USER_PLANE_PREFIX}/connections/revoke`,
@@ -55,6 +92,18 @@ export const ROUTES = Object.freeze({
55
92
  tasks: `${USER_PLANE_PREFIX}/tasks`,
56
93
  tasksGet: `${USER_PLANE_PREFIX}/tasks/get`,
57
94
  tasksCancel: `${USER_PLANE_PREFIX}/tasks/cancel`,
95
+ // One explicit action: remove the durable records of the selected finished
96
+ // execution chains. It is a `POST`, never a load-time or refresh-time write, and it
97
+ // only ever names chains and their exact rounds.
98
+ tasksCleanup: `${USER_PLANE_PREFIX}/tasks/cleanup`,
99
+ // The one planning write the page has: a batch of planning nodes. It creates
100
+ // records only — it cannot dispatch, authorize or review anything.
101
+ plans: `${USER_PLANE_PREFIX}/plans`,
102
+ displayArchive: `${USER_PLANE_PREFIX}/tasks/display-archive`,
103
+ // The durable task → Workspace/Session identity map, narrowed to identity fields.
104
+ // The grouped sidebar reads it to know which real DSH sessions this plugin created;
105
+ // it is a read of the operator plane and never a task action.
106
+ sessionMap: `${USER_PLANE_PREFIX}/session-map`,
58
107
  models: `${USER_PLANE_PREFIX}/models`,
59
108
  credentialsStatus: `${USER_PLANE_PREFIX}/credentials/status`,
60
109
  credentialsSet: `${USER_PLANE_PREFIX}/credentials/set`,
@@ -177,18 +226,31 @@ export function createApi(options = {}) {
177
226
  return await request('POST', ROUTES.settings, { settings });
178
227
  },
179
228
  /**
180
- * Replace only the two silence thresholds.
229
+ * Replace the monitoring block (both no-progress thresholds and the repeated-failure
230
+ * count).
181
231
  *
182
- * This is the narrow route the advanced monitoring controls use, so a operator
183
- * adjusting a timer cannot accidentally rewrite a provider list. The host
184
- * re-validates: whole seconds, each in range, and the attention threshold strictly
185
- * greater than the self-check one.
186
- * @param {{ selfCheckSeconds: number, attentionSeconds: number }} monitoring - thresholds in seconds.
232
+ * This is the narrow route a legacy caller uses, so an operator adjusting a timer
233
+ * cannot accidentally rewrite a provider list. The host re-validates: whole seconds,
234
+ * each in range (`0` = off), and — only when both are enabled — the run progress check
235
+ * strictly after the self-check.
236
+ * @param {{ selfCheckSeconds: number, attentionSeconds: number, repeatFailureThreshold: number }} monitoring - thresholds in seconds.
187
237
  * @returns {Promise<object>} `{ monitoring, settings }`.
188
238
  */
189
239
  async putMonitoring(monitoring) {
190
240
  return await request('POST', ROUTES.monitoring, { monitoring });
191
241
  },
242
+ /**
243
+ * Replace the operator's execution-choice block — today, the Agent Teams default a
244
+ * NEW task gets when its dispatcher states no per-task choice.
245
+ *
246
+ * The host re-validates: the value must be a real boolean, and an absent block means
247
+ * the documented OFF default. This cannot reach DSH's global agent-teams switch.
248
+ * @param {{ agentTeamsDefault: boolean }} execution - the block as the operator set it.
249
+ * @returns {Promise<object>} `{ execution, settings }`.
250
+ */
251
+ async putExecution(execution) {
252
+ return await request('POST', ROUTES.execution, { execution });
253
+ },
192
254
  /**
193
255
  * Resolve provider models/efforts plus the composed effective config.
194
256
  * @param {object} [body] - `{ projectPath }`.
@@ -262,6 +324,17 @@ export function createApi(options = {}) {
262
324
  async getTask(taskId) {
263
325
  return await request('POST', ROUTES.tasksGet, { taskId });
264
326
  },
327
+ /**
328
+ * Read the durable task → Workspace/Session identity map.
329
+ *
330
+ * Identity only: paths, digests, Workspace, Session, isolation. It is what lets the
331
+ * grouped sidebar attribute a real session to this plugin after its task records
332
+ * were cleaned or hidden, without guessing from a title or a directory.
333
+ * @returns {Promise<object>} `{ sessions }`.
334
+ */
335
+ async getSessionMap() {
336
+ return await request('GET', ROUTES.sessionMap);
337
+ },
265
338
  /**
266
339
  * Cancel a task as the operator.
267
340
  * @param {string} taskId - task identity.
@@ -270,6 +343,36 @@ export function createApi(options = {}) {
270
343
  async cancelTask(taskId) {
271
344
  return await request('POST', ROUTES.tasksCancel, { taskId });
272
345
  },
346
+ /**
347
+ * Remove the durable records of finished execution chains (operator-confirmed).
348
+ *
349
+ * The body is exactly `{ confirm: true, chains: [{ chainId, taskIds }] }`: the
350
+ * chains the operator ticked and the exact rounds the page displayed. The host
351
+ * re-checks every one of them against the unfiltered current records and refuses
352
+ * the whole batch when any is unknown, changed or still depended on, so a refusal
353
+ * means nothing was removed.
354
+ * @param {{ chains: Array<{ chainId: string, taskIds: string[] }> }} body - selected chains.
355
+ * @returns {Promise<object>} `{ chains, tasks, deletedTaskIds, remaining, retained }`.
356
+ */
357
+ async cleanupTasks(body) {
358
+ const chains = Array.isArray(body?.chains) ? body.chains : [];
359
+ return await request('POST', ROUTES.tasksCleanup, { confirm: true, chains });
360
+ },
361
+ /**
362
+ * Create a batch of planning nodes.
363
+ *
364
+ * The body is exactly `{ workspacePath?, parentNodeId?, nodes: [...] }`. It
365
+ * deliberately names no connection: the host always writes for the fixed local
366
+ * caller, and a body that tried to name one is refused rather than ignored.
367
+ * @param {object} body - `{ workspacePath?, parentNodeId?, nodes }`.
368
+ * @returns {Promise<object>} `{ nodes, executed: false, switch }`.
369
+ */
370
+ async createPlans(body) {
371
+ return await request('POST', ROUTES.plans, body);
372
+ },
373
+ async setDisplayArchive(nodeId, archived) {
374
+ return await request('POST', ROUTES.displayArchive, { nodeId, archived });
375
+ },
273
376
  /**
274
377
  * Discover one provider's model list from its own API (remote discovery).
275
378
  *
@@ -455,7 +558,8 @@ export function monitoringOf(source) {
455
558
  * at all, and an absent key is not an operator error — it is the documented default. So
456
559
  * `undefined` becomes the default value (making the field editable for an older document),
457
560
  * while an explicit `''`, `null`, fractional or out-of-range value is preserved exactly so
458
- * the precheck still refuses it.
561
+ * the precheck still refuses it. A stored `0` is a DECISION ("off") and is preserved as
562
+ * `0`, never re-defaulted.
459
563
  * @param {object | null} source - draft or served document.
460
564
  * @returns {object} the block as stored, or the defaults when there is none.
461
565
  */
@@ -555,7 +659,7 @@ export const TASK_PHASE_LABELS = Object.freeze({
555
659
  // A question is a DIFFERENT wait from an approval: answering it grants nothing, so the
556
660
  // label must not read as an authorization either.
557
661
  'awaiting-question': '等待回答问题',
558
- review: '附加审查中',
662
+ review: '旧版模型复审',
559
663
  'awaiting-host-review': '等待宿主审查',
560
664
  failed: '已失败',
561
665
  cancelled: '已取消',
@@ -584,10 +688,8 @@ export const TASK_STATE_LABELS = Object.freeze({
584
688
  interrupted: '已中断(进程重启后不会继续执行)',
585
689
  });
586
690
 
587
- /** Chinese labels for task review states. */
691
+ /** Chinese labels for historical model review states. */
588
692
  export const REVIEW_STATE_LABELS = Object.freeze({
589
- disabled: '未启用附加审查',
590
- not_run: '未运行',
591
693
  completed: '已完成',
592
694
  failed: '审查失败(与任务成败无关)',
593
695
  });
@@ -609,6 +711,8 @@ export const CONNECTIVITY_LAYERS = Object.freeze([
609
711
 
610
712
  /** Bounds mirrored from the host validator, used for input attributes only. */
611
713
  export const LIMITS = Object.freeze({
714
+ // LEGACY: no longer offered as a control and no longer bounds an ordinary run. It
715
+ // survives only so an older stored value (or an older client) still round-trips.
612
716
  timeoutSecondsMin: 30,
613
717
  timeoutSecondsMax: 7200,
614
718
  maxParallelismMin: 1,
@@ -618,11 +722,12 @@ export const LIMITS = Object.freeze({
618
722
  sessionGrantTtlSecondsMin: 60,
619
723
  sessionGrantTtlSecondsMax: 43200,
620
724
  providers: 32,
621
- // Silence thresholds. Mirrors `LIMITS` in `src/config/defaults.js`; the host is
725
+ // No-progress thresholds. Mirrors `LIMITS` in `src/config/defaults.js`; the host is
622
726
  // still the authority, these only drive input attributes and the local precheck.
623
- selfCheckSecondsMin: 30,
727
+ // `0` is legal for either and means "this reminder is off".
728
+ selfCheckSecondsMin: 0,
624
729
  selfCheckSecondsMax: 3600,
625
- attentionSecondsMin: 31,
730
+ attentionSecondsMin: 0,
626
731
  attentionSecondsMax: 7200,
627
732
  // Repeated-failure reminder: a COUNT of consecutive identical failures, 0 = off.
628
733
  repeatFailureThresholdMin: 0,
@@ -630,18 +735,66 @@ export const LIMITS = Object.freeze({
630
735
  });
631
736
 
632
737
  /**
633
- * Default silence thresholds and failure count, mirroring `MONITORING_DEFAULTS`.
738
+ * Default monitoring thresholds and failure count, mirroring `MONITORING_DEFAULTS`.
634
739
  *
635
- * Stored as whole SECONDS (300 / 600). The panel presents them as minutes because
636
- * that is how an operator thinks about them; a value that is not a whole number of
637
- * minutes is still editable and is shown exactly.
740
+ * Stored as whole SECONDS: 10 minutes for the read-only self-check, 40 minutes for the
741
+ * run progress check, and the repeated-failure count. Both durations are measured on
742
+ * the SAME clock — consecutive time without real progress — and each can be switched off
743
+ * with `0`. The panel presents them as minutes because that is how an operator thinks
744
+ * about them; a value that is not a whole number of minutes is still editable and is
745
+ * shown exactly.
638
746
  */
639
747
  export const MONITORING_DEFAULTS = Object.freeze({
640
- selfCheckSeconds: 300,
641
- attentionSeconds: 600,
748
+ selfCheckSeconds: 600,
749
+ attentionSeconds: 2400,
642
750
  repeatFailureThreshold: 3,
643
751
  });
644
752
 
753
+ /**
754
+ * The operator's default for a NEW task's Agent Teams choice, mirroring
755
+ * `DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS`.
756
+ *
757
+ * OFF, so an upgrade or a fresh install never starts collaborating by itself. The host
758
+ * is still the authority; this only fills a draft a host has not answered for yet.
759
+ */
760
+ export const AGENT_TEAMS_DEFAULT_FOR_NEW_TASKS = false;
761
+
762
+ /**
763
+ * Where a task's frozen Agent Teams decision came from.
764
+ *
765
+ * Kept apart from the decision itself: "you asked for this", "this follow-up continues
766
+ * a chain that had it" and "the TaskBridge default applied it" are three different
767
+ * stories, and a record that showed the third as the first would misattribute a choice
768
+ * nobody made.
769
+ */
770
+ export const AGENT_TEAMS_ORIGIN_LABELS = Object.freeze({
771
+ request: '本次派工明确指定',
772
+ continuation: '沿用所续接任务的协作选择',
773
+ 'settings-default': '按 TaskBridge 的「新任务默认」',
774
+ });
775
+
776
+ /**
777
+ * The execution block a draft carries, normalized.
778
+ *
779
+ * A document written before this block existed, and a host that never served one, both
780
+ * open at the OFF default — never "on" and never a blank control. A stored value that is
781
+ * not a real boolean is passed through unchanged so the precheck can refuse it instead of
782
+ * the page quietly showing "off" for something the host would reject.
783
+ * @param {object | null} source - served document, draft, or raw block.
784
+ * @returns {{ agentTeamsDefault: boolean | unknown }} normalized block.
785
+ */
786
+ export function executionOf(source) {
787
+ const block = source?.execution;
788
+ if (block === null || typeof block !== 'object' || Array.isArray(block)) {
789
+ return { agentTeamsDefault: AGENT_TEAMS_DEFAULT_FOR_NEW_TASKS };
790
+ }
791
+ return {
792
+ agentTeamsDefault: block.agentTeamsDefault === undefined
793
+ ? AGENT_TEAMS_DEFAULT_FOR_NEW_TASKS
794
+ : block.agentTeamsDefault,
795
+ };
796
+ }
797
+
645
798
  /** Chinese labels for the self-check verdicts the host publishes. */
646
799
  export const SELF_CHECK_LABELS = Object.freeze({
647
800
  'executor-alive-silent': '执行器健在,这段时间没有新输出',
@@ -679,7 +832,7 @@ export function repeatFailureLine(activity) {
679
832
  /** Chinese labels for the reasons a wait returns. */
680
833
  export const WAIT_REASON_LABELS = Object.freeze({
681
834
  heartbeat: '没有需要处理的事(内部心跳)',
682
- attention: '长时间没有任何新进展,需要你判断',
835
+ attention: '任务需要你看一下进展(只是提醒,任务仍在运行)',
683
836
  permission: '有一次工具调用在等待授权决定',
684
837
  ready: '执行已结束,等待宿主审查(不等于已接受)',
685
838
  failed: '执行失败',
@@ -825,12 +978,14 @@ export function defaultDraft() {
825
978
  maxParallelism: 1,
826
979
  isolation: 'worktree',
827
980
  },
828
- review: { enabled: false, providerId: null, model: null, reasoningEffort: null },
829
981
  authorization: { taskGrantTtlSeconds: 900, sessionGrantTtlSeconds: 14400 },
830
982
  // Silence thresholds. Present in a fresh draft so the controls render without a
831
983
  // second load, and normalized from the served document below so an older host
832
984
  // (or an older stored file) still opens with the documented defaults.
833
985
  monitoring: { ...MONITORING_DEFAULTS },
986
+ // The operator's default for NEW tasks only: OFF, so a fresh install and an upgrade
987
+ // both start without agent collaboration. It never opens DSH's global switch.
988
+ execution: { agentTeamsDefault: AGENT_TEAMS_DEFAULT_FOR_NEW_TASKS },
834
989
  projectOverrides: {},
835
990
  presets: [],
836
991
  // Deprecated and inert, kept only so a save round-trips the stored document
@@ -871,20 +1026,24 @@ export function draftFromSettings(document) {
871
1026
  }))
872
1027
  : [],
873
1028
  worker: { ...base.worker, ...(source.worker ?? {}) },
874
- review: { ...base.review, ...(source.review ?? {}) },
875
1029
  authorization: { ...base.authorization, ...(source.authorization ?? {}) },
876
1030
  // A document written before this block existed has no `monitoring` key at all,
877
1031
  // and a host that predates it never serves one. Both open with the documented
878
1032
  // defaults instead of a blank control, and the values are coerced to whole
879
1033
  // seconds because that is the only shape the host accepts.
880
1034
  monitoring: monitoringOf(source),
881
- projectOverrides: clone(source.projectOverrides ?? {}),
1035
+ // The same rule for the operator's new-task default: a document (or a host) that
1036
+ // predates the block opens at the documented OFF default, so an upgraded
1037
+ // installation never presents agent collaboration as already decided on.
1038
+ execution: executionOf(source),
1039
+ projectOverrides: Object.fromEntries(Object.entries(source.projectOverrides ?? {})
1040
+ .filter(([, block]) => block?.review === undefined || block.worker !== undefined)
1041
+ .map(([path, block]) => [path, block?.worker === undefined ? {} : { worker: clone(block.worker) }])),
882
1042
  presets: Array.isArray(source.presets)
883
- ? source.presets.map((preset) => ({
1043
+ ? source.presets.filter((preset) => preset.worker != null).map((preset) => ({
884
1044
  id: String(preset.id ?? ''),
885
1045
  name: String(preset.name ?? preset.id ?? ''),
886
- worker: preset.worker === null || preset.worker === undefined ? null : { ...preset.worker },
887
- review: preset.review === null || preset.review === undefined ? null : { ...preset.review },
1046
+ worker: { ...preset.worker },
888
1047
  }))
889
1048
  : [],
890
1049
  // Read back through the same resolver the save path uses, so a document written
@@ -920,17 +1079,18 @@ export function documentFromDraft(draft) {
920
1079
  };
921
1080
  }),
922
1081
  worker: { ...source.worker },
923
- review: { ...source.review },
924
1082
  authorization: { ...source.authorization },
925
1083
  // Sent on every save, normalized to whole seconds: the host refuses anything
926
1084
  // else, and a document that omitted the block would store the defaults.
927
1085
  monitoring: monitoringOf(source),
1086
+ // Sent on every save so the round-trip is faithful. The value is a plain boolean and
1087
+ // a missing one is written as the documented OFF default, exactly as the host would.
1088
+ execution: executionOf(source),
928
1089
  projectOverrides: clone(source.projectOverrides ?? {}),
929
1090
  presets: (source.presets ?? []).map((preset) => ({
930
1091
  id: preset.id,
931
1092
  name: preset.name,
932
- ...(preset.worker === null ? {} : { worker: { ...preset.worker } }),
933
- ...(preset.review === null ? {} : { review: { ...preset.review } }),
1093
+ worker: { ...preset.worker },
934
1094
  })),
935
1095
  // Sent on every save only so the round-trip is faithful. It is inert: the host
936
1096
  // validates it as a retired value and no run consults it.
@@ -959,12 +1119,11 @@ export function exportDocument(draft) {
959
1119
  * immutable snapshot a running job took.
960
1120
  * @param {object} draft - editable document.
961
1121
  * @param {string | null} [projectPath] - optional project layer.
962
- * @returns {{ worker: object, review: object, applied: string[] }} preview.
1122
+ * @returns {{ worker: object, monitoring: object, applied: string[] }} preview.
963
1123
  */
964
1124
  export function previewEffective(draft, projectPath = null) {
965
1125
  const applied = [];
966
1126
  let worker = { ...(draft?.worker ?? {}) };
967
- let review = { ...(draft?.review ?? {}) };
968
1127
  const overrides = draft?.projectOverrides ?? {};
969
1128
  if (typeof projectPath === 'string' && projectPath.trim() !== '') {
970
1129
  const wanted = projectPath.trim().replace(/[\\/]+$/, '');
@@ -977,16 +1136,17 @@ export function previewEffective(draft, projectPath = null) {
977
1136
  worker = { ...worker, ...block.worker };
978
1137
  applied.push('项目覆盖:执行设置');
979
1138
  }
980
- if (block.review !== undefined && block.review !== null) {
981
- review = { ...review, ...block.review };
982
- applied.push('项目覆盖:附加审查');
983
- }
984
1139
  }
985
1140
  }
986
- if (review.enabled !== true) review = { enabled: false, providerId: null, model: null, reasoningEffort: null };
987
1141
  return {
988
- worker: { ...worker, providerRoute: worker.providerId ?? null },
989
- review: { ...review, providerRoute: review.providerId ?? null },
1142
+ // `executionTimeoutSeconds` mirrors the host: `null` is the documented state "no
1143
+ // total execution deadline", and the legacy stored value is carried separately so
1144
+ // the preview never presents it as a budget the run gets.
1145
+ worker: {
1146
+ ...worker,
1147
+ providerRoute: worker.providerId ?? null,
1148
+ executionTimeoutSeconds: null,
1149
+ },
990
1150
  // Global-only, like the host's own snapshot: no project or per-job layer can
991
1151
  // retime a task, so the preview reports the same pair the task would freeze.
992
1152
  monitoring: monitoringOf(draft),
@@ -1041,29 +1201,27 @@ export function precheckDraft(draft) {
1041
1201
  modelIds.add(model.id);
1042
1202
  }
1043
1203
  }
1044
- for (const [role, block] of [['执行设置', draft?.worker], ['附加审查', draft?.review]]) {
1045
- if (role === '附加审查' && block?.enabled !== true) continue;
1046
- if (block?.providerId === null || block?.providerId === undefined) {
1047
- if (role === '执行设置' && providers.length > 0) problems.push('执行设置尚未选择提供方');
1048
- continue;
1049
- }
1050
- const provider = providers.find((entry) => entry.id === block.providerId);
1204
+ const worker = draft?.worker;
1205
+ if (worker?.providerId == null) {
1206
+ if (providers.length > 0) problems.push('执行设置尚未选择提供方');
1207
+ } else {
1208
+ const provider = providers.find((entry) => entry.id === worker.providerId);
1051
1209
  if (provider === undefined) {
1052
- problems.push(`${role}选择了未配置的提供方「${block.providerId}」`);
1053
- continue;
1054
- }
1055
- const model = (provider.models ?? []).find((entry) => entry.id === block.model);
1056
- if (model === undefined) {
1057
- problems.push(`${role}的模型「${block.model ?? '(空)'}」不在提供方「${provider.id}」的模型列表中`);
1058
- } else if (block.reasoningEffort !== null && block.reasoningEffort !== undefined
1059
- && !(model.efforts ?? []).includes(block.reasoningEffort)) {
1060
- problems.push(`${role}的推理强度「${block.reasoningEffort}」不是模型「${model.id}」声明的能力`);
1210
+ problems.push(`执行设置选择了未配置的提供方「${worker.providerId}」`);
1211
+ } else {
1212
+ const model = (provider.models ?? []).find((entry) => entry.id === worker.model);
1213
+ if (model === undefined) {
1214
+ problems.push(`执行设置的模型「${worker.model ?? '(空)'}」不在提供方「${provider.id}」的模型列表中`);
1215
+ } else if (worker.reasoningEffort != null && !(model.efforts ?? []).includes(worker.reasoningEffort)) {
1216
+ problems.push(`执行设置的推理强度「${worker.reasoningEffort}」不是模型「${model.id}」声明的能力`);
1217
+ }
1061
1218
  }
1062
1219
  }
1063
- const timeout = Number(draft?.worker?.timeoutSeconds);
1064
- if (!Number.isInteger(timeout) || timeout < LIMITS.timeoutSecondsMin || timeout > LIMITS.timeoutSecondsMax) {
1065
- problems.push(`超时需为 ${LIMITS.timeoutSecondsMin}–${LIMITS.timeoutSecondsMax} 秒之间的整数`);
1066
- }
1220
+ // `worker.timeoutSeconds` is LEGACY: the field is no longer offered, no longer
1221
+ // bounds an ordinary run, and the host normalizes a bad stored value instead of
1222
+ // refusing the document. So it is deliberately NOT prechecked here — refusing a
1223
+ // save over a value the page never shows would block the operator for something
1224
+ // they can neither see nor fix.
1067
1225
  const parallelism = Number(draft?.worker?.maxParallelism);
1068
1226
  if (!Number.isInteger(parallelism) || parallelism < LIMITS.maxParallelismMin || parallelism > LIMITS.maxParallelismMax) {
1069
1227
  problems.push(`最大并发需为 ${LIMITS.maxParallelismMin}–${LIMITS.maxParallelismMax} 之间的整数`);
@@ -1074,6 +1232,13 @@ export function precheckDraft(draft) {
1074
1232
  // be validated by the narrow monitoring button and forgotten by this whole-draft check
1075
1233
  // (which is what happened to the repeated-failure count).
1076
1234
  problems.push(...precheckMonitoring(monitoringDraftOf(draft)));
1235
+ // The new-task Agent Teams default must be a real boolean. A UI switch can only ever
1236
+ // produce one, so this only fires for a hand-edited or imported document — and the
1237
+ // host would refuse it too, which is why the page says so before sending.
1238
+ const teamDefault = executionOf(draft).agentTeamsDefault;
1239
+ if (typeof teamDefault !== 'boolean') {
1240
+ problems.push('「新任务默认开启智能体协作」只能是开启或关闭');
1241
+ }
1077
1242
  return problems;
1078
1243
  }
1079
1244
 
@@ -1199,6 +1364,21 @@ export function permissionSummary(task) {
1199
1364
  };
1200
1365
  }
1201
1366
 
1367
+ /**
1368
+ * A monitoring threshold in plain Chinese, for a settings summary.
1369
+ *
1370
+ * A threshold is not an elapsed span, so `0` is not "0 秒": it is the documented
1371
+ * "off" and must read as such, or a reader would conclude the reminder fires
1372
+ * instantly. Any other value is the ordinary duration (`formatDuration`).
1373
+ * @param {number | null | undefined} seconds - stored threshold.
1374
+ * @returns {string} Chinese description, or `—` for a value that is not a number.
1375
+ */
1376
+ export function monitoringText(seconds) {
1377
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0) return '—';
1378
+ if (seconds === 0) return '已关闭';
1379
+ return formatDuration(seconds * 1000);
1380
+ }
1381
+
1202
1382
  /**
1203
1383
  * Human duration in plain Chinese, bounded to two units.
1204
1384
  *
@@ -1253,6 +1433,17 @@ export function taskActivity(task) {
1253
1433
  toolCallsFinished: Number.isFinite(activity.toolCallsFinished) ? activity.toolCallsFinished : null,
1254
1434
  selfCheckSeconds: Number.isFinite(activity.selfCheckSeconds) ? activity.selfCheckSeconds : null,
1255
1435
  attentionSeconds: Number.isFinite(activity.attentionSeconds) ? activity.attentionSeconds : null,
1436
+ // The run progress check, in the same bounded terms the reminder itself uses: the
1437
+ // one time base (no progress for that long), whether this silence already produced a
1438
+ // report, and the context facts. Absent in a record written before the fields existed.
1439
+ progressCheck: activity.progressCheck !== null && typeof activity.progressCheck === 'object'
1440
+ ? {
1441
+ thresholdSeconds: Number.isFinite(activity.progressCheck.thresholdSeconds) ? activity.progressCheck.thresholdSeconds : null,
1442
+ idleForMs: Number.isFinite(activity.progressCheck.idleForMs) ? activity.progressCheck.idleForMs : null,
1443
+ reportedThisEpisode: activity.progressCheck.reportedThisEpisode === true,
1444
+ nextDueAt: Number.isFinite(activity.progressCheck.nextDueAt) ? activity.progressCheck.nextDueAt : null,
1445
+ }
1446
+ : null,
1256
1447
  selfCheck: selfCheck === null || typeof selfCheck !== 'object'
1257
1448
  ? null
1258
1449
  : {
@@ -1315,11 +1506,13 @@ export function taskProgress(task) {
1315
1506
  // that then restarted), but the run will NOT resume. This branch exists because the
1316
1507
  // generic wording would otherwise promise progress that can never happen.
1317
1508
  detailParts.push('这条记录来自一次进程重启:任务已经中断,不会继续执行,也不会再有新的进展。');
1318
- } else if (activity.attentionSeconds !== null) {
1319
- detailParts.push(`超过 ${formatDuration(activity.attentionSeconds * 1000)} 没有新进展时会提醒你;提醒只是提示,不会自动判失败。`);
1509
+ } else if (activity.attentionSeconds !== null && activity.attentionSeconds > 0) {
1510
+ detailParts.push(`连续 ${formatDuration(activity.attentionSeconds * 1000)} 没有新成果回传给派工方时会提醒一次运行进度检查;读到自检结论不算新成果,提醒只是提示,不会自动判失败。`);
1511
+ } else if (activity.attentionSeconds === 0) {
1512
+ detailParts.push('运行进度检查提醒已关闭。');
1320
1513
  }
1321
1514
  if (activity.activityEvents !== null && activity.events !== null) {
1322
- detailParts.push(`已记录 ${activity.events} 个执行事件,其中 ${activity.activityEvents} 个是真正的进展。`);
1515
+ detailParts.push(`已记录 ${activity.events} 个执行事件,其中 ${activity.activityEvents} 个是真实输出或工具活动——它们不算回传给派工方的成果。`);
1323
1516
  }
1324
1517
  return {
1325
1518
  available: true,
@@ -1404,21 +1597,23 @@ export function hasChangingRecords(tasks) {
1404
1597
  }
1405
1598
 
1406
1599
  /**
1407
- * Pre-flight checks for the silence thresholds AND the repeated-failure count.
1600
+ * Pre-flight checks for the two no-progress thresholds AND the repeated-failure count.
1408
1601
  *
1409
- * Mirrors `validateMonitoringSettings`. Kept separate because the monitoring save has
1410
- * its own narrow button: a bad timer must not block saving the rest of the settings,
1411
- * and a bad provider block must not block saving a timer.
1602
+ * Mirrors `validateMonitoringSettings`. Kept separate because the monitoring block has
1603
+ * its own rules: a bad timer must not block saving the rest of the settings, and a bad
1604
+ * provider block must not block saving a timer.
1412
1605
  *
1413
1606
  * The block passed in must be the RAW one (`monitoringDraftOf`), not the display-normalized
1414
1607
  * `monitoringOf`: the latter replaces a cleared field with the documented default, which
1415
1608
  * would make an empty input look valid. This is the single validation path — `precheckDraft`
1416
- * and the monitoring card both delegate here, so the count cannot be checked in one place
1609
+ * and the monitoring card both delegate here, so no field can be checked in one place
1417
1610
  * and forgotten in another.
1418
1611
  *
1419
1612
  * Backwards compatible with an older document or an older host that has no
1420
1613
  * `repeatFailureThreshold` at all: an ABSENT value takes the documented default, exactly as
1421
- * the host validator does. A value that is present but wrong is still refused.
1614
+ * the host validator does. A value that is present but wrong is still refused. `0` is
1615
+ * ALWAYS valid for either duration and for the count — it is the documented "off" — so
1616
+ * only a missing or non-numeric value is an error there.
1422
1617
  * @param {{ selfCheckSeconds: number, attentionSeconds: number, repeatFailureThreshold?: number }} monitoring - raw block.
1423
1618
  * @returns {string[]} Chinese problem descriptions; empty when plausible.
1424
1619
  */
@@ -1426,7 +1621,7 @@ export function precheckMonitoring(monitoring) {
1426
1621
  const problems = [];
1427
1622
  const self = monitoring?.selfCheckSeconds;
1428
1623
  const attention = monitoring?.attentionSeconds;
1429
- // An ABSENT count is not an operator error: a document written before this setting
1624
+ // An ABSENT count is not an operator error: a document written before the setting
1430
1625
  // existed has no such key, and the host fills in the documented default. Anything the
1431
1626
  // operator actually supplied — `''`, `null`, a fraction, an out-of-range number — is
1432
1627
  // validated exactly as given. There is deliberately no `Number()` coercion and no
@@ -1435,13 +1630,15 @@ export function precheckMonitoring(monitoring) {
1435
1630
  ? MONITORING_DEFAULTS.repeatFailureThreshold
1436
1631
  : monitoring.repeatFailureThreshold;
1437
1632
  if (!Number.isInteger(self) || self < LIMITS.selfCheckSecondsMin || self > LIMITS.selfCheckSecondsMax) {
1438
- problems.push(`程序自检间隔需为 ${LIMITS.selfCheckSecondsMin}–${LIMITS.selfCheckSecondsMax} 秒之间的整数`);
1633
+ problems.push(`程序自检间隔需为 ${LIMITS.selfCheckSecondsMin}–${LIMITS.selfCheckSecondsMax} 秒之间的整数(0 表示关闭)`);
1439
1634
  }
1440
1635
  if (!Number.isInteger(attention) || attention < LIMITS.attentionSecondsMin || attention > LIMITS.attentionSecondsMax) {
1441
- problems.push(`提醒你的间隔需为 ${LIMITS.attentionSecondsMin}–${LIMITS.attentionSecondsMax} 秒之间的整数`);
1636
+ problems.push(`运行进度检查间隔需为 ${LIMITS.attentionSecondsMin}–${LIMITS.attentionSecondsMax} 秒之间的整数(0 表示关闭)`);
1442
1637
  }
1443
- if (Number.isInteger(self) && Number.isInteger(attention) && attention <= self) {
1444
- problems.push('提醒你的间隔必须大于程序自检间隔');
1638
+ // The ordering rule applies only when BOTH reminders are on: a disabled threshold has
1639
+ // no instant of its own, so it can never be "too early".
1640
+ if (Number.isInteger(self) && Number.isInteger(attention) && self > 0 && attention > 0 && attention <= self) {
1641
+ problems.push('运行进度检查间隔必须大于程序自检间隔(或把其中一项设为 0 关闭)');
1445
1642
  }
1446
1643
  // The repeated-failure reminder is a COUNT of consecutive identical failures; `0` is a
1447
1644
  // legal "off" value, so the range starts at zero rather than at one.
@@ -1639,29 +1836,193 @@ export function reviewNotePreview(task) {
1639
1836
  */
1640
1837
  export const RECORD_REFRESH_INTERVAL_MS = 5000;
1641
1838
 
1839
+ /**
1840
+ * How often a visible records page re-reads the list when NO record may change.
1841
+ *
1842
+ * This is the case that used to stop polling entirely, and it left an open page unable to
1843
+ * notice a task submitted from outside (Codex dispatching while the operator watches): an
1844
+ * empty list stays empty, and a page full of settled records stays settled, until the
1845
+ * operator reloads. The idle read is a plain read of the same list — no model call, no
1846
+ * task action, no settings write — so it is bounded and deliberately slower than the
1847
+ * active rate: a task that started elsewhere shows up within this interval, while an idle
1848
+ * page does not hammer the host.
1849
+ */
1850
+ export const RECORD_IDLE_REFRESH_INTERVAL_MS = 15000;
1851
+
1852
+ /**
1853
+ * Which rate a visible records page is polling at, or `null` when it must not poll.
1854
+ *
1855
+ * Three answers, because the page has three states:
1856
+ * * `active` — a record may still change (running, awaiting review, conclusion being
1857
+ * written): read quickly, so a conclusion appears without a reload;
1858
+ * * `idle` — nothing of ours may change: keep a SLOW read so a task submitted from
1859
+ * outside the page is still discovered;
1860
+ * * `null` — do not poll: the document is hidden, the records page is not open, or a
1861
+ * read is already in flight.
1862
+ * @param {object} input - `tasks`, `selectedTask`, `visible`, `mounted`, `loading`.
1863
+ * @returns {'active' | 'idle' | null} the polling mode.
1864
+ */
1865
+ export function recordRefreshMode(input = {}) {
1866
+ // Off the records page or hidden: nothing is watching, so nothing is read. Checked before
1867
+ // the in-flight case so an unmounted page reports "not polling" rather than "busy".
1868
+ if (input.mounted === false) return null;
1869
+ if (input.visible === false) return null;
1870
+ // One request at a time: a read already in flight owns the next tick.
1871
+ if (input.loading === true) return null;
1872
+ const all = [];
1873
+ if (Array.isArray(input.tasks)) all.push(...input.tasks);
1874
+ if (input.selectedTask !== null && input.selectedTask !== undefined) all.push(input.selectedTask);
1875
+ return hasChangingRecords(all) ? 'active' : 'idle';
1876
+ }
1877
+
1642
1878
  /**
1643
1879
  * The refresh decision for one render of the task view.
1644
1880
  *
1645
1881
  * Separates "is the execution running" (a status display question) from "may the RECORD
1646
1882
  * still change" (a polling question): a task waiting for review, or a review mid-save,
1647
- * keeps the page polling even though nothing is executing — and the page stops once every
1648
- * visible record is settled. Hidden pages never poll, and a page that is already loading
1649
- * never starts a second request.
1650
- * @param {object} input - `tasks`, `selectedTask`, `visible`, `loading`.
1883
+ * keeps the page at the ACTIVE rate even though nothing is executing, and a settled list
1884
+ * drops to the IDLE rate instead of stopping. Only a hidden page, an unopened records page
1885
+ * or an in-flight read suppresses the next tick.
1886
+ * @param {object} input - `tasks`, `selectedTask`, `visible`, `mounted`, `loading`.
1651
1887
  * @returns {{ refresh: boolean, intervalMs: number, reason: string }} plan.
1652
1888
  */
1653
1889
  export function recordRefreshPlan(input = {}) {
1654
- const all = [];
1655
- if (Array.isArray(input.tasks)) all.push(...input.tasks);
1656
- if (input.selectedTask !== null && input.selectedTask !== undefined) all.push(input.selectedTask);
1657
- const changing = hasChangingRecords(all);
1658
- const intervalMs = RECORD_REFRESH_INTERVAL_MS;
1659
- if (input.visible === false) return { refresh: false, intervalMs, reason: 'hidden' };
1660
- if (changing !== true) return { refresh: false, intervalMs, reason: 'settled' };
1661
- // One request at a time: a refresh already in flight owns the next tick.
1662
- if (input.loading === true) return { refresh: false, intervalMs, reason: 'loading' };
1663
- return { refresh: true, intervalMs, reason: 'changing' };
1890
+ const mode = recordRefreshMode(input);
1891
+ if (mode === null) {
1892
+ // The reason distinguishes the three suppression cases for the page and for tests.
1893
+ if (input.mounted === false) return { refresh: false, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'unmounted' };
1894
+ if (input.visible === false) return { refresh: false, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'hidden' };
1895
+ return { refresh: false, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'loading' };
1896
+ }
1897
+ if (mode === 'active') {
1898
+ return { refresh: true, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'changing' };
1899
+ }
1900
+ return { refresh: true, intervalMs: RECORD_IDLE_REFRESH_INTERVAL_MS, reason: 'idle' };
1901
+ }
1902
+
1903
+ /**
1904
+ * The next read of a visible records surface: when to do it, and why not.
1905
+ *
1906
+ * ONE plan for every surface that shows the shared task records — the records page
1907
+ * and the sidebar's TaskBridge view alike — so an open list that is waiting for a
1908
+ * task dispatched from OUTSIDE (Codex, an MCP host) is discovered by both, on the same
1909
+ * bounded rates, instead of each surface inventing its own policy:
1910
+ *
1911
+ * * the first read after mount is IMMEDIATE (`delayMs: 0`): a panel that opens on an
1912
+ * empty list must not wait a whole idle interval to learn whether anything exists;
1913
+ * * afterwards the ACTIVE rate applies while a record may still change, and the IDLE
1914
+ * rate otherwise — both plain list reads, no model call and no task action. An
1915
+ * already-loaded surface uses those rates from its very first tick (the immediate
1916
+ * read only happens when nothing has been read yet: `loading === false` marks that);
1917
+ * * a hidden document, an unmounted surface or a read already in flight schedules
1918
+ * nothing, and the surface re-checks when it becomes visible again.
1919
+ * @param {object} input - `tasks`, `selectedTask`, `visible`, `mounted`, `loading`,
1920
+ * `first` (true for the read right after mount).
1921
+ * @returns {{ refresh: boolean, delayMs: number | null, intervalMs: number, reason: string }} plan.
1922
+ */
1923
+ export function nextRecordsRead(input = {}) {
1924
+ if (input.mounted === false) return { refresh: false, delayMs: null, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'unmounted' };
1925
+ if (input.visible === false) return { refresh: false, delayMs: null, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'hidden' };
1926
+ if (input.loading === true) return { refresh: false, delayMs: null, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'loading' };
1927
+ if (input.first === true && input.hydrated !== true) {
1928
+ return { refresh: true, delayMs: 0, intervalMs: RECORD_REFRESH_INTERVAL_MS, reason: 'initial' };
1929
+ }
1930
+ const plan = recordRefreshPlan(input);
1931
+ return { refresh: plan.refresh, delayMs: plan.refresh ? plan.intervalMs : null, intervalMs: plan.intervalMs, reason: plan.reason };
1932
+ }
1933
+
1934
+ /**
1935
+ * Drive the records reads of ONE live surface for as long as it stays mounted.
1936
+ *
1937
+ * The single loop behind both surfaces that show the shared task records (the records
1938
+ * page and the sidebar's TaskBridge view). It reads through `store.refreshTasks`, so
1939
+ * the two surfaces never issue duplicate requests for the same store, it never reads a
1940
+ * row on its own, and it stops completely on dispose:
1941
+ *
1942
+ * * the first read is scheduled at once (an empty panel must not sit empty for a
1943
+ * whole interval while a task is waiting to be discovered);
1944
+ * * each read is followed by exactly ONE timer at the planned rate, re-planned from
1945
+ * the CURRENT snapshot passed in `readState()` so the rate follows the records;
1946
+ * * a hidden document pauses the loop, and becoming visible reads once immediately;
1947
+ * * an in-flight read owns the next tick (the plan returns `refresh: false`).
1948
+ *
1949
+ * Nothing here runs during render: a caller starts it from an effect and disposes it
1950
+ * with that effect's cleanup.
1951
+ * @param {object} options - `store` (with `refreshTasks`), `readState()` returning
1952
+ * `{ tasks, selectedTask, loading }`, `visible()` (default: document not hidden),
1953
+ * `onError(messageOrNull)`, `onRead()` (called after every attempt).
1954
+ * @returns {() => void} disposer: cancels the timer, drops the listener and never reads again.
1955
+ */
1956
+ export function startRecordsReadLoop(options = {}) {
1957
+ const store = options?.store ?? null;
1958
+ if (store === null || typeof store.refreshTasks !== 'function') return () => {};
1959
+ const doc = globalThis.document;
1960
+ const visible = typeof options.visible === 'function'
1961
+ ? options.visible
1962
+ : () => doc?.hidden !== true;
1963
+ const readState = typeof options.readState === 'function' ? options.readState : () => ({});
1964
+ const onError = typeof options.onError === 'function' ? options.onError : () => {};
1965
+ const onRead = typeof options.onRead === 'function' ? options.onRead : () => {};
1966
+
1967
+ let timer = null;
1968
+ let disposed = false;
1969
+ let inFlight = false;
1970
+ let first = true;
1971
+
1972
+ const clearTimer = () => {
1973
+ if (timer !== null) clearTimeout(timer);
1974
+ timer = null;
1975
+ };
1976
+ const schedule = () => {
1977
+ clearTimer();
1978
+ if (disposed) return;
1979
+ const plan = nextRecordsRead({ ...readState(), mounted: true, visible: visible(), first });
1980
+ if (!plan.refresh || plan.delayMs === null) return;
1981
+ first = false;
1982
+ // NO `unref()`: this timer is the surface's own life. Unref'd, a process whose only
1983
+ // pending work was this tick (DSH's web host, a Node-driven host) would be free to
1984
+ // exit the moment its last request finished — and the panel would silently stop
1985
+ // noticing anything until the operator clicked. Disposal ends it explicitly.
1986
+ timer = setTimeout(tick, plan.delayMs);
1987
+ };
1988
+ const read = async () => {
1989
+ if (disposed || inFlight) return;
1990
+ inFlight = true;
1991
+ try {
1992
+ const result = await store.refreshTasks('auto');
1993
+ if (disposed || result?.skipped === 'in-flight') return;
1994
+ onError(result?.ok === false ? (result.error ?? true) : null);
1995
+ onRead(result);
1996
+ } catch (error) {
1997
+ if (!disposed) onError(error);
1998
+ } finally {
1999
+ inFlight = false;
2000
+ schedule();
2001
+ }
2002
+ };
2003
+ const tick = () => {
2004
+ timer = null;
2005
+ if (disposed || visible() !== true) return;
2006
+ void read();
2007
+ };
2008
+ const onVisibility = () => {
2009
+ clearTimer();
2010
+ if (disposed) return;
2011
+ if (visible() !== true) return;
2012
+ // Back in view: read now rather than waiting out the remainder of an interval.
2013
+ first = true;
2014
+ void read();
2015
+ };
2016
+
2017
+ doc?.addEventListener?.('visibilitychange', onVisibility);
2018
+ schedule();
2019
+ return () => {
2020
+ disposed = true;
2021
+ clearTimer();
2022
+ doc?.removeEventListener?.('visibilitychange', onVisibility);
2023
+ };
1664
2024
  }
2025
+
1665
2026
  /**
1666
2027
  * Discoverable changed-file list in a task's diff payload.
1667
2028
  *
@@ -1748,6 +2109,10 @@ export function describeError(error) {
1748
2109
  const messages = {
1749
2110
  USER_PLANE_UNREACHABLE: '无法连接宿主设置接口:请确认 DSH 网页仍在运行,并刷新页面后重试。',
1750
2111
  USER_PLANE_MALFORMED: '宿主返回了无法识别的内容。',
2112
+ TASK_DISPLAY_NOT_ACCEPTED: '任务通过验收后才能归档。',
2113
+ TASK_DISPLAY_NOT_FOUND: '任务已不在当前历史中,请刷新。',
2114
+ TASK_DISPLAY_UNAVAILABLE: '归档暂不可用,请刷新后再试。',
2115
+ TASK_DISPLAY_LIMIT: '归档记录已达上限,请恢复部分记录后再试。',
1751
2116
  SETTINGS_MISSING: '请求中没有设置文档。',
1752
2117
  SETTINGS_INVALID: '设置内容不合法,已保留你的草稿。',
1753
2118
  SETTINGS_NO_PROVIDERS: '至少需要配置一个提供方。',
@@ -1819,6 +2184,19 @@ export function describeError(error) {
1819
2184
  DISCOVERY_MALFORMED_RESPONSE: '提供方返回的内容不是可识别的模型列表(需要 OpenAI 兼容的 {"data":[{"id":...}]})。',
1820
2185
  DISCOVERY_BODY_TOO_LARGE: '提供方返回的内容超过大小上限,已中止读取。',
1821
2186
  USER_PLANE_METHOD_NOT_ALLOWED: '该请求方法不被允许。',
2187
+ // Task-record cleanup. Each code names a different fix, and none of them removed a
2188
+ // record: a refusal is whole-batch.
2189
+ CLEANUP_INVALID: '清理请求不完整或超出范围,未删除任何记录。',
2190
+ CLEANUP_CHAIN_NOT_FOUND: '所选执行链已不在当前记录中,未删除任何记录;请刷新后重新选择。',
2191
+ CLEANUP_STALE: '任务记录已变化,所选轮次与当前记录不一致,未删除任何记录;请刷新后重新选择。',
2192
+ CLEANUP_CHAIN_LIVE: '所选执行链仍在执行或尚未结束,未删除任何记录。',
2193
+ CLEANUP_NOT_DURABLE: '所选记录尚未写入或未正常结束,未删除任何记录。',
2194
+ CLEANUP_NEXT_ROUND: '所选执行链还有后续续接轮次,未删除任何记录;请把整条链一起选中。',
2195
+ CLEANUP_PLAN_CHILDREN: '所选执行链下还有规划子节点,未删除任何记录;请先处理这些子节点。',
2196
+ CLEANUP_HIERARCHY_CHILDREN: '仍有子任务依赖这条记录,未删除任何记录。',
2197
+ CLEANUP_REVIEW_WRITE: '该任务的审查意见正在写入,未删除任何记录;请稍后重试。',
2198
+ CLEANUP_UNAVAILABLE: '当前宿主不提供记录清理能力(或记录暂时无法读取),未删除任何记录。',
2199
+ CLEANUP_FAILED: '记录写入失败,未删除任何记录;旧记录仍会显示。',
1822
2200
  };
1823
2201
  const known = messages[code];
1824
2202
  if (known !== undefined) return `${known}(${code})`;
@@ -1827,6 +2205,262 @@ export function describeError(error) {
1827
2205
  return code === '' ? detail : `${detail}(${code})`;
1828
2206
  }
1829
2207
 
2208
+ // ---------------------------------------------------------------------------
2209
+ // Task tree: the host's projection, read as data (never re-derived here)
2210
+ // ---------------------------------------------------------------------------
2211
+
2212
+ /**
2213
+ * Chinese label for one projected node status.
2214
+ *
2215
+ * These are the host's own status keys (`src/jobs/task-tree.js`). The page maps the
2216
+ * key to a word; it never invents a status, and an unknown key is shown verbatim so
2217
+ * a newer host degrades to a readable string instead of a blank.
2218
+ */
2219
+ export const TREE_STATUS_LABELS = Object.freeze({
2220
+ planned: '计划中(尚未执行)',
2221
+ running: '执行中',
2222
+ 'awaiting-permission': '等待逐次授权',
2223
+ 'awaiting-question': '等待回答问题',
2224
+ 'awaiting-host-review': '等待宿主审查',
2225
+ 'changes-requested': '需要修正',
2226
+ accepted: '审查通过',
2227
+ 'children-accepted': '子项均已通过,等待汇总审查',
2228
+ 'in-progress': '进行中',
2229
+ failed: '已失败',
2230
+ cancelled: '已取消',
2231
+ interrupted: '已中断',
2232
+ unknown: '状态未知',
2233
+ });
2234
+
2235
+ /** Badge tone for one projected node status. */
2236
+ export const TREE_STATUS_TONES = Object.freeze({
2237
+ accepted: 'on',
2238
+ running: 'on',
2239
+ planned: 'off',
2240
+ 'children-accepted': 'warn',
2241
+ 'in-progress': 'off',
2242
+ 'awaiting-host-review': 'warn',
2243
+ 'awaiting-permission': 'warn',
2244
+ 'awaiting-question': 'warn',
2245
+ 'changes-requested': 'warn',
2246
+ failed: 'warn',
2247
+ cancelled: 'off',
2248
+ interrupted: 'warn',
2249
+ unknown: 'off',
2250
+ });
2251
+
2252
+ /** How a broken relation is described, in the operator's own terms. */
2253
+ export const TREE_ORPHAN_LABELS = Object.freeze({
2254
+ 'missing-parent': '父节点不在当前记录中,暂列在此',
2255
+ 'missing-plan-node': '计划节点不在当前记录中,暂列在此',
2256
+ 'cycle-broken': '检测到父节点环路,已在此处断开',
2257
+ });
2258
+
2259
+ /**
2260
+ * The tree as the page should render it, or `null` when there is nothing to draw.
2261
+ *
2262
+ * Two inputs are accepted, both from the host: the structured `tree` (with `roots`)
2263
+ * and the flat `tree` (`flatNodes` only). The flat form is not re-parented — doing
2264
+ * that in the browser would be exactly the relation guessing the projection
2265
+ * exists to prevent — it only ORDERs the host's own `depth` values per `nodeId`,
2266
+ * and every identity still comes from the host.
2267
+ *
2268
+ * A host that answered no tree at all (an older version) yields `null`, and the
2269
+ * caller falls back to the flat list. An EMPTY tree is a real answer and is
2270
+ * reported separately (`roots: []` with counts), so "nothing planned yet" never
2271
+ * reads like "this host cannot show plans".
2272
+ *
2273
+ * `cleanupAvailable`/`cleanupError` are carried through when the host states them, and
2274
+ * are ABSENT when it does not: a page must not offer a removal action an older host
2275
+ * would refuse.
2276
+ * @param {object} body - the `/tasks` response body.
2277
+ * @returns {{ roots: object[], flatNodes: object[], counts: object, projects: object[] } | null} view.
2278
+ */
2279
+ export function taskTreeView(body) {
2280
+ const tree = body?.tree;
2281
+ if (tree === null || tree === undefined || typeof tree !== 'object' || Array.isArray(tree)) return null;
2282
+ const projects = Array.isArray(tree.projects) ? tree.projects : [];
2283
+ const counts = tree.counts !== null && typeof tree.counts === 'object' && !Array.isArray(tree.counts)
2284
+ ? tree.counts
2285
+ : {};
2286
+ const display = tree.displayArchiveAvailable === undefined ? {} : {
2287
+ displayArchiveAvailable: tree.displayArchiveAvailable, displayArchiveError: tree.displayArchiveError,
2288
+ };
2289
+ // Task-record cleanup. An absent block means the host predates the feature (the page
2290
+ // then hides the action), while a present one states whether it is available and why.
2291
+ const cleanup = tree.cleanupAvailable === undefined ? {} : {
2292
+ cleanupAvailable: tree.cleanupAvailable === true,
2293
+ cleanupError: typeof tree.cleanupError === 'string' ? tree.cleanupError : null,
2294
+ };
2295
+ if (Array.isArray(tree.roots)) {
2296
+ return { roots: tree.roots.filter(isRenderableNode), flatNodes: flatOfRoots(tree.roots), counts, projects, ...display, ...cleanup };
2297
+ }
2298
+ if (Array.isArray(tree.flatNodes)) {
2299
+ const roots = rootsFromFlatNodes(tree.flatNodes);
2300
+ // The flat shape carries no chain detail, so its chains expose no cleanup facts:
2301
+ // the page then hides the action instead of offering a checkbox that would fail.
2302
+ return { roots, flatNodes: tree.flatNodes.filter(isRenderableNode), counts, projects, ...display, ...cleanup };
2303
+ }
2304
+ // A tree object with neither shape is not a tree: treat it as an older host.
2305
+ return null;
2306
+ }
2307
+
2308
+ /**
2309
+ * Rebuild the nesting a flat projection already describes.
2310
+ *
2311
+ * Only `resolvedParentNodeId` (the host's RESOLVED parent, after orphan detection
2312
+ * and cycle breaking) is used, and only to nest; nothing is matched by title,
2313
+ * time or position. A node whose resolved parent is missing from the same answer
2314
+ * stays at the root rather than disappearing.
2315
+ * @param {object[]} flatNodes - host `flatNodes` in pre-order.
2316
+ * @returns {object[]} root nodes with `children`.
2317
+ */
2318
+ export function rootsFromFlatNodes(flatNodes) {
2319
+ const list = Array.isArray(flatNodes) ? flatNodes.filter(isRenderableNode) : [];
2320
+ const byId = new Map();
2321
+ const wrappers = list.map((node) => {
2322
+ const wrapper = { ...node, children: [] };
2323
+ if (!byId.has(node.nodeId)) byId.set(node.nodeId, wrapper);
2324
+ return wrapper;
2325
+ });
2326
+ const roots = [];
2327
+ for (const wrapper of wrappers) {
2328
+ const parentId = typeof wrapper.resolvedParentNodeId === 'string' ? wrapper.resolvedParentNodeId : null;
2329
+ const parent = parentId === null || parentId === wrapper.nodeId ? undefined : byId.get(parentId);
2330
+ if (parent === undefined) roots.push(wrapper);
2331
+ else parent.children.push(wrapper);
2332
+ }
2333
+ return roots;
2334
+ }
2335
+
2336
+ /** Pre-order flatten of structured roots, for counting and for tests. */
2337
+ function flatOfRoots(roots) {
2338
+ const out = [];
2339
+ const walk = (node) => {
2340
+ if (!isRenderableNode(node)) return;
2341
+ out.push(node);
2342
+ for (const child of Array.isArray(node.children) ? node.children : []) walk(child);
2343
+ };
2344
+ for (const node of roots) walk(node);
2345
+ return out;
2346
+ }
2347
+
2348
+ /** A node the page can key and draw: a stable identity is the one hard requirement. */
2349
+ function isRenderableNode(node) {
2350
+ return node !== null && typeof node === 'object' && typeof node.nodeId === 'string' && node.nodeId !== '';
2351
+ }
2352
+
2353
+ /** The tree slice of one `/tasks` answer, or null when the host sent none. */
2354
+ function treeOf(body) {
2355
+ return taskTreeView(body);
2356
+ }
2357
+
2358
+ /** The plan-document section of one `/tasks` answer, bounded to what the page states. */
2359
+ function plansSummaryOf(body) {
2360
+ const plans = body?.plans;
2361
+ if (plans === null || plans === undefined || typeof plans !== 'object' || Array.isArray(plans)) return null;
2362
+ return {
2363
+ available: plans.available === true,
2364
+ count: Number.isFinite(plans.count) ? plans.count : 0,
2365
+ reason: typeof plans.reason === 'string' ? plans.reason : null,
2366
+ };
2367
+ }
2368
+
2369
+ /** The state patch one successful list read produces. */
2370
+ function listPatchOf(body) {
2371
+ const view = treeOf(body);
2372
+ return {
2373
+ tasks: Array.isArray(body?.tasks) ? body.tasks : [],
2374
+ tree: view,
2375
+ treeAvailable: view !== null,
2376
+ plans: plansSummaryOf(body),
2377
+ tasksError: null,
2378
+ // Every successful list read marks the surface as hydrated, empty or not.
2379
+ tasksLoaded: true,
2380
+ };
2381
+ }
2382
+
2383
+ /**
2384
+ * Project the plan-creation form state onto the request body `PlanStore.create` takes.
2385
+ *
2386
+ * It lives in this framework-free module so the browser page, the DOM tests and any
2387
+ * future caller share ONE projection; `src/client/index.jsx` re-exports it.
2388
+ *
2389
+ * Rules:
2390
+ * * rows become a batch with positional keys (`row-1`, `row-2`, …), so two rows may
2391
+ * carry the SAME title and still be two distinct nodes;
2392
+ * * a row pointing at another row becomes `parentKey` — the only in-batch link
2393
+ * `plan.json` understands, and how one request builds several levels;
2394
+ * * a row pointing at an existing node, or a whole batch attached through the
2395
+ * selector, becomes `parentNodeId` with the REAL id (never a title);
2396
+ * * a blank row is dropped, so an empty trailing row cannot fail a valid batch; a
2397
+ * link to a row that is blank or gone is REFUSED rather than quietly creating the
2398
+ * node at another level;
2399
+ * * a root row keeps its own title/goal; the form's dedicated title/goal describe
2400
+ * the FIRST root, and are refused when every row already has a parent (they would
2401
+ * otherwise become a node nobody asked for);
2402
+ * * nothing is invented: no `connectionId` (the host fixes the owner), no id, no
2403
+ * acceptance, and a workspace only when one was actually chosen.
2404
+ * @param {object} draft - `{ title, goal, parentNodeId, workspacePath, rows }`.
2405
+ * @returns {{ body: object, problems: string[] }} request and local precheck problems.
2406
+ */
2407
+ export function planCreateRequest(draft) {
2408
+ const rows = Array.isArray(draft?.rows) ? draft.rows : [];
2409
+ const problems = [];
2410
+ const kept = [];
2411
+ const batchKeyOf = new Map();
2412
+ rows.forEach((row, index) => {
2413
+ const title = typeof row?.title === 'string' ? row.title.trim() : '';
2414
+ if (title === '') return;
2415
+ kept.push({ row, index, title });
2416
+ batchKeyOf.set(index, `row-${kept.length}`);
2417
+ });
2418
+ if (kept.length === 0) {
2419
+ problems.push('至少填写一个节点标题');
2420
+ return { body: { nodes: [] }, problems };
2421
+ }
2422
+ const items = kept.map(({ row, index, title }) => {
2423
+ const item = { key: batchKeyOf.get(index), title };
2424
+ const goal = typeof row.goalDescription === 'string' ? row.goalDescription.trim() : '';
2425
+ if (goal !== '') item.goalDescription = goal;
2426
+ const parent = typeof row.parent === 'string' ? row.parent : '';
2427
+ if (parent.startsWith('row:')) {
2428
+ const target = Number.parseInt(parent.slice(4), 10);
2429
+ const key = Number.isInteger(target) ? batchKeyOf.get(target) : undefined;
2430
+ if (key === undefined) {
2431
+ problems.push(`第 ${index + 1} 行的父节点“第 ${target + 1} 行”没有标题,无法作为父节点`);
2432
+ } else if (key === item.key) {
2433
+ problems.push(`第 ${index + 1} 行不能作为自己的父节点`);
2434
+ } else {
2435
+ item.parentKey = key;
2436
+ }
2437
+ } else if (parent !== '') {
2438
+ item.parentNodeId = parent;
2439
+ }
2440
+ return item;
2441
+ });
2442
+ if (problems.length > 0) return { body: { nodes: items }, problems };
2443
+
2444
+ const firstRoot = items.findIndex((item) => item.parentKey === undefined && item.parentNodeId === undefined);
2445
+ const formTitle = typeof draft?.title === 'string' ? draft.title.trim() : '';
2446
+ const formGoal = typeof draft?.goal === 'string' ? draft.goal.trim() : '';
2447
+ if (firstRoot >= 0) {
2448
+ if (formTitle !== '') items[firstRoot].title = formTitle;
2449
+ if (formGoal !== '') items[firstRoot].goalDescription = formGoal;
2450
+ } else if (formTitle !== '') {
2451
+ // Every row already names a parent: the batch is a set of children, and the title
2452
+ // cannot silently become a node the operator did not add a row for.
2453
+ problems.push('所有行都指定了父节点;标题只用于根节点,请清空标题或加一行根节点');
2454
+ }
2455
+
2456
+ const body = { nodes: items };
2457
+ const attachTo = typeof draft?.parentNodeId === 'string' ? draft.parentNodeId : '';
2458
+ if (attachTo !== '') body.parentNodeId = attachTo;
2459
+ const workspacePath = typeof draft?.workspacePath === 'string' ? draft.workspacePath.trim() : '';
2460
+ if (workspacePath !== '') body.workspacePath = workspacePath;
2461
+ return { body, problems };
2462
+ }
2463
+
1830
2464
  // ---------------------------------------------------------------------------
1831
2465
  // Store
1832
2466
  // ---------------------------------------------------------------------------
@@ -1843,6 +2477,10 @@ export function describeError(error) {
1843
2477
  */
1844
2478
  export function createStore(options = {}) {
1845
2479
  const api = options.api ?? createApi();
2480
+ // The task-record cleanup projection. It is injected rather than imported so this
2481
+ // module keeps one import list; `index.jsx` passes `cleanupProjection()`, and a
2482
+ // caller that passes nothing gets a projection that removes nothing.
2483
+ const cleanup = options.cleanup ?? emptyCleanupProjection();
1846
2484
  const now = typeof options.now === 'function' ? options.now : () => Date.now();
1847
2485
  // Debounce for the automatic save. Text inputs arrive one keystroke at a time, so a
1848
2486
  // short quiet period merges them into ONE whole-document PUT; switches and selects
@@ -1902,6 +2540,34 @@ export function createStore(options = {}) {
1902
2540
  selectedConnectionId: null,
1903
2541
  grants: [],
1904
2542
  tasks: [],
2543
+ /**
2544
+ * The host's task-tree projection, exactly as `/tasks` served it.
2545
+ *
2546
+ * `null` means "this host answered no tree" — either an older host (the key is
2547
+ * absent) or a failed read. The two are kept apart on purpose: a failed read
2548
+ * publishes `tasksError`, an older host only publishes `treeAvailable: false`,
2549
+ * and the page falls back to the flat list in BOTH cases instead of rendering
2550
+ * an invented hierarchy. Relations are never re-derived in the browser.
2551
+ */
2552
+ tree: null,
2553
+ treeAvailable: false,
2554
+ plans: null,
2555
+ /**
2556
+ * Whether a `/tasks` read has ever SUCCEEDED in this store.
2557
+ *
2558
+ * The records surfaces (the page and the sidebar) decide whether their first tick
2559
+ * must read at once or may wait a full interval: a store that already holds a
2560
+ * published list does not need an immediate read, an UNREAD one does. A list of
2561
+ * zero tasks cannot express that distinction by itself — "empty" and "never read"
2562
+ * look identical — which is why this fact is recorded rather than inferred.
2563
+ */
2564
+ tasksLoaded: false,
2565
+ /** The refused list read, or null. Distinguishes "failed" from "empty". */
2566
+ tasksError: null,
2567
+ /** The last refused plan create, or null; the form shows it and keeps its input. */
2568
+ planCreateError: null,
2569
+ /** Node ids of the last SUCCESSFUL plan create, in the host's order. */
2570
+ planCreateResult: null,
1905
2571
  taskDetail: null,
1906
2572
  // Visible feedback for the detail click: a spinner flag, and the refusal itself so
1907
2573
  // the panel can say WHY nothing opened instead of staying silent.
@@ -2686,7 +3352,7 @@ export function createStore(options = {}) {
2686
3352
  },
2687
3353
 
2688
3354
  /**
2689
- * Replace the silence thresholds and the repeated-failure count.
3355
+ * Replace the silence thresholds, the progress-check cadence and the repeated-failure count.
2690
3356
  *
2691
3357
  * The narrow route exists so an operator adjusting a timer cannot rewrite a
2692
3358
  * provider list. On success the committed document is adopted for `settings` and
@@ -2735,6 +3401,46 @@ export function createStore(options = {}) {
2735
3401
  });
2736
3402
  },
2737
3403
 
3404
+ /**
3405
+ * Set ONLY the operator's Agent Teams default for new tasks.
3406
+ *
3407
+ * Kept beside {@link saveMonitoring} for the same reason it is narrow: an operator
3408
+ * flipping one switch must not be able to rewrite a provider list through the same
3409
+ * call. It writes through the narrow `/execution` route and adopts the committed
3410
+ * document, leaving OTHER unsaved draft edits alone.
3411
+ *
3412
+ * It never touches DSH's global agent-teams switch, and it never changes a task that
3413
+ * already ran: each task froze its own choice at admission.
3414
+ * @param {boolean} enabled - the default a NEW task without its own choice gets.
3415
+ * @returns {Promise<{ ok: boolean, error?: unknown }>} outcome.
3416
+ */
3417
+ async saveAgentTeamsDefault(enabled) {
3418
+ if (typeof enabled !== 'boolean') {
3419
+ const problems = ['「新任务默认开启智能体协作」只能是开启或关闭'];
3420
+ notify('error', `未保存:${problems.join(';')}`);
3421
+ return { ok: false, problems };
3422
+ }
3423
+ if (saveInFlight) return { ok: false, pending: true };
3424
+ saveInFlight = true;
3425
+ return await track('execution', async () => {
3426
+ try {
3427
+ const body = await api.putExecution({ agentTeamsDefault: enabled });
3428
+ const committed = body.settings ?? null;
3429
+ const draft = state.draft === null
3430
+ ? draftFromSettings(committed)
3431
+ : { ...state.draft, execution: executionOf(committed ?? { execution: { agentTeamsDefault: enabled } }) };
3432
+ patch({ settings: committed, draft });
3433
+ notify('success', '新任务的智能体协作默认已保存。只影响之后没有单独指定协作选择的新派工。');
3434
+ return { ok: true, execution: body.execution ?? { agentTeamsDefault: enabled } };
3435
+ } catch (error) {
3436
+ notify('error', describeError(error));
3437
+ return { ok: false, error };
3438
+ } finally {
3439
+ saveInFlight = false;
3440
+ }
3441
+ });
3442
+ },
3443
+
2738
3444
  /**
2739
3445
  * Refresh the task list without operator-facing noise.
2740
3446
  *
@@ -2780,24 +3486,86 @@ export function createStore(options = {}) {
2780
3486
  }
2781
3487
  return merged;
2782
3488
  })();
2783
- patch({ tasks, taskDetail: detail });
3489
+ patch({
3490
+ ...listPatchOf(body),
3491
+ tasks,
3492
+ taskDetail: detail,
3493
+ });
2784
3494
  return { ok: true, tasks, reason };
2785
3495
  } catch (error) {
2786
3496
  if (reason === 'manual') notify('error', describeError(error));
3497
+ // The REASON a read failed is kept even for a silent background refresh: the
3498
+ // page must be able to say "this list is stale" instead of presenting the
3499
+ // previous rows as current. A failed read never clears the rows already shown.
3500
+ patch({ tasksError: error });
2787
3501
  return { ok: false, error };
2788
3502
  } finally {
2789
3503
  if (!disposed) patch({ loading: { ...state.loading, tasks: false } });
2790
3504
  }
2791
3505
  },
2792
3506
 
3507
+ /**
3508
+ * Create planning nodes from the page, then read them back from the host.
3509
+ *
3510
+ * The form owns its own input (the page keeps the draft, including on failure, so
3511
+ * a refused batch never costs the operator what they typed); this method only
3512
+ * sends one batch and then re-reads the records through the EXISTING refresh
3513
+ * path, which is what makes the new nodes appear with the host's own status,
3514
+ * sequence and parent resolution instead of a locally guessed one.
3515
+ * @param {object} body - `{ workspacePath?, parentNodeId?, nodes }`.
3516
+ * @returns {Promise<{ ok: boolean, nodes?: object[], error?: unknown }>} outcome.
3517
+ */
3518
+ async setDisplayArchive(nodeId, archived) {
3519
+ return await track('displayArchive', async () => {
3520
+ try {
3521
+ await api.setDisplayArchive(nodeId, archived);
3522
+ const outcome = await store.refreshTasks('manual');
3523
+ if (outcome.skipped === 'in-flight') await store.loadTasks();
3524
+ return { ok: true };
3525
+ } catch (error) {
3526
+ notify('error', `无法更新展示归档。${describeError(error)}`);
3527
+ return { ok: false, error };
3528
+ }
3529
+ });
3530
+ },
3531
+
3532
+ async createPlans(body) {
3533
+ return await track('planCreate', async () => {
3534
+ let created = [];
3535
+ try {
3536
+ const answer = await api.createPlans(body);
3537
+ created = Array.isArray(answer.nodes) ? answer.nodes : [];
3538
+ patch({ planCreateError: null, planCreateResult: created.map((node) => node.nodeId) });
3539
+ notify('success', `已创建 ${created.length} 个规划节点(只记录计划,不会执行)。`);
3540
+ } catch (error) {
3541
+ // The refusal is KEPT so the form can show why nothing was created and let
3542
+ // the operator fix one field; nothing was written (the host validates the
3543
+ // whole batch atomically).
3544
+ patch({ planCreateError: error, planCreateResult: null });
3545
+ notify('error', `创建规划失败:${describeError(error)}`);
3546
+ return { ok: false, error };
3547
+ }
3548
+ // Re-read through the normal path. A failure here is reported separately: the
3549
+ // nodes exist on disk even when this read failed, and saying otherwise would
3550
+ // invite a duplicate create.
3551
+ const refreshed = await store.refreshTasks('manual');
3552
+ if (refreshed?.ok === false) {
3553
+ notify('error', '规划已写入,但列表暂时读取失败;可点“刷新”重试(不要重复创建)。');
3554
+ return { ok: true, nodes: created, refreshFailed: true };
3555
+ }
3556
+ return { ok: true, nodes: created };
3557
+ });
3558
+ },
3559
+
2793
3560
  /** Read the task list. */
2794
3561
  async loadTasks() {
2795
3562
  return await track('tasks', async () => {
2796
3563
  try {
2797
3564
  const body = await api.listTasks();
2798
- patch({ tasks: Array.isArray(body.tasks) ? body.tasks : [] });
3565
+ patch(listPatchOf(body));
2799
3566
  return { ok: true, tasks: body.tasks ?? [] };
2800
3567
  } catch (error) {
3568
+ patch({ tasksError: error });
2801
3569
  notify('error', describeError(error));
2802
3570
  return { ok: false, error };
2803
3571
  }
@@ -2875,6 +3643,43 @@ export function createStore(options = {}) {
2875
3643
  });
2876
3644
  },
2877
3645
 
3646
+ /** Remove a confirmed selection whose exact rounds still match the current tree. */
3647
+ async cleanupTasks(selection) {
3648
+ const view = cleanup;
3649
+ const candidates = view.candidates(state.tree ?? null);
3650
+ const prepared = view.request(selection ?? {}, candidates);
3651
+ if (prepared.problems.length > 0) {
3652
+ notify('error', prepared.problems[0]);
3653
+ return { ok: false, error: new ApiError('CLEANUP_INVALID', prepared.problems[0]) };
3654
+ }
3655
+ return await track('cleanup', async () => {
3656
+ try {
3657
+ const outcome = await api.cleanupTasks(prepared.body);
3658
+ const deleted = view.outcome(outcome);
3659
+ const sentence = view.describe(outcome);
3660
+ if (sentence === '') throw new ApiError('CLEANUP_RESULT_UNCONFIRMED', '宿主未确认删除结果');
3661
+ notify('success', sentence);
3662
+ if (state.taskDetail !== null && deleted.deletedTaskIds.includes(state.taskDetail.taskId)) {
3663
+ store.closeTask();
3664
+ }
3665
+ // Re-read through the normal path: the tree, the counts and each chain's
3666
+ // eligibility come from the host, never from this response.
3667
+ const refreshed = await store.refreshTasks('manual');
3668
+ if (refreshed?.ok === false) {
3669
+ notify('error', '记录已删除,但列表暂时读取失败;请点“刷新”重试。');
3670
+ return { ok: true, outcome, refreshFailed: true };
3671
+ }
3672
+ return { ok: true, outcome };
3673
+ } catch (error) {
3674
+ const refused = error?.code?.startsWith('CLEANUP_') && error.code !== 'CLEANUP_RESULT_UNCONFIRMED';
3675
+ notify('error', refused ? describeError(error) : '未能确认清理结果,请查看刷新后的任务记录。');
3676
+ // The selection was made from a tree this host no longer agrees with.
3677
+ await store.refreshTasks('manual');
3678
+ return { ok: false, error };
3679
+ }
3680
+ });
3681
+ },
3682
+
2878
3683
  /** Load everything the page needs; the catalog is loaded but not awaited. */
2879
3684
  async init() {
2880
3685
  await Promise.all([store.refreshStatus(), store.loadSettings(), store.loadNativeProviders(), store.loadTasks()]);