nx-kv 0.66.2 → 0.66.3

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 (95) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/assets/nx-kv/references/A03-/346/226/207/346/241/243/344/270/216/345/275/222/345/261/236.md +1 -1
  3. package/package.json +1 -1
  4. package/src/core/attachmentdb/ids.ts +14 -1
  5. package/src/core/attachmentdb/query.ts +0 -38
  6. package/src/core/attachmentdb/repo.ts +98 -0
  7. package/src/core/attachmentdb.ts +5 -1
  8. package/src/core/db/migrations/index.ts +2 -0
  9. package/src/core/db/migrations/v15.sql +88 -0
  10. package/src/core/db/version.ts +4 -1
  11. package/src/modules/claim/assemble.ts +0 -5
  12. package/src/modules/claim/host.ts +1 -3
  13. package/src/modules/claim/preview.ts +0 -1
  14. package/src/modules/docs/actions/docs-detach.ts +1 -2
  15. package/src/modules/docs/attach.ts +3 -17
  16. package/src/modules/docs/render.ts +4 -13
  17. package/src/modules/localtask/actions/localtask-attach.ts +4 -2
  18. package/src/modules/localtask/actions/localtask-config.ts +2 -11
  19. package/src/modules/localtask/actions/localtask-detach.ts +1 -3
  20. package/src/modules/localtask/infra/repo/settings.ts +1 -9
  21. package/src/modules/localtask/lifecycle/task-templates.ts +0 -13
  22. package/src/modules/localtask/lifecycle/topics.ts +3 -6
  23. package/src/modules/localtask/ops/attach-resource.ts +46 -4
  24. package/src/modules/localtask/ops/attach-template.ts +73 -3
  25. package/src/modules/localtask/ops/attach.ts +45 -18
  26. package/src/modules/localtask/ui/action-render.ts +3 -12
  27. package/src/modules/promptplug/compose.ts +1 -3
  28. package/src/modules/promptplug/plugins/attachment.ts +56 -6
  29. package/src/modules/promptplug/plugins/context.ts +11 -2
  30. package/src/modules/promptplug/template-store.ts +25 -3
  31. package/src/shared/prompt-blocks.ts +2 -23
  32. package/src/web/frontend/api/cli-tree.json +4 -4
  33. package/src/web/frontend/api/client.generated.ts +8 -8
  34. package/src/web/frontend/api/tasks.ts +117 -0
  35. package/src/web/frontend/components/Introduction/index.tsx +50 -3
  36. package/src/web/frontend/components/Introduction/style.css +6 -0
  37. package/src/web/frontend/components/Introduction/use-intro.ts +25 -0
  38. package/src/web/frontend/components/md/attachments/attach-area.tsx +9 -11
  39. package/src/web/frontend/components/md/attachments/attach-common.ts +12 -5
  40. package/src/web/frontend/components/md/attachments/attach-modal.tsx +54 -9
  41. package/src/web/frontend/components/md/attachments/attach-repo-pick.tsx +48 -0
  42. package/src/web/frontend/components/sidebar/task-children.tsx +14 -11
  43. package/src/web/frontend/{page/dir → components/task-panel}/dag-editor.tsx +1 -1
  44. package/src/web/frontend/components/task-panel/task-ops.ts +299 -0
  45. package/src/web/frontend/components/task-panel/task-page.tsx +495 -0
  46. package/src/web/frontend/components/tool-acts/modules.ts +3 -0
  47. package/src/web/frontend/page/dir/api.ts +4 -108
  48. package/src/web/frontend/page/dir/index.tsx +148 -331
  49. package/src/web/frontend/page/dir/task-board-section.tsx +3 -0
  50. package/src/web/frontend/page/dir/task-dock-panel.tsx +1 -1
  51. package/src/web/frontend/page/dir/task.tsx +1 -1
  52. package/src/web/frontend/page/doc/doc-dock.tsx +1 -1
  53. package/src/web/frontend/page/group/api.ts +3 -21
  54. package/src/web/frontend/page/group/group-project-memo.ts +41 -0
  55. package/src/web/frontend/page/group/index.tsx +287 -426
  56. package/src/web/frontend/page/settings/api.ts +1 -2
  57. package/src/web/frontend/page/settings/prompt-templates-section.tsx +12 -44
  58. package/src/web/public/assets/{bar-Dy_QDX2h.js → bar-D7cWe7Kp.js} +1 -1
  59. package/src/web/public/assets/{composer-launch-B7DH53Yf.js → composer-launch--nJGFG35.js} +1 -1
  60. package/src/web/public/assets/{composer-panel-Cj1J16r-.js → composer-panel-Dhivt7UJ.js} +1 -1
  61. package/src/web/public/assets/{dag-DXRPHVl8.js → dag-DUhHxgTk.js} +1 -1
  62. package/src/web/public/assets/dir-CkYGYT9e.js +1 -0
  63. package/src/web/public/assets/doc-DgYKv2wo.css +1 -0
  64. package/src/web/public/assets/doc-QBHQi1EV.js +6 -0
  65. package/src/web/public/assets/group-CfJxWA7V.js +1 -0
  66. package/src/web/public/assets/group-project-memo-G-O6sPRw.js +1 -0
  67. package/src/web/public/assets/index-ByAPGidL.js +3 -0
  68. package/src/web/public/assets/{list-filter-CWxiOSg_.js → list-search-B2S2g8kn.js} +1 -1
  69. package/src/web/public/assets/md-history-DdM6P9Gq.js +47 -0
  70. package/src/web/public/assets/{progress-MPse2JLQ.js → progress-BVpSy-uF.js} +1 -1
  71. package/src/web/public/assets/refs-CCZgGPlL.js +2 -0
  72. package/src/web/public/assets/reopen-text-BC9a8KOp.js +13 -0
  73. package/src/web/public/assets/{repo-form-modal-CNLYR12c.js → repo-form-modal-D8WabN0R.js} +1 -1
  74. package/src/web/public/assets/{repos-BGx-yAXd.js → repos-V5xb5Kz-.js} +9 -9
  75. package/src/web/public/assets/settings-CAOSCF3E.js +1 -0
  76. package/src/web/public/assets/task-BwWlNP0i.js +13 -0
  77. package/src/web/public/assets/task-ops-DZgza5eZ.js +2 -0
  78. package/src/web/public/assets/task-utils--WIpAwUx.js +1 -0
  79. package/src/web/public/assets/{templates-Co1Qb1aA.js → templates-6ClSnYJN.js} +3 -3
  80. package/src/web/public/assets/{tool-bar-D5wLBLRl.js → tool-bar-BYdfBQeo.js} +1 -1
  81. package/src/web/public/assets/use-rail-drag-BMXJ48je.js +1 -0
  82. package/src/web/public/index.html +8 -8
  83. package/src/web/frontend/page/dir/landing.tsx +0 -553
  84. package/src/web/public/assets/dir-_M1ciSxM.js +0 -3
  85. package/src/web/public/assets/doc-Iuxssa-b.css +0 -1
  86. package/src/web/public/assets/doc-_iteSM2X.js +0 -6
  87. package/src/web/public/assets/get-loop-modal-DlAfqJMz.js +0 -2
  88. package/src/web/public/assets/group-CH8qe-eg.js +0 -1
  89. package/src/web/public/assets/index-Cui4IuGj.js +0 -3
  90. package/src/web/public/assets/md-history-Bj790fdn.js +0 -46
  91. package/src/web/public/assets/refs-DiIPoqnJ.js +0 -2
  92. package/src/web/public/assets/settings-Pt4YgGdY.js +0 -1
  93. package/src/web/public/assets/task-DOIIpQ4X.js +0 -13
  94. package/src/web/public/assets/task-utils-CJfMODCP.js +0 -13
  95. package/src/web/public/assets/use-rail-drag-CNOHXWng.js +0 -1
@@ -12,6 +12,9 @@ import type { ClipboardEvent, ComponentType, ReactNode } from 'react';
12
12
  import { Modal } from '../../popup/index.jsx';
13
13
  import { api } from '../../../api/client.js';
14
14
  import { clipboardFiles, droppedFiles, readableName, uploadOne } from '../../attach/upload.js';
15
+ import { filterTasks } from '../../../modules/board/task-search.js';
16
+ import { filterByKeyword } from '../../../modules/list-filter.js';
17
+ import AttachRepoPick from './attach-repo-pick.js';
15
18
  import StatusTag from '../../status-tag/index.jsx';
16
19
  import {
17
20
  attachBodyOf,
@@ -39,13 +42,13 @@ const ModalBox = Modal as unknown as ComponentType<{
39
42
  }>;
40
43
 
41
44
  const SOURCE_LABEL: Record<PendingItem['source'], string> = {
42
- file: '本机文件', folder: '本地文件夹', url: '外部链接', task: '任务引用', ref: '文档引用',
45
+ file: '本机文件', folder: '本地文件夹', url: '外部链接', task: '任务引用', ref: '文档引用', repo: '参考仓库',
43
46
  };
44
47
 
45
48
  /** 待确认清单的一条(本地态,不是服务端形状)。 */
46
49
  interface PendingItem {
47
50
  key: string;
48
- source: 'file' | 'folder' | 'url' | 'task' | 'ref';
51
+ source: 'file' | 'folder' | 'url' | 'task' | 'ref' | 'repo';
49
52
  file?: File;
50
53
  fileId?: string;
51
54
  name: string;
@@ -56,6 +59,8 @@ interface PendingItem {
56
59
  folder?: string;
57
60
  seq?: number;
58
61
  docRef?: string;
62
+ /** #184 仓库 key(source='repo') */
63
+ repoKey?: string;
59
64
  note?: string;
60
65
  inline?: boolean;
61
66
  status: 'pending' | 'uploading' | 'error';
@@ -100,7 +105,7 @@ export default function AttachModal({
100
105
  hostKey,
101
106
  hostCwd,
102
107
  refId,
103
- allow = { file: true, url: true, folder: true, task: false, ref: false },
108
+ allow = { file: true, url: true, folder: true, task: false, ref: false, repo: false },
104
109
  taskOptions = [],
105
110
  docOptions = null,
106
111
  replaceAttachment = null,
@@ -118,6 +123,9 @@ export default function AttachModal({
118
123
  const [taskSearch, setTaskSearch] = useState('');
119
124
  const [refSearch, setRefSearch] = useState('');
120
125
  const [docs, setDocs] = useState<DocOption[]>(docOptions || []);
126
+ // #184:参考仓库列表(只用于挂指针,交付时强制参考源码)
127
+ const [repos, setRepos] = useState<Array<{ key: string; name: string; desc?: string; type?: string; path?: string }>>([]);
128
+ const [repoSearch, setRepoSearch] = useState('');
121
129
  const fileRef = useRef<HTMLInputElement | null>(null);
122
130
  const dropRef = useRef<HTMLDivElement | null>(null);
123
131
 
@@ -137,6 +145,7 @@ export default function AttachModal({
137
145
  setFolderErr('');
138
146
  setTaskSearch('');
139
147
  setRefSearch('');
148
+ setRepoSearch('');
140
149
  // 焦点落在拖拽区:不点任何地方直接 Ctrl/⌘+V 也能接住剪贴板里的截图
141
150
  const t = setTimeout(() => dropRef.current?.focus(), 0);
142
151
  return () => clearTimeout(t);
@@ -164,6 +173,23 @@ export default function AttachModal({
164
173
  return () => { alive = false; };
165
174
  }, [open, docOptions, allow.ref]);
166
175
 
176
+ useEffect(() => {
177
+ if (!open || !allow.repo) return undefined;
178
+ let alive = true;
179
+ api<any>('/api/repos').then((r) => {
180
+ if (!alive) return;
181
+ const arr = Array.isArray(r) ? r : (r && Array.isArray(r.repos) ? r.repos : []);
182
+ setRepos(arr.map((x: any) => ({
183
+ key: String(x.key || x.id || ''),
184
+ name: String(x.name || x.key || ''),
185
+ desc: String(x.desc || ''),
186
+ type: String(x.type || ''),
187
+ path: String(x.path || ''),
188
+ })).filter((x: { key: string }) => !!x.key));
189
+ }).catch(() => { /* 拉不到就只显示空态 */ });
190
+ return () => { alive = false; };
191
+ }, [open, allow.repo]);
192
+
167
193
  const addFiles = (list: FileList | File[] | null | undefined) => {
168
194
  if (!allow.file) return;
169
195
  const files = [...(list || [])].filter((f) => f && f.size > 0);
@@ -278,7 +304,7 @@ export default function AttachModal({
278
304
  await ep.attach(attachBodyOf({ ...it, fileId, note: it.note || replaceNote || '' }, host));
279
305
  // #168:换指向——新绑定挂好后解除旧的那条(旧资源进孤儿池,不删字节)
280
306
  if (replaceAttachment) {
281
- try { await ep.detach(replaceAttachment, false); } catch { /* 旧边解不掉也不影响新绑定 */ }
307
+ try { await ep.detach(replaceAttachment); } catch { /* 旧边解不掉也不影响新绑定 */ }
282
308
  }
283
309
  setItems((prev) => prev.filter((x) => x.key !== it.key));
284
310
  return true;
@@ -310,12 +336,21 @@ export default function AttachModal({
310
336
  };
311
337
 
312
338
  const taskList = useMemo(() => {
313
- const q = taskSearch.trim().toLowerCase();
314
- return taskOptions
315
- .filter((t) => String(t.id) !== String(hostId))
316
- .filter((t) => (q ? `${t.id} ${t.text || ''}`.toLowerCase().includes(q) : true))
317
- .slice(0, 12);
339
+ // #183:任务搜索与 topic 页共用 modules/board/task-search.ts 的同一份引擎
340
+ // (空格分词 AND / 剥 frontmatter / 通配 / 编号前缀),弹窗不再自己写 includes。
341
+ const pool = taskOptions.filter((t) => String(t.id) !== String(hostId));
342
+ return filterTasks(pool, taskSearch).slice(0, 12);
318
343
  }, [taskOptions, taskSearch, hostId]);
344
+ const repoList = useMemo(() => filterByKeyword(repos, repoSearch, (r) => [r.name, r.key, r.desc]).slice(0, 12),
345
+ [repos, repoSearch]);
346
+ const addRepo = (r: { key: string; name: string }) => {
347
+ setItems((prev) => [
348
+ ...prev,
349
+ { key: nextKey(), source: 'repo', repoKey: r.key, name: r.name, size: 0, status: 'pending' },
350
+ ]);
351
+ setRepoSearch('');
352
+ };
353
+
319
354
  const refList = useMemo(() => {
320
355
  const q = refSearch.trim().toLowerCase();
321
356
  return docs
@@ -491,6 +526,16 @@ export default function AttachModal({
491
526
  </div>
492
527
  )}
493
528
 
529
+ {allow.repo && (
530
+ <AttachRepoPick
531
+ repos={repos}
532
+ list={repoList}
533
+ search={repoSearch}
534
+ onSearch={setRepoSearch}
535
+ onPick={addRepo}
536
+ />
537
+ )}
538
+
494
539
  {items.length ? (
495
540
  <div className="att-pending">
496
541
  <div className="att-pending-head">待确认清单</div>
@@ -0,0 +1,48 @@
1
+ // 「关联参考仓库」区块(#184):搜索已登记仓库 → 选中后挂指针(不走 folder)。
2
+ // 抽成组件是为了让 attach-modal 不因新增区块超行数门禁。
3
+ export interface RepoPickItem {
4
+ key: string;
5
+ name: string;
6
+ desc?: string;
7
+ type?: string;
8
+ path?: string;
9
+ }
10
+
11
+ export interface AttachRepoPickProps {
12
+ repos: RepoPickItem[];
13
+ list: RepoPickItem[];
14
+ search: string;
15
+ onSearch: (v: string) => void;
16
+ onPick: (r: RepoPickItem) => void;
17
+ }
18
+
19
+ export default function AttachRepoPick({ repos, list, search, onSearch, onPick }: AttachRepoPickProps) {
20
+ return (
21
+ <div className='att-pick'>
22
+ <div className='att-pick-head'>关联参考仓库(repo)</div>
23
+ <input
24
+ className='pp-input'
25
+ placeholder='搜索仓库名 / key / 描述'
26
+ value={search}
27
+ onChange={(e) => onSearch(e.target.value)}
28
+ onKeyDown={(e) => {
29
+ const first = list[0];
30
+ if (e.key === 'Enter' && first) { e.preventDefault(); onPick(first); }
31
+ }}
32
+ spellCheck='false'
33
+ />
34
+ {list.length ? (
35
+ <div className='att-pick-list'>
36
+ {list.map((r) => (
37
+ <button key={r.key} type='button' className='att-pick-item' onClick={() => onPick(r)}>
38
+ <span className='att-pick-main'>{r.name || r.key}</span>
39
+ <span className='att-pick-path'>{r.type === 'ref' ? '参考仓库' : '开发仓库'} · {r.key}</span>
40
+ </button>
41
+ ))}
42
+ </div>
43
+ ) : (
44
+ <div className='att-empty-inline'>{repos.length ? '没有匹配的仓库' : '还没有登记仓库'}</div>
45
+ )}
46
+ </div>
47
+ );
48
+ }
@@ -9,8 +9,9 @@
9
9
  // 显示序:**未完成(待领取)优先**(sortTasksForDisplay——追加序会把新任务
10
10
  // 埋在历史底下);长度:**不分页**——#181 去掉翻页控件后是全量铺开,但队列一长
11
11
  // (实测 68 条)侧栏就被任务子行灌满,树形导航彻底失效。
12
- // #188 用户口径「不要分页,显示……即可」:默认只铺前 8 条,尾部一行「…」收口,
13
- // 点「…」就地展开全部(再点收起)——既没有分页控件,也不把默认视野撑爆。
12
+ // #188 用户口径:默认铺 8 条,尾部「…还有 N 条」**点一次只多加载 10 条**(继续点继续加载),
13
+ // 不再一次铺开全部——队列很长时一次全展开照样把侧栏灌满。
14
+ // 另有「收起」把窗口还原到 8 条。
14
15
  import { useMemo, useState } from 'react';
15
16
  import { Icon } from '../icons.jsx';
16
17
  import { useToast } from '../toast/index.jsx';
@@ -29,8 +30,10 @@ import type { LocalTask } from '../../types.js';
29
30
  // 这里按实际契约声明一次——它毕业成强类型后此桥退化为恒等。
30
31
  const sortTasksForDisplayBridge = sortTasksForDisplay as unknown as (tasks: LocalTask[]) => LocalTask[];
31
32
 
32
- /** 侧栏默认铺开的任务子行条数(超出部分折成一行「…」,不分页)。 */
33
+ /** 侧栏默认铺开的任务子行条数。 */
33
34
  const SIDE_TASK_LIMIT = 8;
35
+ /** #188:点「…还有 N 条」时每次多加载几条。 */
36
+ const SIDE_TASK_STEP = 10;
34
37
 
35
38
  /** TaskChildren 入参。 */
36
39
  export interface TaskChildrenProps {
@@ -54,9 +57,9 @@ export default function TaskChildren({ row, onNavigate, refreshLocal }: TaskChil
54
57
  const base = row.type === 'global'
55
58
  ? '#/global'
56
59
  : `#/dir/${encodeURIComponent(row.topicKey || row.key)}`;
57
- // #188:默认只铺前 N 条,其余折成一行「…」;点它就地展开(再点收起),全程没有翻页控件。
58
- const [showAll, setShowAll] = useState(false);
59
- const shown = showAll ? tasks : tasks.slice(0, SIDE_TASK_LIMIT);
60
+ // #188:默认铺 8 条;「…还有 N 条」点一次多加载 10 条(分页式增量,不一次全铺)。
61
+ const [limit, setLimit] = useState(SIDE_TASK_LIMIT);
62
+ const shown = tasks.slice(0, limit);
60
63
  const rest = tasks.length - shown.length;
61
64
  return (
62
65
  <>
@@ -80,29 +83,29 @@ export default function TaskChildren({ row, onNavigate, refreshLocal }: TaskChil
80
83
  </span>
81
84
  </button>
82
85
  ))}
83
- {/* 「…」收口(#188):不打分页,只表示「还有」。点它就地展开,展开后给「收起」还原 */}
86
+ {/* 「…还有 N 条」:点一次只多加载 10 条(#188),不一次铺开全部 */}
84
87
  {rest > 0 && (
85
88
  <button
86
89
  type="button"
87
90
  className="trow child task-more"
88
- title={`还有 ${rest} 条任务没铺开(点开看全部,不分页)`}
91
+ title={`还有 ${rest} 条任务没铺开——点一次多加载 ${Math.min(SIDE_TASK_STEP, rest)} 条`}
89
92
  onClick={(e) => {
90
93
  e.stopPropagation();
91
- setShowAll(true);
94
+ setLimit((n) => n + SIDE_TASK_STEP);
92
95
  }}
93
96
  >
94
97
  <span className="gico"><Icon name="dots" size={12} /></span>
95
98
  <span className="nm">…还有 {rest} 条</span>
96
99
  </button>
97
100
  )}
98
- {showAll && tasks.length > SIDE_TASK_LIMIT && (
101
+ {limit > SIDE_TASK_LIMIT && (
99
102
  <button
100
103
  type="button"
101
104
  className="trow child task-more"
102
105
  title="收起,只留前几条"
103
106
  onClick={(e) => {
104
107
  e.stopPropagation();
105
- setShowAll(false);
108
+ setLimit(SIDE_TASK_LIMIT);
106
109
  }}
107
110
  >
108
111
  <span className="gico"><Icon name="chevron" size={12} /></span>
@@ -10,7 +10,7 @@
10
10
  // UI 与其对齐:开闸门即清空并禁用上游段。
11
11
  import { useState } from 'react';
12
12
  import type { Dispatch, ReactNode, SetStateAction } from 'react';
13
- import { Modal as ModalRaw } from '../../components/popup/index.jsx';
13
+ import { Modal as ModalRaw } from '../popup/index.jsx';
14
14
  import { titleFromMd } from '../../modules/md/md-parse.js';
15
15
  import { reaches as reachesVia } from '../../../../shared/graph.js';
16
16
  import type { LocalTask } from '../../types.js';
@@ -0,0 +1,299 @@
1
+ // 任务操作模板(#251):从目录任务页抽出的「行尾 / 批量」动作,两个页面共用。
2
+ //
3
+ // 抽离口径:**动作本身(弹窗文案 / 接口调用顺序 / 提示语 / 文档落库)一份**,
4
+ // 只有「任务在哪个队列」随页面变化——所以每个动作都收一个 scope
5
+ // ({ cwd } 目录队列 或 { key } 全局池)。组页的行分属不同成员队列,由调用方按行
6
+ // 解析出 scope 再传进来,动作层不需要知道「组」这件事。
7
+ //
8
+ // 目录页(page/dir)与组页(page/group)都只做接线,不再各写一遍这些流程。
9
+ import {
10
+ addTask,
11
+ cancelManyTasks,
12
+ closeManyTasks,
13
+ findTaskItem,
14
+ patchTaskItem,
15
+ postReopen,
16
+ removeManyTasks,
17
+ removeTaskItem,
18
+ setPlanStatus,
19
+ } from '../../api/tasks.js';
20
+ import type { TaskScope } from '../../api/tasks.js';
21
+ import { FEEDBACK_HEADING, PLAIN_FEEDBACK_HEADING, buildReopenText } from '../../modules/board/reopen-text.js';
22
+ import { docIdOf, saveDoc, scopeOf } from '../../modules/md/doc-store.js';
23
+ import type { DialogFn } from '../../components/popup/index.js';
24
+ import type { LocalTask } from '../../types.js';
25
+
26
+ /** 动作层需要的外部能力(两页各自把自己的 dialog / toast / 刷新递进来)。 */
27
+ export interface TaskOpsDeps {
28
+ dialog: DialogFn;
29
+ toast: (msg: string) => void;
30
+ /** 队列数据刷新(/api/localtasks 重取) */
31
+ refresh?: () => void | Promise<unknown>;
32
+ /** doc-store 的落点 key:目录页给 dirKey,组页给看板 id(草稿正文按同一寻址) */
33
+ docKey?: string;
34
+ /** 单条删除成功后回调(目录页借此关掉已打开的任务页) */
35
+ onDeleted?: (t: LocalTask) => void;
36
+ }
37
+
38
+ /** 一条 DAG 落盘 patch(与 DagEditor 内部 DagPatch 同形)。 */
39
+ export interface DagPatchInput {
40
+ id: number;
41
+ gate?: boolean;
42
+ blockBy?: number[];
43
+ }
44
+
45
+ /** 一次批量动作的范围:同一队列的一组编号(组页的行分属多条成员队列)。 */
46
+ export interface ScopeIds {
47
+ scope: TaskScope;
48
+ ids: number[];
49
+ }
50
+
51
+ /** 行标题:正文首个非空行(去掉 `#` 前缀)。 */
52
+ export function taskTitle(t: LocalTask): string {
53
+ const line = (t.text || '').split('\n').find((l) => l.trim()) || `#${t.id}`;
54
+ return line.replace(/^#\s*/, '');
55
+ }
56
+
57
+ /** scope → 查询串(单条读取用:全局池按 key,目录按 cwd)。 */
58
+ function scopeQuery(scope: TaskScope, id: number | string): string {
59
+ return scope.key && !scope.cwd
60
+ ? `key=${encodeURIComponent(scope.key)}&id=${Number(id)}`
61
+ : `cwd=${encodeURIComponent(scope.cwd || '')}&id=${Number(id)}`;
62
+ }
63
+
64
+ /** scope → 新建任务的落点(全局池只能走 global 标记)。 */
65
+ function addScope(scope: TaskScope): { cwd?: string; global?: boolean } {
66
+ return scope.key && !scope.cwd ? { global: true } : { cwd: scope.cwd };
67
+ }
68
+
69
+ /** 把一条任务的正文写回 doc-store(打开任务页时读的是这里,不是 rows 快照)。 */
70
+ function saveTaskDoc(deps: TaskOpsDeps, landedKey: string | undefined, id: number | string, text: string): void {
71
+ if (!text) return;
72
+ saveDoc(docIdOf(scopeOf(landedKey || deps.docKey), String(id)), { body: text });
73
+ }
74
+
75
+ async function guard(deps: TaskOpsDeps, fn: () => Promise<unknown>): Promise<unknown> {
76
+ try {
77
+ return await fn();
78
+ } catch (e) {
79
+ deps.toast(String((e as Error)?.message || e));
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 反馈 / 重开(#74 / #75 / #79):已完成 → 派生新任务(原任务留档);
86
+ * 未完成 → 就地回写正文并重开。base 取**服务端当前正文**,取不到才退 rows 快照。
87
+ */
88
+ export async function runFeedbackTask(deps: TaskOpsDeps, scope: TaskScope, t: LocalTask): Promise<void> {
89
+ const { dialog, toast } = deps;
90
+ const title = taskTitle(t);
91
+ const acked = !!t.completedAt;
92
+ const body = await dialog({
93
+ title: acked ? `反馈 · #${t.id}` : `反馈修改 · #${t.id}`,
94
+ input: true,
95
+ placeholder: acked
96
+ ? '写下反馈(将新开一条任务,原任务不动)'
97
+ : '写下要改的地方(留空 = 只重开,不改正文)',
98
+ });
99
+ if (body === null || body === undefined) return;
100
+ const fb = String(body).trim();
101
+
102
+ await guard(deps, async () => {
103
+ // #79:列表行的 text 是 rows 快照,可能落后于盘上;先取服务端当前正文
104
+ const fresh = await findTaskItem(scopeQuery(scope, t.id));
105
+ const baseText = String(fresh?.text ?? '').trim() || String(t.text || '').trim();
106
+ const ackSummary = acked ? (fresh?.roundSummary || t.roundSummary || '') : '';
107
+ if (!fb && !acked && !baseText) {
108
+ toast('拿不到任务当前正文,已取消(防止丢内容)');
109
+ return;
110
+ }
111
+
112
+ if (acked) {
113
+ // #75:反馈 = 新开任务,正文 = 旧正文 + 上轮总结 + 本轮反馈
114
+ const reopenArgs = {
115
+ base: baseText,
116
+ feedback: fb,
117
+ ackSummary,
118
+ feedbackHeading: FEEDBACK_HEADING,
119
+ bold: true,
120
+ };
121
+ const text = fb ? buildReopenText(reopenArgs) : '';
122
+ if (!text) {
123
+ toast('写一下反馈');
124
+ return;
125
+ }
126
+ const res = await addTask({
127
+ ...addScope(scope),
128
+ text,
129
+ forkOf: String(t.id),
130
+ forkKind: 'reopen',
131
+ });
132
+ const newId = String(res?.task?.id ?? res?.id ?? '');
133
+ saveTaskDoc(deps, res?.key, newId, text);
134
+ toast(`已反馈「${title}」→ 新任务 #${newId || '?'}`);
135
+ deps.refresh?.();
136
+ return;
137
+ }
138
+
139
+ // #74 就地回写:#79 纯反馈不传 text——服务端把反馈段原子追加到盘上当前正文
140
+ const res = await postReopen({
141
+ ...scope,
142
+ id: t.id,
143
+ kind: 'reopen',
144
+ ...(fb ? { feedback: fb, feedbackHeading: PLAIN_FEEDBACK_HEADING, feedbackBold: false } : {}),
145
+ });
146
+ const sameId = String(res?.task?.id ?? t.id);
147
+ saveTaskDoc(deps, res?.key, sameId, String(res?.task?.text ?? ''));
148
+ toast(
149
+ `已回写「${title}」#${sameId}` + (res?.moved && res.name ? `;归属迁到「${res.name}」` : ''),
150
+ );
151
+ deps.refresh?.();
152
+ });
153
+ }
154
+
155
+ /** 单条删除(软删除,CLI 可恢复)。 */
156
+ export async function runDeleteTask(deps: TaskOpsDeps, scope: TaskScope, t: LocalTask): Promise<void> {
157
+ const { dialog, toast } = deps;
158
+ const ok = await dialog({
159
+ title: `删除任务「${taskTitle(t)}」`,
160
+ message: '软删除:CLI localtask task restore 可恢复。',
161
+ danger: true,
162
+ okText: '删除',
163
+ });
164
+ if (!ok) return;
165
+ await guard(deps, async () => {
166
+ await removeTaskItem({ ...scope, id: t.id });
167
+ toast(`已删除「${taskTitle(t)}」`);
168
+ deps.onDeleted?.(t);
169
+ deps.refresh?.();
170
+ return true;
171
+ });
172
+ }
173
+
174
+ /** 批量动作的总条数。 */
175
+ const totalOf = (groups: ScopeIds[]): number => groups.reduce((n, g) => n + g.ids.length, 0);
176
+
177
+ /** 批量软删除(组页按成员队列分组多次调用,提示只报一次总数)。 */
178
+ export async function runBatchDelete(deps: TaskOpsDeps, groups: ScopeIds[]): Promise<boolean> {
179
+ const total = totalOf(groups);
180
+ if (!total) return false;
181
+ const ok = await deps.dialog({
182
+ title: `删除选中的 ${total} 条任务`,
183
+ message: '软删除:CLI localtask task restore 可恢复。',
184
+ danger: true,
185
+ okText: '删除',
186
+ });
187
+ if (!ok) return false;
188
+ let count = 0;
189
+ for (const g of groups) {
190
+ const res = await guard(deps, () => removeManyTasks({ ...g.scope, ids: g.ids }));
191
+ if (res === false) return false;
192
+ count += (res as { count?: number }).count ?? g.ids.length;
193
+ }
194
+ deps.toast(`已删除 ${count} 条任务`);
195
+ deps.refresh?.();
196
+ return true;
197
+ }
198
+
199
+ /** 批量取消(只处理待领取,其余跳过)。 */
200
+ export async function runBatchCancel(deps: TaskOpsDeps, groups: ScopeIds[]): Promise<boolean> {
201
+ const total = totalOf(groups);
202
+ if (!total) return false;
203
+ const ok = await deps.dialog({
204
+ title: `取消选中的 ${total} 条待领取任务`,
205
+ message: '只处理待领取任务;已领取/已完成/已取消会跳过。取消为终态,原文留档。',
206
+ okText: '取消任务',
207
+ });
208
+ if (!ok) return false;
209
+ let count = 0;
210
+ let skipped = 0;
211
+ for (const g of groups) {
212
+ const res = await guard(deps, () => cancelManyTasks({ ...g.scope, ids: g.ids }));
213
+ if (res === false) return false;
214
+ const r = res as { count?: number; skipped?: unknown[] };
215
+ count += r.count ?? 0;
216
+ skipped += r.skipped?.length || 0;
217
+ }
218
+ deps.toast(`已取消 ${count} 条任务${skipped ? `,跳过 ${skipped} 条` : ''}`);
219
+ deps.refresh?.();
220
+ return true;
221
+ }
222
+
223
+ /** 批量标为完成(待领取 + 已领取都能收口)。 */
224
+ export async function runBatchComplete(deps: TaskOpsDeps, groups: ScopeIds[]): Promise<boolean> {
225
+ const total = totalOf(groups);
226
+ if (!total) return false;
227
+ const ok = await deps.dialog({
228
+ title: `把选中的 ${total} 条任务标为完成`,
229
+ message:
230
+ '待领取与已领取(正在跑)都能收:已领取的直接收口,agent 侧回执会被忽略。已完成/已取消会跳过。完成会补一条完成记录,原文留档。',
231
+ okText: '标为完成',
232
+ });
233
+ if (!ok) return false;
234
+ let count = 0;
235
+ let skipped = 0;
236
+ let claimed = 0;
237
+ for (const g of groups) {
238
+ const res = await guard(deps, () => closeManyTasks({ ...g.scope, ids: g.ids, status: 'done' }));
239
+ if (res === false) return false;
240
+ const r = res as { count?: number; skipped?: unknown[]; claimedClosed?: unknown[] };
241
+ count += r.count ?? 0;
242
+ skipped += r.skipped?.length || 0;
243
+ claimed += r.claimedClosed?.length || 0;
244
+ }
245
+ deps.toast(
246
+ `已标为完成 ${count} 条任务${claimed ? `(含 ${claimed} 条已领取)` : ''}${skipped ? `,跳过 ${skipped} 条` : ''}`,
247
+ );
248
+ deps.refresh?.();
249
+ return true;
250
+ }
251
+
252
+ /** 闸门快捷开关(挡住队列里排在我后面的待领取任务)。 */
253
+ export async function runToggleGate(deps: TaskOpsDeps, scope: TaskScope, t: LocalTask): Promise<void> {
254
+ const next = !t.blocksFollowing;
255
+ const res = await guard(deps, () => patchTaskItem({ ...scope, id: t.id, gate: next }));
256
+ if (!res) return;
257
+ deps.toast(next ? `#${t.id} 已设为闸门——挡住所有后续待领取任务` : `#${t.id} 闸门已取消`);
258
+ deps.refresh?.();
259
+ }
260
+
261
+ /** 一次草稿态切换的范围:同一队列的一组任务。 */
262
+ export interface PlanGroup {
263
+ scope: TaskScope;
264
+ ids: Array<number | string>;
265
+ }
266
+
267
+ /** 草稿态切换(pending ↔ plan;plan 不进 get/wait 队列)。组页按成员队列分组,提示只报一次。 */
268
+ export async function runPlanSwitch(
269
+ deps: TaskOpsDeps,
270
+ groups: PlanGroup[],
271
+ to: 'plan' | 'pending',
272
+ ): Promise<void> {
273
+ const total = groups.reduce((n, g) => n + g.ids.length, 0);
274
+ if (!total) return;
275
+ await guard(deps, async () => {
276
+ for (const g of groups) {
277
+ for (const id of g.ids) await setPlanStatus({ ...g.scope, id: Number(id), to });
278
+ }
279
+ deps.toast(to === 'plan' ? `已把 ${total} 条任务转为草稿(不进队列)` : `已把 ${total} 条草稿转回待领取`);
280
+ deps.refresh?.();
281
+ return true;
282
+ });
283
+ }
284
+
285
+ /** 编排落盘:逐条任务级 PATCH(本任务 gate/blockBy + 下游各方 blockBy)。失败上抛。 */
286
+ export async function saveDagPatches(
287
+ deps: TaskOpsDeps,
288
+ scope: TaskScope,
289
+ patches: DagPatchInput[],
290
+ ): Promise<void> {
291
+ try {
292
+ for (const p of patches) await patchTaskItem({ ...scope, ...p });
293
+ deps.toast('编排已保存');
294
+ deps.refresh?.();
295
+ } catch (e) {
296
+ deps.toast(String((e as Error)?.message || e));
297
+ throw e;
298
+ }
299
+ }