@yolk_vat-y/dsh-project-memory 0.6.2 → 0.6.4

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 (44) hide show
  1. package/CHANGELOG.md +178 -7
  2. package/README.md +26 -23
  3. package/README.zh-CN.md +24 -21
  4. package/client/client.js +432 -248
  5. package/client/client.js.map +1 -1
  6. package/package.json +3 -2
  7. package/scripts/bench-synthetic.mjs +22 -11
  8. package/src/audit.js +36 -32
  9. package/src/auto-inject.js +44 -23
  10. package/src/client/MemoryView.tsx +72 -4
  11. package/src/client/ShowTaskPanelNode.tsx +8 -5
  12. package/src/client/TaskCommandNode.tsx +23 -17
  13. package/src/client/TaskComponents.tsx +18 -3
  14. package/src/client/TaskPanel.tsx +60 -89
  15. package/src/client/client.ts +26 -6
  16. package/src/client/commands.ts +67 -0
  17. package/src/client/task-data-store.ts +33 -14
  18. package/src/client/task-scope.js +32 -0
  19. package/src/client/task-ui-store.ts +15 -2
  20. package/src/commands/insight-actions.js +5 -1
  21. package/src/commands/task-actions.js +59 -4
  22. package/src/commands/tasks.js +5 -2
  23. package/src/index.js +12 -0
  24. package/src/insight-store.js +286 -84
  25. package/src/lazy.js +3 -1
  26. package/src/ops.js +14 -3
  27. package/src/readiness.js +1 -1
  28. package/src/recall.js +76 -30
  29. package/src/setup/taskbridge.js +34 -3
  30. package/src/store.js +329 -46
  31. package/src/tools/forget.js +31 -8
  32. package/src/tools/index-doc.js +3 -5
  33. package/src/tools/index-repo.js +10 -11
  34. package/src/tools/lesson-tools.js +25 -35
  35. package/src/tools/query-memory.js +87 -29
  36. package/src/tools/remember.js +14 -11
  37. package/src/tools/stats.js +31 -4
  38. package/src/tools/task-tools.js +11 -12
  39. package/src/tools/watch-repo.js +3 -5
  40. package/src/types.js +9 -4
  41. package/src/util/fs.js +128 -1
  42. package/src/util/search.js +6 -27
  43. package/src/vector-index.js +175 -22
  44. package/src/watch.js +2 -2
@@ -13,8 +13,9 @@ import {
13
13
  IconQuestionOutline14,
14
14
  } from './icons.ts'
15
15
  import { createTranslate, zh, en } from './locales.ts'
16
+ import { invokeCommand } from './commands.ts'
16
17
  import { missingServices, service } from './services.ts'
17
- import { useTaskData, useTaskDataActions, taskDataStore, parseTaskPayloadText, type TaskStep } from './task-data-store.ts'
18
+ import { useTaskData, useTaskDataActions, parseTaskPayloadText } from './task-data-store.ts'
18
19
  import { useTaskUI, useTaskUIActions, PANEL_VIEWS } from './task-ui-store.ts'
19
20
  import { MiniBar, TaskCard } from './TaskComponents.tsx'
20
21
  import { MemoryView, type InsightScope } from './MemoryView.tsx'
@@ -78,6 +79,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
78
79
  const degraded = missingServices(ctx)
79
80
  const sessionId = useSessionId(ctx)
80
81
  const [syncing, setSyncing] = useState(false)
82
+ const syncingRef = useRef(false)
81
83
  const [syncedAt, setSyncedAt] = useState(0)
82
84
  const [syncError, setSyncError] = useState<string | null>(null)
83
85
  // 提示信息开关落在 UI store(持久化):关掉后面板内所有悬停 title 气泡都不再弹出。
@@ -102,88 +104,67 @@ function TaskPanelView({ ctx }: { ctx: any }) {
102
104
  const applyPayload = (text?: string): boolean => {
103
105
  const parsed = parseTaskPayloadText(text)
104
106
  if (!parsed) return false
105
- dataActions.setTasks({ tasks: parsed.tasks, boundTaskId: parsed.boundId, archivedCount: parsed.archived })
107
+ dataActions.setTasks({ tasks: parsed.tasks, boundTaskId: parsed.boundId, archivedCount: parsed.archived, root: parsed.root })
106
108
  setSyncedAt(Date.now())
107
109
  setSyncError(null)
108
110
  return true
109
111
  }
110
112
 
111
113
  const runLine = async (line: string): Promise<boolean> => {
112
- // 软探测(services.ts):`remote.commands` 是**独立注册的扁平服务**,必须按整名读;
113
- // `ctx.remote.commands` 走属性路径,会被 inject 门控挡下(本插件顶层 inject 为空)。
114
- const commands = service(ctx, 'remote.commands')
115
- if (!sessionId || !commands || typeof commands.execute !== 'function') {
116
- setSyncError(t('panel.no-channel'))
114
+ const result = await invokeCommand(ctx, sessionId, line)
115
+ if (!result.ok) {
116
+ setSyncError(result.error === 'no-channel' ? t('panel.no-channel') : (result.error || t('panel.sync-failed')))
117
117
  return false
118
118
  }
119
- let response: any
120
- try {
121
- response = await commands.execute(sessionId, line, [])
122
- } catch (err) {
123
- setSyncError(String((err as { message?: unknown } | null | undefined)?.message ?? err))
124
- return false
125
- }
126
- const envelope = response as { ok?: boolean; value?: any } | null | undefined
127
- const execution = envelope && typeof envelope === 'object' && 'value' in envelope ? envelope.value : envelope
128
- const result = execution?.result ?? execution
129
- if (result?.kind === 'error') {
130
- setSyncError(result.text ?? 'command error')
131
- return false
132
- }
133
- return applyPayload(result?.text)
119
+ return applyPayload(result.text)
134
120
  }
135
121
 
136
- const refresh = async (): Promise<void> => {
137
- if (syncing) return
122
+ // 锁用 ref 而不是渲染快照里的 state:同一 tick 的两次触发也能被挡住。
123
+ const withLock = async (fn: () => Promise<unknown>): Promise<void> => {
124
+ if (syncingRef.current) return
125
+ syncingRef.current = true
138
126
  setSyncing(true)
139
127
  try {
140
- const prevBoundId = data.boundTaskId
141
- await runLine('/tasks')
142
- const newBoundId = taskDataStore.getSnapshot().boundTaskId
143
- if (newBoundId && newBoundId !== prevBoundId) {
144
- await runLine(`/tasks switch ${newBoundId}`)
145
- }
128
+ await fn()
146
129
  } finally {
130
+ syncingRef.current = false
147
131
  setSyncing(false)
148
132
  }
149
133
  }
150
134
 
135
+ /**
136
+ * 只取数据,**不**顺手 switch。
137
+ *
138
+ * 旧实现在这里补一次 `/tasks switch <boundId>`(条件是"新 boundId 与内存里的不同"),
139
+ * 意图是刷新后让宿主 todo 跟随绑定任务。但那是多余的:宿主的 todo 清单是
140
+ * `sessionProjections` 里的 `todos` 单元(由 `todo/write` 事件折叠而来),重启/换标签页
141
+ * 都会从会话日志重建,不需要谁再推一次;而 switch 会 `session.append('todo/write')`,
142
+ * 于是"打开面板/切一次会话"就写一次会话历史(还顺手刷新任务的 lastActiveAt)。
143
+ * 真正的绑定动作都有明确入口:`select_task`、`/tasks switch`、面板卡片的切换按钮,
144
+ * 它们各自会推宿主清单(adoptStepsToSession),不需要巡检式补写。
145
+ */
146
+ const refresh = async (): Promise<void> => {
147
+ await withLock(() => runLine('/tasks'))
148
+ }
149
+
151
150
  const handleAction = async (verb: 'switch' | 'archive', taskId: string): Promise<void> => {
152
- if (syncing) return
153
- setSyncing(true)
154
- try {
155
- await runLine(`/tasks ${verb} ${taskId}`)
156
- } finally {
157
- setSyncing(false)
158
- }
151
+ await withLock(() => runLine(`/tasks ${verb} ${taskId}`))
159
152
  }
160
153
 
161
154
  // v0.5:任务卡内联记忆动作(confirm/promote/delete 于 /insight task 层),随后刷新任务数据
162
155
  const handleInsightTask = async (action: 'confirm' | 'promote' | 'delete', id: string): Promise<void> => {
163
- if (syncing) return
164
- setSyncing(true)
165
- try {
156
+ await withLock(async () => {
166
157
  await runLine(`/tasks insight ${action} task ${id}`)
167
- await refresh()
168
- } finally {
169
- setSyncing(false)
170
- }
171
- }
172
-
173
- const pushSteps = (taskId: string, steps: TaskStep[]): void => {
174
- void runLine(`/tasks todos ${JSON.stringify(steps.map((s) => ({ content: s.content, status: s.status })))}`)
158
+ await runLine('/tasks')
159
+ })
175
160
  }
176
161
 
177
162
  const cycleStatus = (taskId: string, index: number) => {
178
163
  const task = data.tasks.find((tt) => tt.id === taskId)
179
164
  if (!task) return
180
- const steps = task.steps || []
181
- const next = steps.map((s, i) => {
182
- if (i !== index) return s
183
- const cur = STATUS_CYCLE.indexOf(s.status)
184
- return { ...s, status: STATUS_CYCLE[(cur + 1) % STATUS_CYCLE.length] }
185
- })
186
- pushSteps(taskId, next)
165
+ const cur = STATUS_CYCLE.indexOf((task.steps || [])[index]?.status as (typeof STATUS_CYCLE)[number])
166
+ const next = STATUS_CYCLE[(cur + 1) % STATUS_CYCLE.length]
167
+ void withLock(() => runLine(`/tasks step ${taskId} ${index} ${next}`))
187
168
  }
188
169
 
189
170
  const commitStepText = (taskId: string, index: number, value: string) => {
@@ -192,19 +173,15 @@ function TaskPanelView({ ctx }: { ctx: any }) {
192
173
  if (!task) return
193
174
  const same = (task.steps || [])[index]?.content === trimmed
194
175
  if (same || !trimmed) return
195
- const next = (task.steps || []).map((s, i) => (i === index ? { ...s, content: trimmed } : s))
196
- pushSteps(taskId, next)
176
+ void withLock(() => runLine(`/tasks step-text ${taskId} ${index} ${JSON.stringify(trimmed)}`))
197
177
  }
198
178
 
199
179
  const reorderSteps = (taskId: string, fromIndex: number, toIndex: number) => {
200
180
  if (fromIndex === toIndex) return
201
181
  const task = data.tasks.find((tt) => tt.id === taskId)
202
182
  if (!task) return
203
- const steps = [...(task.steps || [])]
204
- const [moved] = steps.splice(fromIndex, 1)
205
- const targetIndex = toIndex > fromIndex ? toIndex - 1 : toIndex
206
- steps.splice(targetIndex, 0, moved)
207
- pushSteps(taskId, steps)
183
+ // 服务端按拖拽的 from/to 自己算落点;这里不再回写整份数组。
184
+ void withLock(() => runLine(`/tasks step-move ${taskId} ${fromIndex} ${toIndex}`))
208
185
  }
209
186
 
210
187
  const commitTitle = (taskId: string, value: string) => {
@@ -213,12 +190,12 @@ function TaskPanelView({ ctx }: { ctx: any }) {
213
190
  if (!task) return
214
191
  const same = task.title === trimmed
215
192
  if (same || !trimmed) return
216
- void runLine(`/tasks rename ${taskId} ${JSON.stringify(trimmed)}`)
193
+ void withLock(() => runLine(`/tasks rename ${taskId} ${JSON.stringify(trimmed)}`))
217
194
  }
218
195
 
219
196
  const expand = () => {
220
197
  uiActions.open()
221
- if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 30_000) {
198
+ if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 5_000) {
222
199
  void refresh()
223
200
  }
224
201
  }
@@ -233,6 +210,9 @@ function TaskPanelView({ ctx }: { ctx: any }) {
233
210
 
234
211
  const panelRef = useRef<HTMLDivElement>(null)
235
212
  const drag = useRef<{ dx: number; dy: number } | null>(null)
213
+ // 拖动期间位置只进本地 state;mouseup 才写 UI store(否则每个 mousemove 都同步写 localStorage)。
214
+ const [dragPos, setDragPos] = useState<{ x: number; y: number } | null>(null)
215
+ const dragPosRef = useRef<{ x: number; y: number } | null>(null)
236
216
 
237
217
  const handleDragStart = (e: React.MouseEvent) => {
238
218
  if (e.target !== e.currentTarget) return
@@ -245,40 +225,31 @@ function TaskPanelView({ ctx }: { ctx: any }) {
245
225
  const height = panelRef.current?.offsetHeight ?? 480
246
226
  const x = Math.max(8, Math.min(window.innerWidth - width - 8, ev.clientX - drag.current.dx))
247
227
  const y = Math.max(8, Math.min(window.innerHeight - 64, ev.clientY - drag.current.dy))
248
- uiActions.setPanelPosition({ x, y })
228
+ dragPosRef.current = { x, y }
229
+ setDragPos({ x, y })
249
230
  }
250
231
  const onUp = () => {
251
232
  drag.current = null
252
233
  window.removeEventListener('mousemove', onMove)
253
234
  window.removeEventListener('mouseup', onUp)
235
+ if (dragPosRef.current) uiActions.setPanelPosition(dragPosRef.current)
236
+ dragPosRef.current = null
237
+ setDragPos(null)
254
238
  }
255
239
  window.addEventListener('mousemove', onMove)
256
240
  window.addEventListener('mouseup', onUp)
257
241
  }
258
242
 
259
- // 会话切换时仅同步数据,不自动打开面板
260
- useEffect(() => {
261
- if (!sessionId) return
262
- // 仅当面板已打开时才自动刷新
263
- if (!ui.closed) {
264
- void refresh()
265
- }
266
- }, [sessionId])
267
-
268
- // 监听模型工具请求打开面板
243
+ // 只在面板打开、或切回任务页时补一次数据;切到记忆页不发任务命令。
244
+ // 命令节点本身由 TaskCommandNode 隐藏,所以这次补数据不会在对话里留下可见行;
245
+ // 但切回任务页必须刷新,否则刚在记忆页确认/提升的草稿状态会一直显示旧值。
246
+ const refreshRef = useRef<() => void>(() => {})
247
+ refreshRef.current = () => { void refresh() }
269
248
  useEffect(() => {
270
- const ctxWithEvents = ctx
271
- const handler = () => {
272
- uiActions.open()
273
- if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 30_000) {
274
- void refresh()
275
- }
276
- }
277
- ctxWithEvents?.events?.on?.('dsh:task-panel:show', handler)
278
- return () => {
279
- ctxWithEvents?.events?.off?.('dsh:task-panel:show', handler)
280
- }
281
- }, [ctx, uiActions, data.lastUpdate, syncedAt, refresh])
249
+ if (ui.closed || !sessionId || ui.view !== 'task') return
250
+ if (Date.now() - Math.max(data.lastUpdate, syncedAt) < 5_000) return
251
+ refreshRef.current()
252
+ }, [ui.closed, ui.view, sessionId])
282
253
 
283
254
  // 彻底隐藏:不渲染任何东西
284
255
  if (ui.closed) {
@@ -314,7 +285,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
314
285
  <div
315
286
  className={css.panel}
316
287
  ref={panelRef}
317
- style={{ left: ui.panelPosition.x, top: ui.panelPosition.y }}
288
+ style={{ left: (dragPos ?? ui.panelPosition).x, top: (dragPos ?? ui.panelPosition).y }}
318
289
  data-theme={style === 'native' ? undefined : style}
319
290
  >
320
291
  <div className={css.dragHandle} onMouseDown={handleDragStart} title={showHints ? t('task.drag') : undefined}>
@@ -411,7 +382,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
411
382
  {syncError && <div className={css.notice}>{t('panel.sync-failed')}: {syncError}</div>}
412
383
 
413
384
  {view !== 'task' ? (
414
- <MemoryView ctx={ctx} sessionId={sessionId} scope={view as InsightScope} boundTaskId={data.boundTaskId} showHints={showHints} t={t} />
385
+ <MemoryView ctx={ctx} sessionId={sessionId} scope={view as InsightScope} root={data.root ?? null} boundTaskId={data.boundTaskId} showHints={showHints} t={t} />
415
386
  ) : activeTasks.length === 0 ? (
416
387
  <div className={css.emptyState}>
417
388
  <p className={css.emptyTitle}>{t('panel.empty')}</p>
@@ -89,13 +89,33 @@ function registerSlashSource(ctx: any): void {
89
89
  * @param ctx - client 根上下文
90
90
  */
91
91
  function registerTaskPanel(ctx: any): void {
92
- const mount = (slots: any): void => {
92
+ const mount = (slots: any, effect?: (fn: () => () => void) => void): void => {
93
93
  if (!slots || typeof slots.inject !== 'function') {
94
94
  console.warn(`[${NS}] host has no slots service — task panel disabled`)
95
95
  return
96
96
  }
97
+ // 每个 register 都挂到 effect 上:HMR/禁用再启用时先释放旧注册,否则同 id 重复注册会抛。
98
+ const keep = (off: unknown): void => {
99
+ if (typeof off !== 'function') return
100
+ const dispose = () => {
101
+ try {
102
+ off()
103
+ } catch {
104
+ // 宿主已经拆掉这个槽:忽略
105
+ }
106
+ }
107
+ if (typeof effect === 'function') effect(() => dispose)
108
+ }
109
+ const register = (spec: object, component: any): void => {
110
+ try {
111
+ keep(slots.register(spec, component))
112
+ } catch (err) {
113
+ console.warn(`[${NS}] slot registration failed:`, err)
114
+ }
115
+ }
116
+
97
117
  try {
98
- slots.inject('shell.overlay', () => slots.register(
118
+ slots.inject('shell.overlay', () => register(
99
119
  {
100
120
  name: 'shell.overlay',
101
121
  id: 'dsh-project-memory-task-panel',
@@ -109,7 +129,7 @@ function registerTaskPanel(ctx: any): void {
109
129
  // 合并后只剩一条用户命令 /tasks(子动词都记在同一个命令名下)。
110
130
  const nodeKeys = ['tasks']
111
131
  for (const key of nodeKeys) {
112
- slots.inject('conversation.chat.commandview', () => slots.register(
132
+ slots.inject('conversation.chat.commandview', () => register(
113
133
  { name: 'conversation.chat.commandview', key },
114
134
  TaskCommandNode
115
135
  ))
@@ -118,7 +138,7 @@ function registerTaskPanel(ctx: any): void {
118
138
  // 工具调用视图:`show_task_panel` 的唯一实际效果就是开面板,而面板状态在浏览器侧;
119
139
  // 宿主进程碰不到它(宿主契约里 `ToolRunContext` 没有 `ctx`)。认领这个**工具名**后,
120
140
  // 工具结果一渲染就把面板打开 —— 见 ShowTaskPanelNode.tsx。
121
- registerShowTaskPanelView(slots)
141
+ registerShowTaskPanelView(slots, keep)
122
142
  } catch (err) {
123
143
  console.warn(`[${NS}] task panel registration failed:`, err)
124
144
  }
@@ -126,13 +146,13 @@ function registerTaskPanel(ctx: any): void {
126
146
 
127
147
  if (typeof ctx?.inject === 'function') {
128
148
  try {
129
- ctx.inject(['slots'], (scope: any) => mount(scope?.slots ?? service(ctx, 'slots')))
149
+ ctx.inject(['slots'], (scope: any) => mount(scope?.slots ?? service(ctx, 'slots'), scope?.effect))
130
150
  return
131
151
  } catch (err) {
132
152
  console.warn(`[${NS}] slots injection failed:`, err)
133
153
  }
134
154
  }
135
- mount(service(ctx, 'slots'))
155
+ mount(service(ctx, 'slots'), typeof ctx?.effect === 'function' ? ctx.effect.bind(ctx) : undefined)
136
156
  }
137
157
 
138
158
  /**
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 客户端命令调用层:所有 `remote.commands.execute` 只走这里。
3
+ *
4
+ * 三件事必须集中在一处,否则每个调用点都会各漏一项:
5
+ * - 超时/取消(宿主 RPC 不返回时不能把面板永久锁死);
6
+ * - 信封解析(宿主 `{ok:false,error}` 与 `{ok:true,value}` 是两种形状);
7
+ * - 错误归一(调用点只关心 ok/text/error,不重复猜)。
8
+ */
9
+ import { service } from './services.ts'
10
+
11
+ export interface InvokeResult {
12
+ ok: boolean
13
+ text: string
14
+ error?: string
15
+ }
16
+
17
+ function errorText(value: unknown): string {
18
+ if (typeof value === 'string') return value
19
+ if (value && typeof value === 'object') {
20
+ const record = value as { message?: unknown; code?: unknown }
21
+ if (typeof record.message === 'string' && record.message) return record.message
22
+ if (typeof record.code === 'string' && record.code) return record.code
23
+ }
24
+ return ''
25
+ }
26
+
27
+ /**
28
+ * 执行一条 `/tasks` 命令。
29
+ * @param ctx client 上下文(服务一律软探测)
30
+ * @param sessionId 当前会话;为空表示没有可用数据通道
31
+ * @param line 完整命令行(以 `/tasks` 开头)
32
+ * @param timeoutMs 超时;到点 abort,调用方拿到可重试的错误态
33
+ */
34
+ export async function invokeCommand(
35
+ ctx: any,
36
+ sessionId: string | null,
37
+ line: string,
38
+ timeoutMs = 15_000,
39
+ ): Promise<InvokeResult> {
40
+ const commands = service(ctx, 'remote.commands')
41
+ if (!sessionId || !commands || typeof commands.execute !== 'function') {
42
+ return { ok: false, text: '', error: 'no-channel' }
43
+ }
44
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
45
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
46
+ try {
47
+ const response = await commands.execute(sessionId, line, [], controller?.signal)
48
+ const envelope = response && typeof response === 'object' ? response as { ok?: boolean; value?: any; error?: unknown } : null
49
+ if (envelope && envelope.ok === false) {
50
+ return { ok: false, text: '', error: errorText(envelope.error) || 'command rejected' }
51
+ }
52
+ const execution = envelope && 'value' in envelope ? envelope.value : envelope
53
+ if (execution === undefined || execution === null) {
54
+ return { ok: false, text: '', error: 'unknown or malformed command' }
55
+ }
56
+ const result = execution.result ?? execution
57
+ if (result?.kind === 'error') {
58
+ return { ok: false, text: '', error: String(result.text ?? 'command error') }
59
+ }
60
+ return { ok: true, text: typeof result?.text === 'string' ? result.text : '' }
61
+ } catch (err) {
62
+ const aborted = controller?.signal.aborted === true
63
+ return { ok: false, text: '', error: aborted ? 'command timed out' : String((err as { message?: unknown } | null | undefined)?.message ?? err) }
64
+ } finally {
65
+ if (timer !== null) clearTimeout(timer)
66
+ }
67
+ }
@@ -4,6 +4,7 @@
4
4
  * - 无 UI 状态,无 localStorage,纯内存 + BroadcastChannel 同步
5
5
  */
6
6
  import { useSyncExternalStore } from 'react'
7
+ import { broadcastAppliesTo, payloadRoot } from './task-scope.js'
7
8
 
8
9
  export interface TaskStep {
9
10
  content: string
@@ -37,6 +38,8 @@ export interface TaskPayload {
37
38
  tasks: Task[]
38
39
  boundId: string | null
39
40
  archived: number
41
+ /** 项目根。旧宿主没有这个键(null):跨标签页同步在未知根时退回"只按会话"处理。 */
42
+ root?: string | null
40
43
  }
41
44
 
42
45
  export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
@@ -52,7 +55,12 @@ export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
52
55
  try {
53
56
  const data = JSON.parse(jsonBlock)
54
57
  if (!Array.isArray(data.tasks)) return null
55
- return { tasks: data.tasks, boundId: data.boundId ?? null, archived: data.archived ?? 0 }
58
+ return {
59
+ tasks: data.tasks,
60
+ boundId: data.boundId ?? null,
61
+ archived: data.archived ?? 0,
62
+ root: payloadRoot(data.root),
63
+ }
56
64
  } catch {
57
65
  return null
58
66
  }
@@ -62,6 +70,8 @@ interface TaskDataState {
62
70
  tasks: Task[]
63
71
  boundTaskId: string | null
64
72
  archivedCount: number
73
+ /** 这份数据的项目根:广播按它做作用域,避免多项目标签页互相覆盖。 */
74
+ root: string | null
65
75
  lastUpdate: number
66
76
  }
67
77
 
@@ -71,6 +81,7 @@ let dataState: TaskDataState = {
71
81
  tasks: [],
72
82
  boundTaskId: null,
73
83
  archivedCount: 0,
84
+ root: null,
74
85
  lastUpdate: 0,
75
86
  }
76
87
 
@@ -84,31 +95,36 @@ function setDataState(next: TaskDataState | ((prev: TaskDataState) => TaskDataSt
84
95
  tasks: Array.isArray(patch?.tasks) ? patch.tasks : [],
85
96
  boundTaskId: patch?.boundTaskId ?? null,
86
97
  archivedCount: typeof patch?.archivedCount === 'number' ? patch.archivedCount : 0,
98
+ root: payloadRoot(patch?.root),
87
99
  lastUpdate: typeof patch?.lastUpdate === 'number' ? patch.lastUpdate : 0,
88
100
  }
89
101
  for (const listener of dataListeners) listener()
90
102
  }
91
103
 
92
- function broadcastDataUpdate(tasks: Task[], archivedCount: number): void {
104
+ function broadcastDataUpdate(tasks: Task[], archivedCount: number, root: string | null): void {
93
105
  if (!SYNC_CHANNEL) return
94
106
  SYNC_CHANNEL.postMessage({
95
107
  type: 'PROJECT_TASKS_UPDATED',
96
- payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount },
108
+ payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount, root },
97
109
  })
98
110
  }
99
111
 
100
112
  if (SYNC_CHANNEL) {
101
113
  SYNC_CHANNEL.onmessage = (event) => {
102
114
  const msg = event.data
103
- if (msg?.type === 'PROJECT_TASKS_UPDATED' && msg.payload) {
104
- const { tasks, archivedCount } = msg.payload
105
- setDataState(prev => ({
106
- ...prev,
107
- tasks: Array.isArray(tasks) ? tasks : [],
108
- archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
109
- lastUpdate: Date.now(),
110
- }))
111
- }
115
+ if (msg?.type !== 'PROJECT_TASKS_UPDATED' || !msg.payload) return
116
+ const { tasks, archivedCount, root } = msg.payload
117
+ // 频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个),所以**必须**按项目根过滤:
118
+ // 否则在 A 项目点一下刷新,B 项目的标签页面板就被贴上 A 的任务列表(而它还保留自己的
119
+ // boundTaskId,看起来像"绑定丢了")。两侧都已知根且不同 → 丢弃;本页还不知道根(还没
120
+ // 同步过)→ 也丢弃,让它自己那一次 /tasks 决定归属,不先借别人的数据。
121
+ if (!broadcastAppliesTo(dataState.root, root)) return
122
+ setDataState(prev => ({
123
+ ...prev,
124
+ tasks: Array.isArray(tasks) ? tasks : [],
125
+ archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
126
+ lastUpdate: Date.now(),
127
+ }))
112
128
  }
113
129
  }
114
130
 
@@ -121,22 +137,25 @@ export const taskDataStore = {
121
137
  return dataState
122
138
  },
123
139
  actions: {
124
- setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number }): void {
140
+ setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number; root?: string | null }): void {
125
141
  const nextTasks = payload.tasks || []
126
142
  const nextArchived = payload.archivedCount ?? 0
143
+ const nextRoot = payloadRoot(payload.root)
127
144
  setDataState({
128
145
  tasks: nextTasks,
129
146
  boundTaskId: payload.boundTaskId ?? null,
130
147
  archivedCount: nextArchived,
148
+ root: nextRoot,
131
149
  lastUpdate: Date.now(),
132
150
  })
133
- broadcastDataUpdate(nextTasks, nextArchived)
151
+ broadcastDataUpdate(nextTasks, nextArchived, nextRoot)
134
152
  },
135
153
  reset(): void {
136
154
  setDataState({
137
155
  tasks: [],
138
156
  boundTaskId: null,
139
157
  archivedCount: 0,
158
+ root: null,
140
159
  lastUpdate: 0,
141
160
  })
142
161
  },
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 跨标签页任务广播的**项目作用域**判定(纯函数,无 React / 无 BroadcastChannel 依赖)。
3
+ *
4
+ * 为什么需要它:同步频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个
5
+ * `dsh-pm-tasks-data`),而消息体只带任务数组。没有作用域判定时,在 A 项目点一下刷新,
6
+ * B 项目的标签页面板就会被贴上 A 的任务列表——它自己保留着 B 的 `boundTaskId`,
7
+ * 于是表现为"绑定莫名丢了"。频道名不能按项目拆:项目根是数据到达后才知道的,
8
+ * 而 `new BroadcastChannel` 在模块加载期就要定名。
9
+ *
10
+ * 判据刻意**严格**:消息里没有根、或本页还没确定根,都不接受。
11
+ * - 无根:老宿主/老 bundle 的载荷,宁可不同步也不猜;
12
+ * - 本页未知根:它自己那一次 `/tasks` 会决定归属,不先借别人的数据(避免短暂显示错项目)。
13
+ * 两侧都已知且相等时才接受——这正是"同一项目的两个标签页"。
14
+ *
15
+ * @param {string|null|undefined} localRoot - 本页当前数据的项目根(未同步过为 null)
16
+ * @param {unknown} incomingRoot - 广播消息里的项目根
17
+ * @returns {boolean} true = 这条广播属于同一个项目,可以套用
18
+ */
19
+ export function broadcastAppliesTo(localRoot, incomingRoot) {
20
+ if (typeof incomingRoot !== 'string' || incomingRoot === '') return false
21
+ if (typeof localRoot !== 'string' || localRoot === '') return false
22
+ return localRoot === incomingRoot
23
+ }
24
+
25
+ /**
26
+ * 从 `/tasks` 载荷里取项目根(旧宿主没有该键)。
27
+ * @param {unknown} value - `payload.root`
28
+ * @returns {string|null} 非空字符串才算根
29
+ */
30
+ export function payloadRoot(value) {
31
+ return typeof value === 'string' && value !== '' ? value : null
32
+ }
@@ -43,6 +43,19 @@ function defaultPosition(): { x: number; y: number } {
43
43
  return { x: 0, y: 0 }
44
44
  }
45
45
 
46
+ /** 位置必须留在视口内:换小屏/拔掉外接屏后,持久化的坐标可能已经看不见。 */
47
+ function clampPosition(value: unknown): { x: number; y: number } {
48
+ if (typeof window === 'undefined') return defaultPosition()
49
+ const pos = value as { x?: unknown; y?: unknown } | null | undefined
50
+ const x = Number(pos?.x)
51
+ const y = Number(pos?.y)
52
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return defaultPosition()
53
+ return {
54
+ x: Math.max(8, Math.min(x, window.innerWidth - 80)),
55
+ y: Math.max(8, Math.min(y, window.innerHeight - 40)),
56
+ }
57
+ }
58
+
46
59
  /**
47
60
  * 启动时的初始状态:
48
61
  * - closed 恒为 true(不读取 localStorage 的 closed),刷新后面板隐藏;
@@ -56,7 +69,7 @@ function getDefaultUIState(): TaskUIState {
56
69
  const parsed = JSON.parse(saved)
57
70
  return {
58
71
  expandedTaskIds: Array.isArray(parsed.expandedTaskIds) ? parsed.expandedTaskIds : [],
59
- panelPosition: parsed.panelPosition ?? defaultPosition(),
72
+ panelPosition: clampPosition(parsed.panelPosition),
60
73
  minimized: parsed.minimized !== false,
61
74
  closed: true,
62
75
  theme: typeof parsed.theme === 'string' ? parsed.theme : 'native',
@@ -114,7 +127,7 @@ export const taskUIStore = {
114
127
  setUIState({ ...uiState, expandedTaskIds: taskIds })
115
128
  },
116
129
  setPanelPosition(pos: { x: number; y: number }): void {
117
- setUIState({ ...uiState, panelPosition: pos })
130
+ setUIState({ ...uiState, panelPosition: clampPosition(pos) })
118
131
  },
119
132
  open(): void {
120
133
  setUIState({ ...uiState, minimized: false, closed: false })
@@ -4,7 +4,7 @@
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, INSIGHT_KINDS } from '../insight-store.js'
7
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, INSIGHT_KINDS } from '../insight-store.js'
8
8
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
10
 
@@ -150,6 +150,8 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
150
150
  return { ok: true, text: `已审核:${insight.title}` }
151
151
  }
152
152
  if (act === 'delete') {
153
+ // 面板删除与 forget 同一套留痕:真删,但最近 5 条可在同目录 deleted.json 里找回来。
154
+ recordDeleted({ store, globalStore: gs }, [{ ...insight, home: 'task', taskId: task.id }])
153
155
  task.insights = (task.insights || []).filter((i) => i.id !== id)
154
156
  store.markTasksDirty()
155
157
  return { ok: true, text: `已删除任务级条目 ${id}` }
@@ -191,6 +193,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
191
193
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
192
194
  }
193
195
  if (act === 'delete') {
196
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'project' }])
194
197
  items.splice(idx, 1)
195
198
  store.replaceInsightItems(items)
196
199
  return { ok: true, text: `已删除 project 条目 ${id}` }
@@ -243,6 +246,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
243
246
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
244
247
  }
245
248
  if (act === 'delete') {
249
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'global' }])
246
250
  items.splice(idx, 1)
247
251
  gs.markDirty()
248
252
  return { ok: true, text: `已删除 global 条目 ${id}` }