dsh-work-fish 0.0.0-stage → 0.1.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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -2
  3. package/THIRD-PARTY-NOTICES.md +61 -0
  4. package/board/client.js +1048 -0
  5. package/cordis.patch.yml +173 -0
  6. package/core/approve-paths.mjs +387 -0
  7. package/core/approve-paths.test.mjs +241 -0
  8. package/core/approve.mjs +182 -0
  9. package/core/bootstrap.mjs +186 -0
  10. package/core/events.mjs +80 -0
  11. package/core/guard.mjs +155 -0
  12. package/core/index.mjs +630 -0
  13. package/core/parse.mjs +310 -0
  14. package/core/persona.mjs +98 -0
  15. package/core/pet-bridge.mjs +439 -0
  16. package/core/report.mjs +370 -0
  17. package/core/skills.mjs +111 -0
  18. package/docs/DETAIL.md +1 -0
  19. package/docs/DETAIL.zh.md +1 -0
  20. package/docs/preview.webp +0 -0
  21. package/icon.png +0 -0
  22. package/locale/en.json +7 -0
  23. package/locale/zh.json +7 -0
  24. package/package.json +69 -4
  25. package/rules/code-rules.md +92 -0
  26. package/rules/experience-pool.md +59 -0
  27. package/rules/file-rules.md +134 -0
  28. package/rules/memory-rules.md +91 -0
  29. package/rules/task-rules.md +71 -0
  30. package/skills/code-review/LICENSE +202 -0
  31. package/skills/code-review/NOTICE.md +75 -0
  32. package/skills/code-review/SKILL.md +155 -0
  33. package/skills/code-review/upstream/README.md +258 -0
  34. package/skills/code-review/upstream/code-review.command.md +110 -0
  35. package/skills/code-review/upstream/plugin.json +10 -0
  36. package/skills/code-simplifier/LICENSE +202 -0
  37. package/skills/code-simplifier/NOTICE.md +72 -0
  38. package/skills/code-simplifier/SKILL.md +126 -0
  39. package/skills/code-simplifier/agents/code-simplifier.md +52 -0
  40. package/skills/code-simplifier/upstream/plugin.json +9 -0
  41. package/skills/comfyui-h3/SKILL.md +455 -0
  42. package/skills/comfyui-h3/reference/failures.md +84 -0
  43. package/skills/comfyui-h3/reference/serial-production.md +173 -0
  44. package/skills/delete-gate/SKILL.md +48 -0
  45. package/skills/doc-writing/SKILL.md +152 -0
  46. package/skills/doc-writing/reference/skeletons.md +81 -0
  47. package/skills/feature-dev/LICENSE +202 -0
  48. package/skills/feature-dev/NOTICE.md +67 -0
  49. package/skills/feature-dev/SKILL.md +181 -0
  50. package/skills/feature-dev/agents/code-architect.md +34 -0
  51. package/skills/feature-dev/agents/code-explorer.md +51 -0
  52. package/skills/feature-dev/agents/code-reviewer.md +46 -0
  53. package/skills/feature-dev/upstream/README.md +412 -0
  54. package/skills/feature-dev/upstream/feature-dev.command.md +125 -0
  55. package/skills/feature-dev/upstream/plugin.json +9 -0
  56. package/skills/frontend-design/LICENSE.txt +177 -0
  57. package/skills/frontend-design/SKILL.md +71 -0
  58. package/skills/git-flow/SKILL.md +80 -0
  59. package/skills/plan-revision/SKILL.md +54 -0
  60. package/skills/task-setup/SKILL.md +124 -0
  61. package/template/AGENTS.template.md +28 -0
  62. package/template/memory/pool/experience.md +9 -0
  63. package/template/memory/preferences.md +17 -0
  64. package/template/memory/projects/README.md +6 -0
  65. package/template/memory/user-profile.md +33 -0
  66. package/template/persona-core.md +32 -0
  67. package/template/persona-user.md +0 -0
  68. package/template/rules/user-rules.md +20 -0
  69. package/template/rules-index.md +50 -0
  70. package/template/tasks/index.md +34 -0
  71. package/tools/lib/paths.mjs +31 -0
  72. package/tools/lib/persona.mjs +454 -0
  73. package/tools/lib/taskboard.mjs +713 -0
  74. package/tools/wf-audit.cmd +3 -0
  75. package/tools/wf-audit.ps1 +242 -0
  76. package/tools/wf-mem.mjs +336 -0
  77. package/tools/wf-metrics.mjs +601 -0
  78. package/tools/wf-persona.mjs +337 -0
  79. package/tools/wf-pool.mjs +250 -0
  80. package/tools/wf-preview.mjs +242 -0
  81. package/tools/wf-recent.mjs +168 -0
  82. package/tools/wf-review.mjs +650 -0
  83. package/tools/wf-rule.mjs +407 -0
  84. package/tools/wf-snapshot.mjs +100 -0
  85. package/tools/wf-spec.mjs +882 -0
  86. package/tools/wf-task.mjs +303 -0
@@ -0,0 +1,1048 @@
1
+ /**
2
+ * Browser half of Work Fish (`dsh-work-fish` client entry).
3
+ *
4
+ * One surface: the task panel. The character that used to stand next to it now
5
+ * belongs to `dsh-pet` — that plugin owns the sprite, the physics, the
6
+ * right-click menu and the settings page — so this module draws no pet at all.
7
+ * What is left is the thing only Work Fish can show: the ledger.
8
+ *
9
+ * Three mounts:
10
+ *
11
+ * - `conversation.session.header.utilities` — a button that toggles the
12
+ * panel, plus a seat that publishes the current session's composer actions
13
+ * so the panel's "问大肥鱼" line can hand a question to that session;
14
+ * - `shell.overlay` — the panel itself, floating over every page and dragged
15
+ * by its own header;
16
+ * - `settings.section` — the persona editor and read-only host facts.
17
+ *
18
+ * The panel is opened from either place: the header button, or the 「大肥鱼」
19
+ * group in the desktop pet's right-click menu, which reaches this half through
20
+ * the host's `GET /wf/events` long poll.
21
+ *
22
+ * @module dsh-work-fish/client
23
+ */
24
+
25
+ window.__ModuleLoader__.load({
26
+ id: 'dsh-work-fish',
27
+ factory(require) {
28
+ const React = require('react')
29
+ const h = React.createElement
30
+
31
+ /** `react-dom`, used to float the panel and its portal host outside the header. */
32
+ let reactDomModule
33
+ function reactDOM() {
34
+ if (reactDomModule !== undefined) return reactDomModule
35
+ try {
36
+ const dom = require('react-dom')
37
+ if (typeof dom?.createPortal === 'function') {
38
+ reactDomModule = dom
39
+ return dom
40
+ }
41
+ } catch {
42
+ reactDomModule = null
43
+ }
44
+ return null
45
+ }
46
+
47
+ /** Must match `ROUTE_PREFIX` in `core/index.mjs`. */
48
+ const ROUTE = '/wf'
49
+
50
+ /** Client-side identity, shared with the tests. */
51
+ const BOARD_ATTR = 'data-wf-board'
52
+ const SEAT_ATTR = 'data-wf-seat'
53
+ const ROW_ATTR = 'data-wf-row'
54
+
55
+ /** Panel geometry: one width, a drag handle, and the viewport clamp. */
56
+ const PANEL_WIDTH = 400
57
+ const PANEL_HEIGHT = 540
58
+ const POSITION_KEY = 'wf:board-position:v1'
59
+
60
+ /** Refresh cadence while the panel is open, in milliseconds. */
61
+ const POLL_MS = 60_000
62
+
63
+ /** The CSS this module installs once. */
64
+ const CSS = `
65
+ :root{--wf-danger:#c02b2b;--wf-warn:#8a5d0c;--wf-success:#1f8a55;--wf-on-accent:#fff}
66
+ [data-wf-board]{position:fixed;z-index:31;display:flex;flex-direction:column;border-radius:16px;background:var(--dsw-alias-bg-base,#fff);border:1px solid var(--dsw-alias-border-l2,#e3e8f2);box-shadow:0 28px 72px rgba(15,23,42,.28),0 4px 14px rgba(15,23,42,.08);color:var(--dsw-alias-label-primary,#1d2433);overflow:hidden}
67
+ [data-wf-board] *{box-sizing:border-box}
68
+ [data-wf-board] .jp-head{padding:12px 14px 0;border-bottom:1px solid var(--dsw-alias-border-l1,#eef1f7);cursor:grab;user-select:none;flex:none}
69
+ [data-wf-board][data-dragging="true"] .jp-head{cursor:grabbing}
70
+ [data-wf-board] .jp-title-row{display:flex;align-items:center;gap:9px}
71
+ [data-wf-board] .jp-avatar{width:26px;height:26px;border-radius:8px;background:linear-gradient(135deg,#e8efff,#d6e2ff);display:flex;align-items:center;justify-content:center;font-size:14px;flex:none;box-shadow:inset 0 0 0 1px rgba(77,107,254,.14)}
72
+ [data-wf-board] .jp-title{font-size:13.5px;font-weight:600;letter-spacing:.01em}
73
+ [data-wf-board] .jp-close{margin-left:auto;width:26px;height:26px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1,#eef1f7);background:0 0;color:var(--dsw-alias-label-tertiary,#8b96ab);font-size:12px;line-height:1;cursor:pointer;flex:none}
74
+ [data-wf-board] .jp-close:hover{background:var(--dsw-alias-interactive-bg-hover,#f2f5fb);color:var(--dsw-alias-label-primary,#1d2433)}
75
+ [data-wf-board] .jp-sub{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b96ab);margin-top:3px}
76
+ [data-wf-board] .jp-tabs{display:flex;gap:2px;margin:10px 0 0;padding:3px;background:var(--dsw-alias-bg-layer-2,#f1f4fa);border-radius:9px}
77
+ [data-wf-board] .jp-tab{flex:1;min-width:0;height:28px;padding:0;border:0;border-radius:7px;background:0 0;color:var(--dsw-alias-label-secondary,#6b7488);font:inherit;font-size:11px;line-height:1;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
78
+ [data-wf-board] .jp-tab:hover{color:var(--dsw-alias-label-primary,#1d2433)}
79
+ [data-wf-board] .jp-tab[data-active="true"]{background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#1d2433);font-weight:600;box-shadow:0 1px 4px rgba(15,23,42,.12)}
80
+ [data-wf-board] .jp-list{flex:1;min-height:0;overflow-y:auto;padding:10px 12px 12px;display:flex;flex-direction:column;gap:8px;scrollbar-width:thin;scrollbar-color:rgba(120,132,160,.35) transparent}
81
+ [data-wf-board] .jp-list::-webkit-scrollbar{width:8px}
82
+ [data-wf-board] .jp-list::-webkit-scrollbar-thumb{background:rgba(120,132,160,.28);border-radius:4px;border:2px solid transparent;background-clip:content-box}
83
+ [data-wf-board] .jp-alert{font-size:11px;color:var(--wf-warn);background:color-mix(in srgb,var(--wf-warn) 8%,transparent);border:1px solid color-mix(in srgb,var(--wf-warn) 28%,transparent);border-radius:7px;padding:5px 8px}
84
+ [data-wf-board] .jp-row{border:1px solid var(--dsw-alias-border-l1,#eef1f7);border-radius:10px;padding:9px 10px;background:var(--dsw-alias-bg-base,#fff);transition:border-color .12s,box-shadow .12s}
85
+ [data-wf-board] .jp-row:hover{border-color:var(--dsw-alias-border-l2,#e3e8f2);box-shadow:0 2px 10px rgba(15,23,42,.06)}
86
+ [data-wf-board] .jp-row[data-overdue="true"]{border-color:color-mix(in srgb,var(--wf-danger) 35%,transparent);background:color-mix(in srgb,var(--wf-danger) 4%,transparent)}
87
+ [data-wf-board] .jp-row-top{display:flex;align-items:center;gap:6px}
88
+ [data-wf-board] .jp-tag{font-size:10.5px;padding:2px 7px;border-radius:999px;background:var(--dsw-alias-bg-layer-2,#f1f4fa);color:var(--dsw-alias-label-secondary,#6b7488);font-weight:500}
89
+ [data-wf-board] .jp-tag[data-kind="inProgress"]{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#4d6bfe) 12%,transparent);color:var(--dsw-alias-state-business-primary,#4d6bfe)}
90
+ [data-wf-board] .jp-tag[data-kind="waiting"]{background:color-mix(in srgb,var(--wf-warn) 14%,transparent);color:var(--wf-warn)}
91
+ [data-wf-board] .jp-tag[data-kind="done"]{background:color-mix(in srgb,var(--wf-success) 12%,transparent);color:var(--wf-success)}
92
+ [data-wf-board] .jp-id{font:10.5px/1 Consolas,monospace;color:var(--dsw-alias-label-tertiary,#81858c)}
93
+ [data-wf-board] .jp-overdue{margin-left:auto;font-size:10.5px;color:var(--wf-danger);font-weight:500}
94
+ [data-wf-board] .jp-row-title{font-size:12.5px;font-weight:600;margin-top:5px;line-height:1.45}
95
+ [data-wf-board] .jp-meta{font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8b96ab);margin-top:3px}
96
+ [data-wf-board] .jp-next{font-size:10.5px;color:var(--dsw-alias-label-secondary,#6b7488);margin-top:5px;background:var(--dsw-alias-bg-layer-1,#f7f9fd);border-radius:6px;padding:4px 7px;line-height:1.45}
97
+ [data-wf-board] .jp-next b{color:var(--dsw-alias-state-business-primary,#4d6bfe);font-weight:600;margin-right:2px}
98
+ [data-wf-board] .jp-acts{display:flex;gap:6px;margin-top:8px;flex-wrap:wrap}
99
+ [data-wf-board] .jp-act{height:27px;padding:0 10px;border:.5px solid var(--dsw-alias-border-l3,#d5dbe7);border-radius:6px;background:0 0;color:var(--dsw-alias-label-primary,#1d2433);font:inherit;font-size:11.5px;cursor:pointer}
100
+ [data-wf-board] .jp-act:hover{background:var(--dsw-alias-interactive-bg-hover,#f2f5fb);border-color:var(--dsw-alias-state-business-primary,#4d6bfe);color:var(--dsw-alias-state-business-primary,#4d6bfe)}
101
+ [data-wf-board] .jp-act[data-primary="true"]{background:var(--dsw-alias-state-business-primary,#4d6bfe);border-color:transparent;color:var(--wf-on-accent)}
102
+ [data-wf-board] .jp-act:disabled{opacity:.45;cursor:default}
103
+ [data-wf-board] .jp-compose{margin-top:8px;border:1px solid var(--dsw-alias-border-l1,#eef1f7);border-radius:8px;padding:8px;background:var(--dsw-alias-bg-layer-1,#f7f9fd);display:flex;flex-direction:column;gap:6px}
104
+ [data-wf-board] .jp-input{width:100%;height:29px;padding:0 9px;border:1px solid var(--dsw-alias-border-l2,#e3e8f2);border-radius:7px;background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#1d2433);font:inherit;font-size:11.5px}
105
+ [data-wf-board] .jp-input:focus{outline:none;border-color:var(--dsw-alias-state-business-primary,#4d6bfe);box-shadow:0 0 0 2px color-mix(in srgb,var(--dsw-alias-state-business-primary,#4d6bfe) 16%,transparent)}
106
+ [data-wf-board] .jp-chips{display:flex;gap:5px;flex-wrap:wrap}
107
+ [data-wf-board] .jp-chip{display:inline-flex;align-items:center;min-height:26px;padding:0 9px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,#e3e8f2);background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-secondary,#6b7488);font-size:11px;cursor:pointer}
108
+ [data-wf-board] .jp-chip:hover{border-color:var(--dsw-alias-state-business-primary,#4d6bfe);color:var(--dsw-alias-state-business-primary,#4d6bfe)}
109
+ [data-wf-board] .jp-toast{font-size:11px;color:var(--dsw-alias-label-secondary,#6b7488);background:var(--dsw-alias-bg-layer-2,#eef2ff);border-radius:7px;padding:6px 9px}
110
+ [data-wf-board] .jp-empty{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b96ab);text-align:center;padding:24px 0}
111
+ [data-wf-board] .jp-foot{border-top:1px solid var(--dsw-alias-border-l1,#eef1f7);padding:9px 14px 11px;display:flex;flex-direction:column;gap:6px;flex:none}
112
+ [data-wf-board] .jp-ask{display:flex;align-items:center;gap:7px}
113
+ [data-wf-board] .jp-ask input{flex:1;min-width:0;height:32px;padding:0 10px;border:1px solid var(--dsw-alias-border-l2,#e3e8f2);border-radius:8px;background:var(--dsw-alias-bg-layer-1,#f7f9fd);color:var(--dsw-alias-label-primary,#1d2433);font:inherit;font-size:11.5px}
114
+ [data-wf-board] .jp-ask input:focus{outline:none;border-color:var(--dsw-alias-state-business-primary,#4d6bfe);background:var(--dsw-alias-bg-base,#fff)}
115
+ [data-wf-board] .jp-send{width:33px;height:33px;flex:none;border:0;border-radius:50%;background:var(--dsw-alias-state-business-primary,#4d6bfe);color:var(--wf-on-accent);font-size:13px;cursor:pointer}
116
+ [data-wf-board] .jp-send:disabled{opacity:.35;cursor:default}
117
+ [data-wf-board] .jp-note{font-size:10.5px;color:var(--dsw-alias-label-tertiary,#81858c);text-align:right}
118
+ [data-wf-seat]{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 9px;border:.5px solid var(--dsw-alias-border-l2,#e3e8f2);border-radius:999px;background:0 0;color:var(--dsw-alias-label-secondary,#6b7488);font:inherit;font-size:11.5px;cursor:pointer}
119
+ [data-wf-seat]:hover{background:var(--dsw-alias-interactive-bg-hover,#f2f5fb);color:var(--dsw-alias-label-primary,#1d2433)}
120
+ [data-wf-seat][data-open="true"]{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#4d6bfe) 10%,transparent);color:var(--dsw-alias-state-business-primary,#4d6bfe);border-color:transparent}
121
+ [data-wf-seat] .jp-seat-count{font-variant-numeric:tabular-nums;color:var(--wf-danger);font-weight:600}
122
+ [data-wf-settings]{width:100%;font-size:13px;line-height:22px;color:var(--dsw-alias-label-primary,#1d2433)}
123
+ [data-wf-settings] .jps-alert{display:flex;align-items:center;gap:10px;margin:0 0 18px;padding:0 0 12px;border-bottom:.5px solid var(--dsw-alias-border-l2,#e3e8f2);font-size:12px;line-height:18px;color:var(--dsw-alias-state-warn-primary,var(--wf-warn))}
124
+ [data-wf-settings] .jps-alert-dot{flex:none;width:6px;height:6px;border-radius:50%;background:currentColor}
125
+ [data-wf-settings] .jps-alert-text{flex:1;min-width:0}
126
+ [data-wf-settings] .jps-card{box-sizing:border-box;width:100%;padding:0 16px 4px;border:.5px solid var(--dsw-alias-settings-card-stroke,var(--dsw-alias-border-l3,#d5dbe7));border-radius:var(--dsw-radius-xl,20px);background:var(--dsw-alias-settings-card-fill,var(--dsw-alias-bg-layer-2,#f1f4fa))}
127
+ [data-wf-settings] .jps-card+.jps-card{margin-top:20px}
128
+ [data-wf-settings] .jps-title{margin:0;padding:14px 0 2px;font-size:14px;line-height:20px;font-weight:600}
129
+ [data-wf-settings] .jps-row{display:grid;grid-template-columns:minmax(0,1fr) 208px;align-items:center;column-gap:16px;padding:12px 0;border-bottom:.5px solid var(--dsw-alias-border-l2,#e3e8f2)}
130
+ [data-wf-settings] .jps-row[data-span="full"]{grid-template-columns:minmax(0,1fr)}
131
+ [data-wf-settings] .jps-card .jps-row:last-child{border-bottom:none}
132
+ [data-wf-settings] .jps-label{font-size:14px;line-height:20px}
133
+ [data-wf-settings] .jps-hint{margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#6b7488)}
134
+ [data-wf-settings] .jps-value{justify-self:end;min-width:0;font-size:12px;line-height:18px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#6b7488);text-align:right;word-break:break-all}
135
+ [data-wf-settings] .jps-btn{height:30px;padding:0 12px;border:.5px solid var(--dsw-alias-border-l3,#d5dbe7);border-radius:var(--dsw-radius-sm,8px);background:0 0;color:var(--dsw-alias-label-primary,#1d2433);font:inherit;font-size:13px;line-height:20px;cursor:pointer}
136
+ [data-wf-settings] .jps-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#f2f5fb)}
137
+ [data-wf-settings] .jps-btn[data-primary="true"]{border-color:transparent;background:var(--dsw-alias-state-business-primary,#4d6bfe);color:var(--wf-on-accent)}
138
+ [data-wf-settings] .jps-btn[data-primary="true"][disabled]{background:var(--dsw-alias-bg-layer-2,#f1f4fa);color:var(--dsw-alias-label-tertiary,#8b96ab);cursor:default}
139
+ [data-wf-settings] .jps-btn[data-size="sm"]{height:26px;padding:0 8px;font-size:12px}
140
+ [data-wf-settings] .jps-editor{display:flex;flex-direction:column;gap:8px;margin-top:8px;padding-bottom:12px}
141
+ [data-wf-settings] .jps-textarea{width:100%;height:132px;min-height:96px;padding:10px 12px;border:.5px solid var(--dsw-alias-border-l2,#e3e8f2);border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-bg-base,#fff);color:inherit;font-family:inherit;font-size:13px;line-height:20px;resize:vertical}
142
+ [data-wf-settings] .jps-textarea[data-invalid]{border-color:var(--dsw-alias-state-error-primary,var(--wf-danger))}
143
+ [data-wf-settings] .jps-foot{display:flex;align-items:center;gap:12px}
144
+ [data-wf-settings] .jps-count{font-size:12px;line-height:18px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#6b7488)}
145
+ [data-wf-settings] .jps-count[data-over="true"]{color:var(--dsw-alias-state-error-primary,var(--wf-danger))}
146
+ [data-wf-settings] .jps-status{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#6b7488)}
147
+ [data-wf-settings] .jps-note-inline{font-size:12px;line-height:18px;color:var(--dsw-alias-state-warn-primary,var(--wf-warn))}
148
+ [data-wf-settings] .jps-foot-actions{margin-left:auto;display:flex;align-items:center;gap:8px}
149
+ @media (max-width:420px){[data-wf-settings] .jps-row{grid-template-columns:minmax(0,1fr);row-gap:8px}[data-wf-settings] .jps-value{justify-self:start;text-align:left}}
150
+ @media (prefers-reduced-motion: reduce){[data-wf-board] *{transition:none!important}}
151
+ `
152
+
153
+ /** Install the stylesheet once per document, replacing a stale one on reload. */
154
+ function installCss() {
155
+ if (typeof document === 'undefined') return
156
+ const id = 'wf-css'
157
+ let style = document.getElementById(id)
158
+ if (style === null) {
159
+ style = document.createElement('style')
160
+ style.id = id
161
+ document.head.appendChild(style)
162
+ }
163
+ if (style.textContent !== CSS) style.textContent = CSS
164
+ }
165
+
166
+ /**
167
+ * Installed before the first component renders: a reloaded module must not
168
+ * paint with the sheet left behind by the previous generation.
169
+ */
170
+ installCss()
171
+
172
+ /** Report one activation fact to the host's diagnostics route. */
173
+ function report(payload) {
174
+ try {
175
+ void fetch(`${ROUTE}/client-report`, {
176
+ method: 'POST',
177
+ headers: { 'content-type': 'application/json' },
178
+ body: JSON.stringify(payload),
179
+ }).catch(() => {})
180
+ } catch {
181
+ return
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Module-level open flag: the header seat and the overlay panel mount in
187
+ * different slots but the same window, so one tiny store beats threading
188
+ * props through the slot API.
189
+ */
190
+ let boardOpen = false
191
+
192
+ /** @type {Set<(open: boolean) => void>} */
193
+ const openListeners = new Set()
194
+
195
+ /**
196
+ * Open or close the panel and tell every mounted consumer.
197
+ * @param {boolean} next desired state.
198
+ */
199
+ function setBoardOpen(next) {
200
+ if (boardOpen === next) return
201
+ boardOpen = next
202
+ for (const listener of [...openListeners]) {
203
+ try {
204
+ listener(next)
205
+ } catch {
206
+ continue
207
+ }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Subscribe to the open state.
213
+ * @param {(open: boolean) => void} listener called on every change.
214
+ * @returns {() => void} unsubscribe.
215
+ */
216
+ function subscribeBoard(listener) {
217
+ openListeners.add(listener)
218
+ return () => openListeners.delete(listener)
219
+ }
220
+
221
+ /**
222
+ * Read the saved panel position, or place it above the composer corner.
223
+ * @returns {{x: number, y: number}} viewport coordinates.
224
+ */
225
+ function readPosition() {
226
+ if (typeof window === 'undefined') return { x: 0, y: 0 }
227
+ const fallback = clampPosition(window.innerWidth - PANEL_WIDTH - 28, window.innerHeight - PANEL_HEIGHT - 40)
228
+ try {
229
+ const raw = window.localStorage.getItem(POSITION_KEY)
230
+ if (raw !== null) {
231
+ const parsed = JSON.parse(raw)
232
+ if (Number.isFinite(parsed?.x) && Number.isFinite(parsed?.y)) {
233
+ return clampPosition(parsed.x, parsed.y)
234
+ }
235
+ }
236
+ } catch {
237
+ return fallback
238
+ }
239
+ return fallback
240
+ }
241
+
242
+ /**
243
+ * Keep the panel inside the viewport.
244
+ * @param {number} x left.
245
+ * @param {number} y top.
246
+ * @returns {{x: number, y: number}} clamped position.
247
+ */
248
+ function clampPosition(x, y) {
249
+ const maxX = Math.max(8, window.innerWidth - Math.min(PANEL_WIDTH, window.innerWidth - 16) - 8)
250
+ const maxY = Math.max(8, window.innerHeight - 140)
251
+ return { x: Math.min(Math.max(8, x), maxX), y: Math.min(Math.max(8, y), maxY) }
252
+ }
253
+
254
+ /** Persist one panel position. */
255
+ function savePosition(position) {
256
+ try {
257
+ window.localStorage.setItem(POSITION_KEY, JSON.stringify(position))
258
+ } catch {
259
+ return
260
+ }
261
+ }
262
+
263
+ /** The weekday label the ledger uses. */
264
+ const WEEKDAY = { Mon: '周一', Tue: '周二', Wed: '周三', Thu: '周四', Fri: '周五', Sat: '周六', Sun: '周日' }
265
+
266
+ /** Read the maximum revision across the active rows. */
267
+ function maxRevision(data) {
268
+ let max = 0
269
+ for (const rows of [data?.inProgress, data?.todo, data?.waiting]) {
270
+ for (const row of Array.isArray(rows) ? rows : []) {
271
+ if (Number.isFinite(row?.rev)) max = Math.max(max, row.rev)
272
+ }
273
+ }
274
+ return max
275
+ }
276
+
277
+ /**
278
+ * Session-scoped facts the conversational seat offers the global panel.
279
+ *
280
+ * The panel mounts once over every page, so it cannot read a session's
281
+ * composer directly; the header seat publishes those facts here instead.
282
+ */
283
+ let sessionBridge = { sessionId: '', running: false, inputActions: null }
284
+ const sessionBridgeListeners = new Set()
285
+
286
+ /** Merge a patch and notify only when a field actually changed. */
287
+ function bridgeUpdate(patch) {
288
+ const next = { ...sessionBridge, ...patch }
289
+ if (
290
+ next.sessionId === sessionBridge.sessionId &&
291
+ next.running === sessionBridge.running &&
292
+ next.inputActions === sessionBridge.inputActions
293
+ ) {
294
+ return
295
+ }
296
+ sessionBridge = next
297
+ for (const listener of sessionBridgeListeners) listener(sessionBridge)
298
+ }
299
+
300
+ /** Subscribe to bridge updates; returns the unsubscribe. */
301
+ function bridgeSubscribe(listener) {
302
+ sessionBridgeListeners.add(listener)
303
+ return () => sessionBridgeListeners.delete(listener)
304
+ }
305
+
306
+ /** One task row, its actions, and the inline composer. */
307
+ function TaskRow({ row, kind, api }) {
308
+ const overdue = Number.isFinite(row?.overdueDays) && row.overdueDays > 0
309
+ const meta = []
310
+ if (kind === 'waiting') {
311
+ if (row.who) meta.push(`等 ${row.who}`)
312
+ if (row.what) meta.push(row.what)
313
+ if (row.nudge) meta.push(`催 ${row.nudge}`)
314
+ } else if (kind === 'done') {
315
+ if (row.completed) meta.push(`完成 ${row.completed}`)
316
+ if (row.deliverable) meta.push(row.deliverable)
317
+ } else {
318
+ meta.push(`截止 ${row.dueRaw || '未定'}`)
319
+ }
320
+ if (row.priority) meta.push(`优先级 ${row.priority}`)
321
+ if (Number.isFinite(row.rev) && row.rev > 0) meta.push(`r${row.rev}`)
322
+
323
+ const id = row.id || ''
324
+ const busy = id !== '' && api.busyKey.startsWith(`${id}:`)
325
+ const composing = api.compose !== null && api.compose.id === id
326
+ const canWrite = api.writes === true && id !== '' && Number.isInteger(row.rev) && row.rev > 0
327
+ const act = (action, body = {}) => api.action(action, { id, expectRev: row.rev, ...body })
328
+ const openCompose = (mode) => api.setCompose({ id, rev: row.rev, mode, text: '', result: '', deliverable: '' })
329
+
330
+ const actions = []
331
+ if (canWrite) {
332
+ if (kind === 'todo') {
333
+ actions.push(h('button', { key: 'start', className: 'jp-act', 'data-primary': 'true', disabled: busy, onClick: () => act('start') }, busy ? '写入中…' : '开始'))
334
+ } else if (kind === 'inProgress') {
335
+ actions.push(h('button', { key: 'advance', className: 'jp-act', disabled: busy, onClick: () => openCompose('advance') }, '推进'))
336
+ actions.push(h('button', { key: 'finish', className: 'jp-act', disabled: busy, onClick: () => openCompose('finish') }, '完成'))
337
+ actions.push(h('button', { key: 'pause', className: 'jp-act', disabled: busy, onClick: () => act('pause') }, '暂停'))
338
+ } else if (kind === 'waiting') {
339
+ actions.push(h('button', { key: 'nudge', className: 'jp-act', disabled: busy, onClick: () => act('nudge', { text: '催办' }) }, '催一下'))
340
+ actions.push(h('button', { key: 'resume', className: 'jp-act', 'data-primary': 'true', disabled: busy, onClick: () => act('resume') }, '继续'))
341
+ }
342
+ }
343
+
344
+ const composeNode =
345
+ composing === false
346
+ ? null
347
+ : h(
348
+ 'div',
349
+ { className: 'jp-compose' },
350
+ api.compose.mode === 'advance'
351
+ ? h(
352
+ React.Fragment,
353
+ null,
354
+ h('input', {
355
+ className: 'jp-input',
356
+ autoFocus: true,
357
+ placeholder: '写一句进展…',
358
+ value: api.compose.text,
359
+ onChange: (event) => api.updateCompose({ text: event.target.value }),
360
+ onKeyDown: (event) => {
361
+ if (event.key === 'Enter' && !event.nativeEvent?.isComposing) {
362
+ event.preventDefault()
363
+ api.submitCompose()
364
+ }
365
+ },
366
+ }),
367
+ h(
368
+ 'div',
369
+ { className: 'jp-chips' },
370
+ ...['已提交', '等评审', '已改完', '卡住了'].map((quick) =>
371
+ h('button', { key: quick, type: 'button', className: 'jp-chip', onClick: () => api.updateCompose({ text: quick }) }, quick),
372
+ ),
373
+ ),
374
+ )
375
+ : h(
376
+ React.Fragment,
377
+ null,
378
+ h('input', {
379
+ className: 'jp-input',
380
+ autoFocus: true,
381
+ placeholder: '结果(默认:已完成)',
382
+ value: api.compose.result,
383
+ onChange: (event) => api.updateCompose({ result: event.target.value }),
384
+ }),
385
+ h('input', {
386
+ className: 'jp-input',
387
+ placeholder: '交付物(可选)',
388
+ value: api.compose.deliverable,
389
+ onChange: (event) => api.updateCompose({ deliverable: event.target.value }),
390
+ }),
391
+ ),
392
+ h(
393
+ 'div',
394
+ { className: 'jp-acts' },
395
+ h(
396
+ 'button',
397
+ {
398
+ className: 'jp-act',
399
+ 'data-primary': 'true',
400
+ disabled: busy || (api.compose.mode === 'advance' && api.compose.text.trim() === ''),
401
+ onClick: () => api.submitCompose(),
402
+ },
403
+ busy ? '写入中…' : '记录',
404
+ ),
405
+ h('button', { className: 'jp-act', disabled: busy, onClick: () => api.setCompose(null) }, '取消'),
406
+ ),
407
+ )
408
+
409
+ return h(
410
+ 'div',
411
+ { className: 'jp-row', [ROW_ATTR]: row.id, 'data-overdue': overdue ? 'true' : undefined },
412
+ h(
413
+ 'div',
414
+ { className: 'jp-row-top' },
415
+ h('span', { className: 'jp-tag', 'data-kind': kind }, kind === 'waiting' ? '等待' : kind === 'todo' ? '待办' : kind === 'done' ? '已做' : '进行中'),
416
+ row.id ? h('span', { className: 'jp-id' }, row.id) : null,
417
+ overdue ? h('span', { className: 'jp-overdue' }, `逾期 ${row.overdueDays} 天`) : null,
418
+ ),
419
+ h('div', { className: 'jp-row-title' }, row.title || '(无标题)'),
420
+ meta.length > 0 ? h('div', { className: 'jp-meta' }, meta.join(' · ')) : null,
421
+ row.next ? h('div', { className: 'jp-next' }, h('b', null, '下一步'), ' ', row.next) : null,
422
+ actions.length > 0 ? h('div', { className: 'jp-acts' }, ...actions) : null,
423
+ composeNode,
424
+ )
425
+ }
426
+
427
+ /** The floating task panel: header handle, four tabs, rows, ask line. */
428
+ function TaskPanel({ position, onMove, onClose, data, error, loading, tabs, activeTab, onTab, draft, onDraft, onSend, canSend, toast, api }) {
429
+ const rows =
430
+ data === null
431
+ ? []
432
+ : activeTab === 'inProgress'
433
+ ? data.inProgress
434
+ : activeTab === 'todo'
435
+ ? data.todo
436
+ : activeTab === 'waiting'
437
+ ? data.waiting
438
+ : data.doneToday
439
+ const kind = activeTab === 'done' ? 'done' : activeTab
440
+ const counts = data?.counts ?? {}
441
+ const weekday = WEEKDAY[data?.today?.weekday] ?? ''
442
+ const alerts = Array.isArray(data?.alerts) ? data.alerts.slice(0, 2) : []
443
+ const empty = data !== null && rows.length === 0
444
+ const drag = React.useRef(null)
445
+ const [dragging, setDragging] = React.useState(false)
446
+
447
+ const onPointerDown = (event) => {
448
+ if (event.button !== 0) return
449
+ /** Buttons inside the header (the close control) must stay clickable. */
450
+ if (event.target instanceof Element && event.target.closest('button') !== null) return
451
+ event.currentTarget.setPointerCapture?.(event.pointerId)
452
+ drag.current = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, originX: position.x, originY: position.y }
453
+ setDragging(true)
454
+ }
455
+ const onPointerMove = (event) => {
456
+ const state = drag.current
457
+ if (state === null || state.pointerId !== event.pointerId) return
458
+ onMove(clampPosition(state.originX + (event.clientX - state.startX), state.originY + (event.clientY - state.startY)))
459
+ }
460
+ const onPointerUp = (event) => {
461
+ const state = drag.current
462
+ if (state === null || state.pointerId !== event.pointerId) return
463
+ drag.current = null
464
+ setDragging(false)
465
+ event.currentTarget.releasePointerCapture?.(event.pointerId)
466
+ onMove(position, true)
467
+ }
468
+
469
+ return h(
470
+ 'div',
471
+ {
472
+ [BOARD_ATTR]: 'true',
473
+ 'data-dragging': dragging ? 'true' : undefined,
474
+ style: {
475
+ left: `${position.x}px`,
476
+ top: `${position.y}px`,
477
+ width: `${Math.min(PANEL_WIDTH, typeof window === 'undefined' ? PANEL_WIDTH : window.innerWidth - 16)}px`,
478
+ height: `${Math.min(PANEL_HEIGHT, typeof window === 'undefined' ? PANEL_HEIGHT : window.innerHeight - 32)}px`,
479
+ },
480
+ role: 'dialog',
481
+ 'aria-label': '大肥鱼任务',
482
+ },
483
+ h(
484
+ 'div',
485
+ { className: 'jp-head', onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp },
486
+ h(
487
+ 'div',
488
+ { className: 'jp-title-row' },
489
+ h('span', { className: 'jp-avatar' }, '🐋'),
490
+ h('span', { className: 'jp-title' }, '大肥鱼 · 任务'),
491
+ h('button', { className: 'jp-close', type: 'button', 'aria-label': '关闭', onClick: onClose }, '✕'),
492
+ ),
493
+ h(
494
+ 'div',
495
+ { className: 'jp-sub' },
496
+ data === null
497
+ ? loading
498
+ ? '读取台账…'
499
+ : '台账不可读'
500
+ : `${data.today?.label ?? ''} ${weekday} · 逾期 ${counts.overdue ?? 0} · 活跃 ${counts.active ?? 0} · r${maxRevision(data)}`,
501
+ ),
502
+ h(
503
+ 'div',
504
+ { className: 'jp-tabs' },
505
+ tabs.map((tab) =>
506
+ h(
507
+ 'button',
508
+ {
509
+ key: tab.id,
510
+ type: 'button',
511
+ className: 'jp-tab',
512
+ 'data-active': activeTab === tab.id ? 'true' : undefined,
513
+ onClick: () => onTab(tab.id),
514
+ },
515
+ `${tab.label} ${tab.count}`,
516
+ ),
517
+ ),
518
+ ),
519
+ ),
520
+ h(
521
+ 'div',
522
+ { className: 'jp-list' },
523
+ toast ? h('div', { className: 'jp-toast' }, toast) : null,
524
+ error !== null ? h('div', { className: 'jp-alert' }, error) : null,
525
+ ...alerts.map((alert) => h('div', { key: alert, className: 'jp-alert' }, alert)),
526
+ empty ? h('div', { className: 'jp-empty' }, loading ? '读取台账…' : '这一栏是空的') : null,
527
+ rows.map((row) => h(TaskRow, { key: `${kind}:${row.id || row.title}`, row, kind, api })),
528
+ ),
529
+ h(
530
+ 'div',
531
+ { className: 'jp-foot' },
532
+ h(
533
+ 'div',
534
+ { className: 'jp-ask' },
535
+ h('input', {
536
+ value: draft,
537
+ placeholder: canSend ? '问大肥鱼,或让他推进…' : '到会话页才能发',
538
+ disabled: !canSend,
539
+ onChange: (event) => onDraft(event.target.value),
540
+ onKeyDown: (event) => {
541
+ if (event.key === 'Enter' && !event.nativeEvent?.isComposing) {
542
+ event.preventDefault()
543
+ onSend()
544
+ }
545
+ },
546
+ }),
547
+ h('button', { className: 'jp-send', type: 'button', disabled: !canSend || draft.trim() === '', onClick: onSend, 'aria-label': '发送' }, '↑'),
548
+ ),
549
+ h('div', { className: 'jp-note' }, '读自任务台账 · 打开时每 60 秒刷新'),
550
+ ),
551
+ )
552
+ }
553
+
554
+ /** The panel's data, writes and event subscription, mounted once. */
555
+ function BoardSurface() {
556
+ const [open, setOpen] = React.useState(boardOpen)
557
+ const [position, setPosition] = React.useState(readPosition)
558
+ const [data, setData] = React.useState(null)
559
+ const [error, setError] = React.useState(null)
560
+ const [loading, setLoading] = React.useState(false)
561
+ const [activeTab, setActiveTab] = React.useState('inProgress')
562
+ const [draft, setDraft] = React.useState('')
563
+ const [busyKey, setBusyKey] = React.useState('')
564
+ const [compose, setCompose] = React.useState(null)
565
+ const [toast, setToast] = React.useState('')
566
+ const [session, setSession] = React.useState(sessionBridge)
567
+
568
+ React.useEffect(() => subscribeBoard(setOpen), [])
569
+ React.useEffect(() => bridgeSubscribe(setSession), [])
570
+
571
+ const canSend = typeof session.inputActions?.setDraft === 'function' && typeof session.inputActions?.submit === 'function'
572
+
573
+ /** Fetch the task payload; never throws into render. */
574
+ const load = React.useCallback(async () => {
575
+ setLoading(true)
576
+ try {
577
+ const response = await fetch(`${ROUTE}/tasks`, { headers: { accept: 'application/json' }, cache: 'no-store' })
578
+ const body = await response.json()
579
+ if (!response.ok || body?.ok !== true) throw new Error(body?.detail || body?.message || `HTTP ${response.status}`)
580
+ setData(body)
581
+ setError(null)
582
+ } catch (failure) {
583
+ setError(`台账读取失败:${String(failure?.message ?? failure)}`)
584
+ } finally {
585
+ setLoading(false)
586
+ }
587
+ }, [])
588
+
589
+ /**
590
+ * Read once so the header button can show an overdue count, then refresh on
591
+ * the slow cadence while closed and the fast one while open.
592
+ */
593
+ React.useEffect(() => {
594
+ void load()
595
+ const timer = window.setInterval(() => {
596
+ if (!open) void load()
597
+ }, 5 * 60000)
598
+ return () => window.clearInterval(timer)
599
+ }, [load, open])
600
+
601
+ React.useEffect(() => {
602
+ if (!open) return undefined
603
+ void load()
604
+ const timer = window.setInterval(() => void load(), POLL_MS)
605
+ return () => window.clearInterval(timer)
606
+ }, [open, load])
607
+
608
+ /**
609
+ * Host events: the pet's menu asks for the panel, or a write elsewhere moved
610
+ * the ledger. The first poll subscribes from "now", so remounting the panel
611
+ * cannot replay a click that happened before it existed; after that the
612
+ * cursor follows the host's sequence — zero included, because a restarted
613
+ * host starts its sequence over.
614
+ */
615
+ React.useEffect(() => {
616
+ let alive = true
617
+ let since = null
618
+ const controller = new AbortController()
619
+ const run = async () => {
620
+ while (alive) {
621
+ try {
622
+ const query = since === null ? '?wait=8000' : `?since=${since}&wait=8000`
623
+ const response = await fetch(`${ROUTE}/events${query}`, {
624
+ headers: { accept: 'application/json' },
625
+ cache: 'no-store',
626
+ signal: controller.signal,
627
+ })
628
+ const body = await response.json()
629
+ if (body?.ok !== true) throw new Error(body?.message ?? 'events')
630
+ if (typeof body.since === 'number') since = body.since
631
+ for (const event of Array.isArray(body.events) ? body.events : []) {
632
+ if (event?.type === 'open') setBoardOpen(true)
633
+ if (event?.type === 'changed') void load()
634
+ }
635
+ } catch {
636
+ if (!alive) return
637
+ await new Promise((resolve) => window.setTimeout(resolve, 4000))
638
+ }
639
+ }
640
+ }
641
+ void run()
642
+ return () => {
643
+ alive = false
644
+ controller.abort()
645
+ }
646
+ }, [load])
647
+
648
+ /** Escape closes the panel, so it never sits in the way. */
649
+ React.useEffect(() => {
650
+ if (!open) return undefined
651
+ const onKey = (event) => {
652
+ if (event.key === 'Escape') setBoardOpen(false)
653
+ }
654
+ document.addEventListener('keydown', onKey)
655
+ return () => document.removeEventListener('keydown', onKey)
656
+ }, [open])
657
+
658
+ /** Move the panel, optionally persisting the result. */
659
+ const moveTo = React.useCallback((next, persist = false) => {
660
+ setPosition(next)
661
+ if (persist) savePosition(next)
662
+ }, [])
663
+
664
+ /** POST one task mutation, then reload the payload. */
665
+ const write = React.useCallback(
666
+ async (action, body) => {
667
+ setBusyKey(`${body.id}:${action}`)
668
+ try {
669
+ const response = await fetch(`${ROUTE}/tasks/${action}`, {
670
+ method: 'POST',
671
+ headers: { 'content-type': 'application/json', 'x-wf': '1' },
672
+ body: JSON.stringify(body),
673
+ })
674
+ const result = await response.json().catch(() => null)
675
+ if (!response.ok || result?.ok !== true) {
676
+ if (result?.verdict === 'STALE') setToast(`台账刚被改过(r${result.currentRev ?? '?'}),已刷新`)
677
+ else setToast(result?.message || `写入失败(HTTP ${response.status})`)
678
+ setCompose(null)
679
+ await load()
680
+ return false
681
+ }
682
+ const label = action === 'finish' ? '已完成' : action === 'start' ? '已开始' : action === 'pause' ? '已暂停' : action === 'nudge' ? '已记催办' : '已记录'
683
+ setToast(label)
684
+ setCompose(null)
685
+ await load()
686
+ return true
687
+ } catch (failure) {
688
+ setToast(`写入失败:${String(failure?.message ?? failure)}`)
689
+ return false
690
+ } finally {
691
+ setBusyKey('')
692
+ }
693
+ },
694
+ [load],
695
+ )
696
+
697
+ /** Patch the open composer. */
698
+ const updateCompose = React.useCallback((patch) => {
699
+ setCompose((current) => (current === null ? null : { ...current, ...patch }))
700
+ }, [])
701
+
702
+ /** Submit the open composer as advance or finish. */
703
+ const submitCompose = React.useCallback(() => {
704
+ if (compose === null) return
705
+ if (compose.mode === 'advance') {
706
+ const text = compose.text.trim()
707
+ if (text === '') return
708
+ void write('advance', { id: compose.id, expectRev: compose.rev, text })
709
+ } else {
710
+ void write('finish', {
711
+ id: compose.id,
712
+ expectRev: compose.rev,
713
+ result: compose.result.trim() || '已完成',
714
+ deliverable: compose.deliverable.trim() || undefined,
715
+ })
716
+ }
717
+ }, [compose, write])
718
+
719
+ /**
720
+ * The status line lives for four seconds; `toast` is its only owner.
721
+ */
722
+ React.useEffect(() => {
723
+ if (toast === '') return undefined
724
+ const timer = window.setTimeout(() => setToast(''), 4000)
725
+ return () => window.clearTimeout(timer)
726
+ }, [toast])
727
+
728
+ const onSend = () => {
729
+ const value = draft.trim()
730
+ if (value === '' || !canSend) return
731
+ try {
732
+ session.inputActions.setDraft(value)
733
+ session.inputActions.submit()
734
+ setDraft('')
735
+ } catch {
736
+ setError('发送失败:当前会话不接受输入')
737
+ }
738
+ }
739
+
740
+ const tabs = [
741
+ { id: 'inProgress', label: '进行中', count: data?.inProgress?.length ?? 0 },
742
+ { id: 'todo', label: '待办', count: data?.todo?.length ?? 0 },
743
+ { id: 'waiting', label: '等待', count: data?.waiting?.length ?? 0 },
744
+ { id: 'done', label: '今日', count: data?.doneToday?.length ?? 0 },
745
+ ]
746
+ const api = {
747
+ writes: data?.writes === true,
748
+ busyKey,
749
+ compose,
750
+ action: write,
751
+ setCompose,
752
+ updateCompose,
753
+ submitCompose,
754
+ }
755
+
756
+ if (!open) return null
757
+
758
+ const panel = h(TaskPanel, {
759
+ position,
760
+ onMove: moveTo,
761
+ onClose: () => setBoardOpen(false),
762
+ data,
763
+ error,
764
+ loading,
765
+ tabs,
766
+ activeTab,
767
+ onTab: setActiveTab,
768
+ draft,
769
+ onDraft: setDraft,
770
+ onSend,
771
+ canSend,
772
+ toast,
773
+ api,
774
+ })
775
+
776
+ const dom = reactDOM()
777
+ if (dom !== null && typeof document !== 'undefined') return dom.createPortal(panel, document.body)
778
+ return panel
779
+ }
780
+
781
+ /** Button in the conversation header: opens the panel and publishes session facts. */
782
+ function SessionSeat(props) {
783
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : ''
784
+ const inputActions = props?.inputActions ?? null
785
+ const running =
786
+ typeof props?.useSessionStatus === 'function'
787
+ ? props.useSessionStatus((statuses) => statuses?.get?.(sessionId)?.running === true)
788
+ : false
789
+ const [open, setOpen] = React.useState(boardOpen)
790
+ const [overdue, setOverdue] = React.useState(0)
791
+
792
+ React.useEffect(() => subscribeBoard(setOpen), [])
793
+ React.useEffect(() => {
794
+ bridgeUpdate({ sessionId, inputActions })
795
+ return () => bridgeUpdate({ sessionId: '', inputActions: null })
796
+ }, [sessionId, inputActions])
797
+ React.useEffect(() => {
798
+ bridgeUpdate({ running })
799
+ }, [running])
800
+
801
+ /** A cheap overdue count for the badge; the panel does the real reading. */
802
+ React.useEffect(() => {
803
+ let alive = true
804
+ const tick = async () => {
805
+ try {
806
+ const response = await fetch(`${ROUTE}/tasks`, { headers: { accept: 'application/json' }, cache: 'no-store' })
807
+ const body = await response.json()
808
+ if (alive && body?.ok === true) setOverdue(Number(body?.counts?.overdue ?? 0))
809
+ } catch {
810
+ return
811
+ }
812
+ }
813
+ void tick()
814
+ const timer = window.setInterval(() => void tick(), 5 * 60000)
815
+ return () => {
816
+ alive = false
817
+ window.clearInterval(timer)
818
+ }
819
+ }, [])
820
+
821
+ return h(
822
+ 'button',
823
+ {
824
+ type: 'button',
825
+ [SEAT_ATTR]: 'true',
826
+ 'data-open': open ? 'true' : undefined,
827
+ title: '大肥鱼任务台账',
828
+ onClick: () => setBoardOpen(!boardOpen),
829
+ },
830
+ h('span', null, '🐋 任务'),
831
+ overdue > 0 ? h('span', { className: 'jp-seat-count' }, overdue > 9 ? '9+' : String(overdue)) : null,
832
+ )
833
+ }
834
+
835
+ /**
836
+ * Settings → 大肥鱼: the persona editor plus read-only host facts.
837
+ *
838
+ * The pet's own preferences (size, physics, notifications) live in
839
+ * `dsh-pet`'s settings page now; this section only owns what Work Fish owns.
840
+ */
841
+ function WorkFishSettings() {
842
+ const [info, setInfo] = React.useState(null)
843
+ const [error, setError] = React.useState(null)
844
+
845
+ /** Fetch the host's diagnostics; never throws into render. */
846
+ const loadInfo = React.useCallback(async () => {
847
+ try {
848
+ const response = await fetch(`${ROUTE}/info`, { headers: { accept: 'application/json' }, cache: 'no-store' })
849
+ const body = await response.json()
850
+ if (!response.ok || body?.ok !== true) throw new Error(body?.detail || body?.message || `HTTP ${response.status}`)
851
+ setInfo(body)
852
+ setError(null)
853
+ } catch (failure) {
854
+ setError(String(failure?.message ?? failure))
855
+ }
856
+ }, [])
857
+
858
+ React.useEffect(() => {
859
+ void loadInfo()
860
+ }, [loadInfo])
861
+
862
+ const [persona, setPersona] = React.useState(null)
863
+ const [personaDraft, setPersonaDraft] = React.useState('')
864
+ const [personaNote, setPersonaNote] = React.useState(null)
865
+ const [personaBusy, setPersonaBusy] = React.useState(false)
866
+
867
+ /** Read the current persona (mode, bytes, revision, user text). */
868
+ const loadPersona = React.useCallback(async () => {
869
+ try {
870
+ const response = await fetch(`${ROUTE}/persona`, { headers: { accept: 'application/json' }, cache: 'no-store' })
871
+ const body = await response.json()
872
+ if (!response.ok || body?.ok !== true) throw new Error(body?.message || `HTTP ${response.status}`)
873
+ setPersona(body)
874
+ setPersonaDraft(typeof body.user === 'string' ? body.user : '')
875
+ } catch (failure) {
876
+ setPersonaNote({ kind: 'error', text: `读取人设失败:${String(failure?.message ?? failure)}` })
877
+ }
878
+ }, [])
879
+
880
+ React.useEffect(() => {
881
+ void loadPersona()
882
+ }, [loadPersona])
883
+
884
+ /** UTF-8 byte count, the unit the store enforces. */
885
+ const personaBytes = (() => {
886
+ const text = personaDraft
887
+ try {
888
+ return new TextEncoder().encode(text).length
889
+ } catch {
890
+ return text.length
891
+ }
892
+ })()
893
+ const personaLimit = persona?.limit ?? 32768
894
+ const personaOver = personaBytes > personaLimit
895
+ /** Nothing to save until the draft differs from what is stored. */
896
+ const personaDirty = persona !== null && personaDraft.trimEnd() !== String(persona.user ?? '').trimEnd()
897
+
898
+ /** Put the user section, CAS-guarded by the revision we read. */
899
+ const savePersona = async () => {
900
+ if (personaBusy) return
901
+ if (personaOver) {
902
+ setPersonaNote({ kind: 'error', text: `超限 ${personaBytes - personaLimit} 字节,先删一些再保存。` })
903
+ return
904
+ }
905
+ setPersonaBusy(true)
906
+ try {
907
+ const response = await fetch(`${ROUTE}/persona`, {
908
+ method: 'PUT',
909
+ headers: { 'content-type': 'application/json', 'x-wf': '1' },
910
+ body: JSON.stringify({ mode: 'user', text: personaDraft, expectRevision: persona?.revision }),
911
+ })
912
+ const body = await response.json().catch(() => null)
913
+ if (response.ok && body?.ok === true) {
914
+ setPersonaNote({ kind: 'ok', text: '已保存,下一步对话生效(无需重启)。' })
915
+ await loadPersona()
916
+ } else if (response.status === 409) {
917
+ setPersonaNote({ kind: 'error', text: '人设已在别处改动,先点「重新载入」再保存。' })
918
+ } else {
919
+ setPersonaNote({ kind: 'error', text: `${body?.message ?? `HTTP ${response.status}`}` })
920
+ }
921
+ } catch (failure) {
922
+ setPersonaNote({ kind: 'error', text: String(failure?.message ?? failure) })
923
+ } finally {
924
+ setPersonaBusy(false)
925
+ }
926
+ }
927
+
928
+ const alertLine = (() => {
929
+ const unreadable = info !== null && info?.ledger?.readable === false
930
+ if (error === null && !unreadable) return null
931
+ return h(
932
+ 'div',
933
+ { className: 'jps-alert' },
934
+ h('span', { className: 'jps-alert-dot' }),
935
+ h('span', { className: 'jps-alert-text' }, error !== null ? '运行信息没读出来,设置仍可用' : '台账读不到,面板是空的'),
936
+ h('button', { type: 'button', className: 'jps-btn', 'data-size': 'sm', 'data-primary': 'true', onClick: () => void loadInfo() }, '重试'),
937
+ )
938
+ })()
939
+
940
+ const infoRow = (label, value, hint) =>
941
+ h(
942
+ 'div',
943
+ { className: 'jps-row' },
944
+ h('div', null, h('div', { className: 'jps-label' }, label), hint === undefined ? null : h('div', { className: 'jps-hint' }, hint)),
945
+ h('div', { className: 'jps-value' }, value),
946
+ )
947
+
948
+ const personaHint = persona?.mode === 'full' ? '整段人设生效中,此页只改补充' : '清空后保存即回出厂人设'
949
+
950
+ const factsCard = h(
951
+ 'section',
952
+ { className: 'jps-card' },
953
+ h('h3', { className: 'jps-title' }, '台账与桌宠'),
954
+ infoRow('台账', info?.ledger?.path ?? '—', '唯一事实来源,面板与 CLI 读写同一份'),
955
+ infoRow('桌宠', info?.pet?.connected === true ? `已连上 ${info.pet.petId}` : info?.pet?.reason || '未连上', '形象与菜单由 dsh-pet 提供'),
956
+ infoRow('写入', info?.allowWrites === true ? '允许' : '已关闭', '关掉后桌宠菜单与面板都只能读'),
957
+ )
958
+
959
+ const personaCard = h(
960
+ 'section',
961
+ { className: 'jps-card' },
962
+ h('h3', { className: 'jps-title' }, '人设'),
963
+ h(
964
+ 'div',
965
+ { className: 'jps-row', 'data-span': 'full' },
966
+ h(
967
+ 'div',
968
+ null,
969
+ h('div', { className: 'jps-label' }, '补充'),
970
+ h('div', { className: 'jps-hint' }, personaHint),
971
+ h(
972
+ 'div',
973
+ { className: 'jps-editor' },
974
+ h('textarea', {
975
+ className: 'jps-textarea',
976
+ 'data-invalid': personaOver ? 'true' : undefined,
977
+ spellCheck: false,
978
+ value: personaDraft,
979
+ placeholder: '叫我老板;回答简短些,先给结论。',
980
+ onChange: (event) => setPersonaDraft(event.target.value),
981
+ }),
982
+ h(
983
+ 'div',
984
+ { className: 'jps-foot' },
985
+ h('span', { className: 'jps-count', 'data-over': personaOver ? 'true' : undefined }, `${personaBytes} / ${personaLimit} 字节`),
986
+ personaOver
987
+ ? h('span', { className: 'jps-note-inline' }, `超出 ${personaBytes - personaLimit} 字节`)
988
+ : personaNote === null
989
+ ? null
990
+ : h('span', { className: personaNote.kind === 'ok' ? 'jps-status' : 'jps-note-inline' }, personaNote.text),
991
+ h(
992
+ 'span',
993
+ { className: 'jps-foot-actions' },
994
+ h('button', { type: 'button', className: 'jps-btn', 'data-size': 'sm', onClick: () => void loadPersona() }, '重新载入'),
995
+ h(
996
+ 'button',
997
+ {
998
+ type: 'button',
999
+ className: 'jps-btn',
1000
+ 'data-primary': 'true',
1001
+ disabled: personaBusy || personaOver || !personaDirty,
1002
+ onClick: () => void savePersona(),
1003
+ },
1004
+ personaBusy ? '处理中…' : '保存',
1005
+ ),
1006
+ ),
1007
+ ),
1008
+ ),
1009
+ ),
1010
+ ),
1011
+ )
1012
+
1013
+ return h('div', { 'data-wf-settings': 'true' }, alertLine, factsCard, personaCard)
1014
+ }
1015
+
1016
+ report({ phase: 'factory' })
1017
+
1018
+ return {
1019
+ inject: ['slots'],
1020
+ apply(ctx) {
1021
+ try {
1022
+ ctx.slots.inject('shell.overlay', () =>
1023
+ ctx.slots.register({ name: 'shell.overlay', id: 'work-fish-board', order: 40 }, BoardSurface),
1024
+ )
1025
+ report({ phase: 'applied', slot: 'shell.overlay' })
1026
+ } catch (error) {
1027
+ report({ phase: 'apply-failed', slot: 'shell.overlay', detail: String(error?.message ?? error) })
1028
+ }
1029
+ try {
1030
+ ctx.slots.inject('conversation.session.header.utilities', () =>
1031
+ ctx.slots.register({ name: 'conversation.session.header.utilities', id: 'wf-seat', order: 100 }, SessionSeat),
1032
+ )
1033
+ report({ phase: 'applied', slot: 'conversation.session.header.utilities' })
1034
+ } catch (error) {
1035
+ report({ phase: 'apply-failed', slot: 'conversation.session.header.utilities', detail: String(error?.message ?? error) })
1036
+ }
1037
+ try {
1038
+ ctx.slots.inject('settings.section', () =>
1039
+ ctx.slots.register({ name: 'settings.section', id: 'work-fish', order: 30, label: () => '大肥鱼' }, WorkFishSettings),
1040
+ )
1041
+ report({ phase: 'applied', slot: 'settings.section' })
1042
+ } catch (error) {
1043
+ report({ phase: 'apply-failed', slot: 'settings.section', detail: String(error?.message ?? error) })
1044
+ }
1045
+ },
1046
+ }
1047
+ },
1048
+ })