@keyou007/agent-bot 0.1.27-alpha.4 → 0.1.27-alpha.5

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 (63) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +37 -18
  3. package/README.zh.md +37 -18
  4. package/assets/workspace-sessions.js +959 -229
  5. package/assets/workspace.css +241 -57
  6. package/assets/workspace.js +1463 -227
  7. package/dist/feishu/FeishuTurnPresenter.js +26 -9
  8. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  9. package/dist/local-files/GitDiffPreview.js +69 -7
  10. package/dist/local-files/GitDiffPreview.js.map +1 -1
  11. package/dist/local-files/LocalFileViewerServer.js +10 -7
  12. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  13. package/dist/local-files/PreviewSyntaxHighlight.js +1 -1
  14. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  15. package/dist/local-files/TurnPreviewPage.js +30 -7
  16. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  17. package/dist/local-files/WorkspaceImages.js +28 -0
  18. package/dist/local-files/WorkspaceImages.js.map +1 -1
  19. package/dist/local-files/WorkspacePage.js +5 -2
  20. package/dist/local-files/WorkspacePage.js.map +1 -1
  21. package/dist/local-files/WorkspaceSessions.js +343 -96
  22. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  23. package/dist/local-files/WorkspaceTimeline.js +34 -10
  24. package/dist/local-files/WorkspaceTimeline.js.map +1 -1
  25. package/dist/presentation/OutboundRouter.js +3 -1
  26. package/dist/presentation/OutboundRouter.js.map +1 -1
  27. package/dist/presentation/TurnStateReducer.js +3 -1
  28. package/dist/presentation/TurnStateReducer.js.map +1 -1
  29. package/dist/proxy/ProxySessionController.js +130 -45
  30. package/dist/proxy/ProxySessionController.js.map +1 -1
  31. package/dist/scheduling/ScheduledTaskStore.js +6 -4
  32. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  33. package/dist/scheduling/types.js +2 -1
  34. package/dist/scheduling/types.js.map +1 -1
  35. package/dist/state/StateStore.js +77 -13
  36. package/dist/state/StateStore.js.map +1 -1
  37. package/dist/state/TurnPreviewJournal.js +24 -13
  38. package/dist/state/TurnPreviewJournal.js.map +1 -1
  39. package/dist/utils/promptAttachments.js +4 -2
  40. package/dist/utils/promptAttachments.js.map +1 -1
  41. package/dist/utils/promptQuotes.js +47 -0
  42. package/dist/utils/promptQuotes.js.map +1 -0
  43. package/npm-shrinkwrap.json +2 -2
  44. package/package.json +1 -1
  45. package/src/feishu/FeishuTurnPresenter.ts +27 -8
  46. package/src/local-files/GitDiffPreview.ts +72 -8
  47. package/src/local-files/LocalFileViewerServer.ts +10 -7
  48. package/src/local-files/PreviewSyntaxHighlight.ts +1 -1
  49. package/src/local-files/TurnPreviewPage.ts +35 -7
  50. package/src/local-files/WorkspaceImages.ts +25 -0
  51. package/src/local-files/WorkspacePage.ts +5 -2
  52. package/src/local-files/WorkspaceSessions.ts +318 -101
  53. package/src/local-files/WorkspaceTimeline.ts +41 -15
  54. package/src/presentation/OutboundRouter.ts +3 -0
  55. package/src/presentation/TurnStateReducer.ts +3 -1
  56. package/src/presentation/turnViewTypes.ts +1 -1
  57. package/src/proxy/ProxySessionController.ts +135 -44
  58. package/src/scheduling/ScheduledTaskStore.ts +6 -4
  59. package/src/scheduling/types.ts +4 -1
  60. package/src/state/StateStore.ts +83 -17
  61. package/src/state/TurnPreviewJournal.ts +27 -14
  62. package/src/utils/promptAttachments.ts +5 -2
  63. package/src/utils/promptQuotes.ts +48 -0
@@ -1,4 +1,5 @@
1
1
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
2
3
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import MarkdownIt from "markdown-it";
@@ -9,20 +10,23 @@ import { listTaskDirectories, TASK_DIRECTORY_KIND, taskDirectoryId } from "../pr
9
10
  import { displayRuntimeError } from "../runtime/responseErrors.js";
10
11
  import { TurnNotSubmittedError } from "../runtime/submissionErrors.js";
11
12
  import { scheduleDisplayPrompt, scheduleInputSchema } from "../scheduling/types.js";
13
+ import { isTerminalTurnStatus } from "../presentation/turnStatus.js";
12
14
  import { toolTextFields } from "../state/TurnToolText.js";
13
15
  import { formatPreviewToolCommand, normalizeToolOutput } from "./ToolCommandDisplay.js";
14
- import { workspaceTimeline } from "./WorkspaceTimeline.js";
15
- import { workspaceImageExtension } from "./WorkspaceImages.js";
16
+ import { recordedWorkspaceTimeline, workspaceTimeline } from "./WorkspaceTimeline.js";
17
+ import { WORKSPACE_PNG_HEADER_BYTES, workspaceImageExtension, workspacePngDisplaySize } from "./WorkspaceImages.js";
16
18
  import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
17
19
  import { highlightPreviewCode } from "./PreviewSyntaxHighlight.js";
18
- import { highlightRecordedPatch } from "./GitDiffPreview.js";
20
+ import { highlightRecordedPatch, renderRecordedDiff } from "./GitDiffPreview.js";
19
21
  import { WORKSPACE_INSTANCE, WORKSPACE_INSTANCE_HEADER, WORKSPACE_REVISION, WORKSPACE_REVISION_HEADER } from "./WorkspacePage.js";
20
22
  import { resolveWorkspaceDirectoryAddress, resolveWorkspacePath, WorkspaceError } from "./WorkspaceFiles.js";
21
23
  import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
22
24
  import { turnAnswerFilename } from "./MarkdownExport.js";
25
+ import { turnUsageFields } from "./TurnPreviewPage.js";
23
26
  import { toolTimestamp } from "../utils/toolTimestamp.js";
24
27
  import { formatStorageSize } from "../utils/formatStorageSize.js";
25
28
  import { defaultResourcePromptFromCounts, queuedPromptContent } from "../utils/promptAttachments.js";
29
+ import { promptQuoteInstruction, promptQuotesSchema } from "../utils/promptQuotes.js";
26
30
  const TTL = 8 * 60 * 60_000;
27
31
  const MAX_HISTORY = 20;
28
32
  const TASK_PAGE_SIZE = 20;
@@ -31,12 +35,29 @@ const MAX_EXECUTION_CHARS = 32_000;
31
35
  const MAX_TOOL_FILE_ENTRIES = 200;
32
36
  const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
33
37
  const MAX_ATTACHMENT_TOTAL = 12 * 1024 * 1024;
34
- const MAX_OPERATION_BYTES = Math.ceil(MAX_ATTACHMENT_TOTAL / 3) * 4 + 150_000;
38
+ const MAX_OPERATION_BYTES = Math.ceil(MAX_ATTACHMENT_TOTAL / 3) * 4 + 1024 * 1024;
35
39
  const attachmentData = z.string().max(Math.ceil(MAX_ATTACHMENT_BYTES / 3) * 4);
36
40
  const attachmentKind = "workspace-prompt-files";
41
+ const workspacePromptKind = "workspace-prompt";
37
42
  const id = z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u);
43
+ const toolPatchId = (file) => hash(JSON.stringify([file.path, file.moveTo])).slice(0, 32);
38
44
  const key = z.uuid();
39
45
  const imageEntry = z.string().min(1).max(4096).regex(/^[^\x00-\x1f\x7f]+$/u);
46
+ const savedWorkspacePrompt = z.object({
47
+ action: z.enum(["send", "steer", "queue"]),
48
+ text: z.string(),
49
+ turn: id.optional(),
50
+ quotes: promptQuotesSchema.optional(),
51
+ attachments: z.object({
52
+ images: z.array(z.string()),
53
+ files: z.array(z.object({ fileName: z.string(), filePath: z.string() })),
54
+ }),
55
+ });
56
+ function displaySubmittedPrompt(text, saved) {
57
+ if (saved?.quotes?.length && !saved.text && text === promptQuoteInstruction(saved.quotes))
58
+ return "";
59
+ return text ?? saved?.text;
60
+ }
40
61
  const directoryPanelKind = "workspace-directory-panel";
41
62
  const directoryPanelKey = "state";
42
63
  const maxDirectoryTabs = 24;
@@ -59,15 +80,18 @@ const taskSetting = z.object({ task: id, setting: z.enum(["model", "thinking"]),
59
80
  const turnAction = z.object({ task: id, turn: id, action: z.enum(["reset", "fork"]) }).strict();
60
81
  const queueRevision = z.string().regex(/^[a-f0-9]{64}$/u);
61
82
  const queueCancel = z.object({ task: id, prompt: id, request: key, revision: queueRevision.optional() }).strict();
83
+ const queueSend = z.object({ task: id, prompt: id, request: key, revision: queueRevision }).strict();
62
84
  const queueEdit = z.object({ task: id, prompt: id, revision: queueRevision, text: z.string().trim().max(24_000) }).strict();
63
85
  const attachmentEntry = z.object({ name: z.string().min(1).max(255), entry: imageEntry });
64
86
  const uploadFields = {
65
87
  images: z.array(attachmentData.min(1)).max(4).optional(),
66
- files: z.array(z.object({ name: attachmentEntry.shape.name, data: attachmentData }).strict()).max(4).optional()
88
+ files: z.array(z.object({ name: attachmentEntry.shape.name, data: attachmentData }).strict()).max(4).optional(),
89
+ quotes: promptQuotesSchema.optional()
67
90
  };
91
+ const promptAttachmentCount = (input) => (input.images?.length ?? 0) + (input.files?.length ?? 0) + (input.quotes?.length ?? 0);
68
92
  const scheduleCreate = z.object({ task: id, request: key, schedule: scheduleInputSchema, ...uploadFields }).strict()
69
- .refine(input => Boolean(input.schedule.prompt || input.images?.length || input.files?.length)
70
- && (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4, "请输入 Prompt 或添加至多 4 个附件。");
93
+ .refine(input => Boolean(input.schedule.prompt || promptAttachmentCount(input))
94
+ && promptAttachmentCount(input) <= 4, "请输入 Prompt 或添加至多 4 个附件。");
71
95
  const scheduleActionFields = { task: id, job: id, revision: z.int().positive() };
72
96
  const scheduleAction = z.discriminatedUnion("action", [
73
97
  z.object({ ...scheduleActionFields, action: z.literal("edit"), schedule: scheduleInputSchema }).strict(),
@@ -78,8 +102,7 @@ const instruction = z.discriminatedUnion("action", [
78
102
  z.object({ action: z.enum(["send", "queue"]), ...promptFields }).strict(),
79
103
  z.object({ action: z.literal("steer"), turn: id, ...promptFields }).strict(),
80
104
  z.object({ action: z.literal("stop"), task: id, request: key, turn: id }).strict(),
81
- ]).refine((input) => input.action === "stop" || (Boolean(input.text || input.images?.length || input.files?.length)
82
- && (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4));
105
+ ]).refine((input) => input.action === "stop" || (Boolean(input.text || promptAttachmentCount(input)) && promptAttachmentCount(input) <= 4));
83
106
  const markdown = new MarkdownIt({ html: false, breaks: true, linkify: true, highlight: highlightPreviewCode });
84
107
  markdown.renderer.rules.table_open = (tokens, index, options, _env, renderer) => '<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0">' + renderer.renderToken(tokens, index, options);
85
108
  markdown.renderer.rules.table_close = () => '</table></div>\n';
@@ -149,11 +172,13 @@ export class WorkspaceSessions {
149
172
  imageSecret = randomBytes(32);
150
173
  failures = [];
151
174
  rendered = new Map();
175
+ attachmentSizes = new Map();
152
176
  metricsCache = new Map();
153
177
  catalogue = 0;
154
178
  catalogueHash = "";
155
179
  nextCatalogue = 0;
156
180
  timer;
181
+ polling = false;
157
182
  nextPrune = 0;
158
183
  operationBodies = 0;
159
184
  lastSubmissionAt;
@@ -168,12 +193,13 @@ export class WorkspaceSessions {
168
193
  }
169
194
  start() {
170
195
  this.base = new URL(this.viewer.mountService("workspace-app", this).publicBaseUrl);
171
- this.timer = setInterval(() => this.poll(), 400);
196
+ this.timer = setInterval(() => void this.poll(), 400);
172
197
  this.timer.unref();
173
198
  return this.base.pathname;
174
199
  }
175
200
  async close() {
176
201
  clearInterval(this.timer);
202
+ this.timer = undefined;
177
203
  for (const stream of this.streams.values())
178
204
  stream.response.end();
179
205
  this.streams.clear();
@@ -401,6 +427,15 @@ export class WorkspaceSessions {
401
427
  });
402
428
  return;
403
429
  }
430
+ if (route === "/task-title" && request.method === "POST") {
431
+ const input = parse(z.object({ task: id, title: z.string().trim().min(1).max(120) }).strict(), await this.body(request));
432
+ const task = this.task(input.task);
433
+ await this.controlAction(grant, async () => {
434
+ await this.options.controller.controlSetTaskTitle(task.localSessionId, input.title, "workspace");
435
+ this.json(response, 200, { title: this.task(task.localSessionId).title });
436
+ });
437
+ return;
438
+ }
404
439
  if (route === "/task-settings") {
405
440
  const input = request.method === "POST" ? parse(taskSetting, await this.body(request)) : undefined;
406
441
  const task = this.task(input?.task ?? parse(id, url.searchParams.get("task")));
@@ -427,7 +462,10 @@ export class WorkspaceSessions {
427
462
  throw new RequestError(400, "对话分页参数冲突。");
428
463
  const stream = after ? this.streams.get(url.searchParams.get("page") ?? "") : undefined;
429
464
  const version = stream?.grant === grant && stream.task === task.localSessionId ? stream.version : undefined;
430
- this.json(response, 200, { ...this.history(task, origin, before, anchor, after), version });
465
+ const history = await this.history(task, origin, before, anchor, after);
466
+ if (!this.valid(grant))
467
+ throw new RequestError(401, "工作台会话已过期。");
468
+ this.json(response, 200, { ...history, version });
431
469
  return;
432
470
  }
433
471
  if (route === "/focus" && request.method === "POST") {
@@ -440,26 +478,34 @@ export class WorkspaceSessions {
440
478
  const task = input.task ? this.task(input.task) : undefined;
441
479
  stream.task = task?.localSessionId;
442
480
  stream.generation = input.generation;
443
- stream.tail = undefined;
444
- this.json(response, 200, { ...(task && this.history(task, origin, undefined, input.anchor)), version: stream.version, generation: stream.generation });
481
+ stream.tail = stream.queue = undefined;
482
+ const version = stream.version;
483
+ const history = task && await this.history(task, origin, undefined, input.anchor);
484
+ if (!this.valid(grant))
485
+ throw new RequestError(401, "工作台会话已过期。");
486
+ if (stream.task !== input.task || stream.generation !== input.generation)
487
+ throw new RequestError(409, "所选任务已变更。");
488
+ this.json(response, 200, { ...history, version, generation: input.generation });
445
489
  return;
446
490
  }
447
491
  if (route === "/queue" && request.method === "GET") {
448
492
  const task = this.task(parse(id, url.searchParams.get("task")));
449
493
  const promptId = parse(id, url.searchParams.get("prompt"));
450
494
  const prompt = this.requireQueuedPrompt(task.localSessionId, promptId);
451
- const run = this.options.store.schedules.getRun(promptId);
452
- const requestId = run ? run.id.slice("schedule_run_".length)
453
- : promptId.startsWith("workspace:") ? key.safeParse(promptId.slice("workspace:".length)).data : undefined;
495
+ const requestId = this.queuedPromptRequest(promptId);
454
496
  const files = this.attachmentLinks(task.localSessionId, requestId);
455
- this.json(response, 200, { text: run ? queuedPromptContent(prompt).text : files?.length ? prompt.displayPrompt ?? prompt.text : prompt.text,
456
- revision: queuePromptRevision(prompt), files, images: this.attachments(task, prompt.localImagePaths) });
497
+ const quotes = this.quotesForRequest(task.localSessionId, requestId);
498
+ const text = quotes?.length || promptId.startsWith("schedule_run_") ? queuedPromptContent(prompt, quotes).text
499
+ : files?.length ? prompt.displayPrompt ?? prompt.text : prompt.text;
500
+ this.json(response, 200, { text,
501
+ revision: queuePromptRevision(prompt), files, quotes, images: this.attachments(task, prompt.localImagePaths) });
457
502
  return;
458
503
  }
459
504
  if (route === "/queue/edit" && request.method === "GET") {
460
505
  const task = this.task(parse(id, url.searchParams.get("task")));
461
506
  const prompt = this.requireQueuedPrompt(task.localSessionId, parse(id, url.searchParams.get("prompt")));
462
- this.json(response, 200, { text: queuedPromptContent(prompt).text, revision: queuePromptRevision(prompt) });
507
+ const quotes = this.quotesForRequest(task.localSessionId, this.queuedPromptRequest(prompt.promptId));
508
+ this.json(response, 200, { text: queuedPromptContent(prompt, quotes).text, revision: queuePromptRevision(prompt) });
463
509
  return;
464
510
  }
465
511
  if (route === "/queue/edit" && request.method === "POST") {
@@ -467,7 +513,8 @@ export class WorkspaceSessions {
467
513
  await this.controlAction(grant, async () => {
468
514
  this.task(input.task);
469
515
  const prompt = this.requireQueuedPrompt(input.task, input.prompt);
470
- const content = queuedPromptContent(prompt);
516
+ const quotes = this.quotesForRequest(input.task, this.queuedPromptRequest(prompt.promptId));
517
+ const content = queuedPromptContent(prompt, quotes);
471
518
  if (input.text === content.text) {
472
519
  this.json(response, 200, this.describeQueuedPrompt(prompt));
473
520
  return;
@@ -475,9 +522,9 @@ export class WorkspaceSessions {
475
522
  if (input.revision !== queuePromptRevision(prompt))
476
523
  throw new RequestError(409, "这条消息已被修改,请重新打开编辑。");
477
524
  const images = prompt.localImagePaths?.length ?? 0;
478
- if (!input.text && !images && !content.fileCount)
525
+ if (!input.text && !images && !content.fileCount && !quotes?.length)
479
526
  throw new RequestError(400, "请输入消息内容。");
480
- const text = input.text || (content.fileCount ? defaultResourcePromptFromCounts(images, content.fileCount) : "");
527
+ const text = input.text || promptQuoteInstruction(quotes) || (content.fileCount ? defaultResourcePromptFromCounts(images, content.fileCount) : "");
481
528
  const run = this.options.store.schedules.getRun(prompt.promptId);
482
529
  const job = run && this.options.store.schedules.get(run.jobId);
483
530
  const displayPrompt = job && run
@@ -505,6 +552,11 @@ export class WorkspaceSessions {
505
552
  });
506
553
  return;
507
554
  }
555
+ if (route === "/queue/send" && request.method === "POST") {
556
+ const input = parse(queueSend, await this.body(request));
557
+ await this.controlAction(grant, async () => this.json(response, 200, await this.sendQueuedPrompt(input)));
558
+ return;
559
+ }
508
560
  if (route === "/schedules" && request.method === "GET") {
509
561
  const task = this.task(parse(id, url.searchParams.get("task")));
510
562
  const offset = parse(z.coerce.number().int().min(0).max(1_000_000), url.searchParams.get("offset") ?? 0);
@@ -591,7 +643,8 @@ export class WorkspaceSessions {
591
643
  const toolId = parse(id, url.searchParams.get("tool"));
592
644
  const offset = parse(z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER - MAX_EXECUTION_CHARS), url.searchParams.get("offset") ?? 0);
593
645
  const revision = parse(z.string().max(64).optional(), url.searchParams.get("revision") ?? undefined);
594
- const page = await this.toolPage(task, state, toolId, offset, revision);
646
+ const patch = parse(z.string().regex(/^[a-f0-9]{32}$/u).optional(), url.searchParams.get("patch") ?? undefined);
647
+ const page = await this.toolPage(task, state, toolId, offset, revision, patch);
595
648
  if (grant.signal.aborted || !this.valid(grant))
596
649
  throw new RequestError(401, "工作台会话已过期。");
597
650
  const currentHead = this.head(this.task(task.localSessionId));
@@ -601,12 +654,15 @@ export class WorkspaceSessions {
601
654
  this.json(response, 200, page);
602
655
  return;
603
656
  }
604
- const cwd = state.projectCwd ?? task.cwd;
605
- const changes = this.toolFiles(task, cwd, workspaceFileSummary(state, cwd));
657
+ const saved = await this.recordedTurn(turn, state.previewTurnId, state.continuedToTurnId) ?? state;
658
+ if (!this.valid(grant))
659
+ throw new RequestError(401, "工作台会话已过期。");
660
+ this.requireBranchTurn(this.task(task.localSessionId), turn);
661
+ const cwd = saved.projectCwd ?? task.cwd;
662
+ const changes = this.toolFiles(task, cwd, workspaceFileSummary(saved, cwd));
606
663
  this.json(response, 200, {
607
- plan: (state.plan ?? []).slice(0, 30),
664
+ plan: (saved.plan ?? []).slice(0, 30),
608
665
  changes: changes.files, changesTruncated: changes.filesTruncated,
609
- compact: Boolean(state.previewJournal || state.activitiesTruncated || state.historyDetail === "summary"),
610
666
  });
611
667
  return;
612
668
  }
@@ -750,7 +806,7 @@ export class WorkspaceSessions {
750
806
  const { name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes } = job.spec;
751
807
  return { id: job.id, revision: job.revision, name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes,
752
808
  status: job.status, nextRunAt: job.nextRunAt, notice: job.notice,
753
- images: job.attachments?.images.length, files: job.attachments?.files.map(file => file.fileName) };
809
+ images: job.attachments?.images.length, files: job.attachments?.files.map(file => file.fileName), quotes: job.attachments?.quotes?.length };
754
810
  }
755
811
  scheduleForTask(task, id, owner) {
756
812
  const job = this.options.store.schedules.get(id);
@@ -771,8 +827,9 @@ export class WorkspaceSessions {
771
827
  return previous;
772
828
  }
773
829
  const { images, files } = this.decodeAttachments(input.images ?? [], input.files ?? []);
830
+ const quotes = input.quotes?.length ? input.quotes : undefined;
774
831
  if (!images.length && !files.length)
775
- return create();
832
+ return create(quotes ? { images: [], files: [], quotes } : undefined);
776
833
  if (previous)
777
834
  throw new RequestError(409, "该请求标识已用于另一项计划。");
778
835
  const { directory, attachments } = await this.writePromptAttachments(images, files);
@@ -781,7 +838,7 @@ export class WorkspaceSessions {
781
838
  if (!this.valid(grant))
782
839
  throw new RequestError(401, "工作台会话已过期,未创建计划。");
783
840
  const alreadyCreated = store.getByRequest(input.request);
784
- const job = create(attachments);
841
+ const job = create(quotes ? { ...attachments, quotes } : attachments);
785
842
  keep = !alreadyCreated;
786
843
  return job;
787
844
  }
@@ -796,14 +853,63 @@ export class WorkspaceSessions {
796
853
  throw new RequestError(404, "这条消息已离开队列。");
797
854
  return prompt;
798
855
  }
856
+ async sendQueuedPrompt(input) {
857
+ const task = this.task(input.task), store = this.options.store;
858
+ const fingerprint = hash(JSON.stringify(["send-queued-prompt", input]));
859
+ const previous = store.workspaceRequest(input.request);
860
+ if (previous) {
861
+ if (previous.fingerprint !== fingerprint)
862
+ throw new RequestError(409, "该请求标识已用于另一项操作。");
863
+ return this.operation(input.request, previous);
864
+ }
865
+ if (task.status === "closed")
866
+ throw new RequestError(409, "任务已归档,无法发送消息。");
867
+ const prompt = this.requireQueuedPrompt(input.task, input.prompt);
868
+ if (queuePromptRevision(prompt) !== input.revision)
869
+ throw new RequestError(409, "排队消息已被修改,请重新发送。");
870
+ store.beginWorkspaceRequest(input.request, input.task, fingerprint);
871
+ this.lastSubmissionAt = Math.max(Date.now(), (this.lastSubmissionAt ?? 0) + 1);
872
+ this.running.add(input.request);
873
+ let submitting = false;
874
+ try {
875
+ await this.options.controller.controlSendWorkspaceQueuedPrompt(prompt, {
876
+ requestId: input.request, onSubmitting: () => { submitting = true; },
877
+ onPosted: () => { store.markWorkspaceRequestPosted(input.request); },
878
+ });
879
+ store.updateWorkspaceRequest(input.request, "accepted");
880
+ }
881
+ catch (error) {
882
+ const unknown = submitting && !(error instanceof TurnNotSubmittedError);
883
+ store.updateWorkspaceRequest(input.request, unknown ? "unknown" : "failed", false, displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "发送排队消息失败。"));
884
+ }
885
+ finally {
886
+ this.running.delete(input.request);
887
+ }
888
+ return this.operation(input.request, store.workspaceRequest(input.request));
889
+ }
799
890
  describeQueuedPrompt(prompt) {
800
- const { text, fileCount } = queuedPromptContent(prompt);
801
- return { id: prompt.promptId, text: (prompt.displayPrompt ?? text).slice(0, 180),
802
- ...(fileCount || prompt.localImagePaths?.length ? { hasAttachments: true } : {}) };
891
+ const quotes = this.quotesForRequest(prompt.localSessionId, this.queuedPromptRequest(prompt.promptId));
892
+ const { text, fileCount } = queuedPromptContent(prompt, quotes);
893
+ const preview = (prompt.displayPrompt ?? text).slice(0, 180);
894
+ return { id: prompt.promptId, text: preview, revision: queuePromptRevision(prompt),
895
+ ...(text === preview ? {} : { editText: text }),
896
+ ...(fileCount || prompt.localImagePaths?.length || quotes?.length ? { hasAttachments: true } : {}) };
897
+ }
898
+ queuedPromptRequest(promptId) {
899
+ const prefix = promptId.startsWith("workspace:") ? "workspace:" : "schedule_run_";
900
+ if (promptId.startsWith(prefix))
901
+ return key.safeParse(promptId.slice(prefix.length)).data;
803
902
  }
804
903
  describeQueue(task) {
805
- const queuedPrompts = this.options.store.listQueuedPrompts(task).map(prompt => this.describeQueuedPrompt(prompt));
806
- return { queued: queuedPrompts.length, queuedPrompts };
904
+ const store = this.options.store, queued = store.listQueuedPrompts(task);
905
+ const remaining = new Set(queued.map(prompt => prompt.promptId));
906
+ const dispatching = store.listQueuedPromptDispatches(task).filter(prompt => !remaining.has(prompt.promptId));
907
+ const queuedPrompts = [
908
+ ...queued.map(prompt => ({ prompt, dispatching: false })),
909
+ ...dispatching.map(prompt => ({ prompt, dispatching: true })),
910
+ ].sort((a, b) => Date.parse(a.prompt.createdAt) - Date.parse(b.prompt.createdAt))
911
+ .map(({ prompt, dispatching }) => ({ ...this.describeQueuedPrompt(prompt), dispatching: dispatching || undefined }));
912
+ return { queued: queued.length, queuedPrompts };
807
913
  }
808
914
  describe(task, fileOrigin) {
809
915
  const project = this.project(task);
@@ -881,8 +987,9 @@ export class WorkspaceSessions {
881
987
  return { ...row, status: liveStatus ?? row.status,
882
988
  promptPreview: executing && !liveStatus ? null : workspacePromptPreview(summary?.prompt) };
883
989
  }
884
- history(task, origin, before, anchor, after) {
990
+ async history(task, origin, before, anchor, after) {
885
991
  const head = this.head(task), store = this.options.store;
992
+ const describedTask = this.describe(task, origin);
886
993
  const anchored = Boolean(anchor && anchor !== head && !store.workspaceTurnPage(task.localSessionId, head, anchor, 1).beforeMissing);
887
994
  const page = after ? store.workspaceTurnsAfter(task.localSessionId, head, after, MAX_HISTORY)
888
995
  : store.workspaceTurnPage(task.localSessionId, anchored ? anchor : head, before, MAX_HISTORY);
@@ -891,7 +998,7 @@ export class WorkspaceSessions {
891
998
  const turns = [];
892
999
  let bytes = 0;
893
1000
  for (const turnId of page.ids) {
894
- const turn = this.turn(task, turnId, turnId === head);
1001
+ const turn = await this.turn(task, turnId, turnId === head, true);
895
1002
  if (!turn)
896
1003
  continue;
897
1004
  const cost = Buffer.byteLength(JSON.stringify(turn));
@@ -901,7 +1008,7 @@ export class WorkspaceSessions {
901
1008
  bytes += cost;
902
1009
  }
903
1010
  const summary = head ? store.getTurnPromptSummary(head) : undefined;
904
- return { task: { ...this.describe(task, origin), promptPreview: workspacePromptPreview(summary?.prompt),
1011
+ return { task: { ...describedTask, promptPreview: workspacePromptPreview(summary?.prompt),
905
1012
  metrics: this.conversationMetrics(task, head) }, head, headStatus: summary?.status,
906
1013
  execution: this.activeExecution(task, head, summary?.status),
907
1014
  plan: head ? store.workspaceTurnPlan(head) : [],
@@ -913,45 +1020,98 @@ export class WorkspaceSessions {
913
1020
  const store = this.options.store;
914
1021
  const snapshot = store.workspaceTurnExecution(turnId);
915
1022
  const submission = store.provenance.forTurn(turnId, task.localSessionId);
1023
+ const tokens = snapshot ? turnUsageFields(snapshot).tokens : [];
916
1024
  return {
917
1025
  startedAt: toolTimestamp(snapshot?.startedAt) ?? toolTimestamp(submission?.submittedAt),
918
1026
  model: submission?.settings.model ?? snapshot?.model ?? undefined,
919
1027
  thinking: submission?.settings.reasoningEffort ?? snapshot?.thinking ?? undefined,
1028
+ tokenUsage: tokens.length ? tokens.map(({ text }) => text).join(" · ") : undefined,
920
1029
  };
921
1030
  }
922
- turn(task, turnId, current = false) {
1031
+ async recordedTurn(turnId, journalId, continuedToTurnId) {
1032
+ const journal = this.options.store.previews;
1033
+ journalId ??= turnId;
1034
+ if (!journal.has(journalId))
1035
+ return undefined;
1036
+ try {
1037
+ const saved = await journal.loadAsync(journalId, false, continuedToTurnId ? turnId : undefined);
1038
+ return saved?.turnId === turnId ? saved : undefined;
1039
+ }
1040
+ catch (error) {
1041
+ this.options.logger.warn({ error, turnId: journalId }, "Failed to read the Workspace turn journal.");
1042
+ return undefined;
1043
+ }
1044
+ }
1045
+ async turn(task, turnId, current = false, hydrate = false) {
923
1046
  const row = this.options.store.workspaceTurnText(turnId);
924
1047
  if (!row)
925
1048
  return undefined;
926
- const activities = JSON.parse(row.activities);
927
- const reasoning = JSON.parse(row.reasoning);
928
- const answer = row.answer || row.live;
929
- return { id: turnId, status: row.status, startedAt: row.startedAt, prompt: row.prompt?.slice(0, 24_000),
1049
+ let recorded = await this.recordedTurn(turnId, row.journalId, row.continuedToTurnId);
1050
+ if (!recorded && hydrate && row.detail === "summary") {
1051
+ try {
1052
+ const history = await this.options.loadTurnDetails?.(turnId);
1053
+ if (history?.historyDetail === "full")
1054
+ recorded = history;
1055
+ }
1056
+ catch (error) {
1057
+ this.options.logger.warn({ error, turnId }, "Failed to load the Workspace turn history.");
1058
+ }
1059
+ }
1060
+ const savedPrompt = this.savedPrompt(task.localSessionId, row.promptRequestId ?? undefined);
1061
+ const originalPrompt = row.ownerTask === task.localSessionId ? savedPrompt : this.savedPrompt(row.ownerTask, row.promptRequestId ?? undefined);
1062
+ const { activities, reasoning } = recorded ? recordedWorkspaceTimeline(recorded) : {
1063
+ activities: JSON.parse(row.activities), reasoning: JSON.parse(row.reasoning),
1064
+ };
1065
+ const finalAnswer = row.answer || recorded?.finalResponse;
1066
+ const answer = finalAnswer || recorded?.assistantText || row.live;
1067
+ const changes = recorded && workspaceFileSummary(recorded, recorded.projectCwd ?? task.cwd);
1068
+ const changeCount = changes?.length ?? row.changeCount;
1069
+ const changeSummary = changes ? JSON.stringify(changes) : row.changeSummary;
1070
+ const startedAt = toolTimestamp(row.startedAt);
1071
+ const terminal = isTerminalTurnStatus(row.status);
1072
+ const recordedDuration = terminal && row.durationMs !== null && Number.isFinite(row.durationMs) && row.durationMs >= 0
1073
+ ? row.durationMs : undefined;
1074
+ const completedAt = terminal ? toolTimestamp(row.completedAt)
1075
+ ?? (startedAt !== undefined && recordedDuration !== undefined ? startedAt + recordedDuration : undefined) : undefined;
1076
+ const durationMs = recordedDuration ?? (startedAt !== undefined && completedAt !== undefined && completedAt >= startedAt
1077
+ ? completedAt - startedAt : undefined);
1078
+ const usage = terminal ? turnUsageFields(row) : undefined;
1079
+ return { id: turnId, status: row.status, startedAt, completedAt, durationMs,
1080
+ prompt: displaySubmittedPrompt(row.prompt, originalPrompt)?.slice(0, 24_000),
1081
+ usage: usage && (usage.tokens.length || usage.activity.length) ? [...usage.tokens, ...usage.activity] : undefined,
930
1082
  promptRequestId: row.promptRequestId ?? undefined,
1083
+ promptQuotes: originalPrompt?.quotes ?? this.scheduledAttachments(row.ownerTask, row.promptRequestId ?? undefined)?.quotes,
931
1084
  promptFiles: this.attachmentLinks(task.localSessionId, row.promptRequestId ?? undefined),
932
- promptImages: this.attachments(task, row.promptImages ? JSON.parse(row.promptImages) : undefined),
933
- answer: answer ? this.render(task, answer) : undefined, final: Boolean(answer && (row.answer || row.status === "completed")),
934
- answerExport: Boolean(row.answer), previewUrl: row.answer ? this.viewer.createTurnPreviewUrl(turnId) : undefined,
1085
+ promptImages: this.attachments(task, savedPrompt?.attachments.images.length ? savedPrompt.attachments.images
1086
+ : row.promptImages ? JSON.parse(row.promptImages) : undefined),
1087
+ answer: answer ? this.render(task, answer) : undefined, final: Boolean(answer && (finalAnswer || row.status === "completed")),
1088
+ answerExport: Boolean(finalAnswer), previewUrl: finalAnswer ? this.viewer.createTurnPreviewUrl(turnId) : undefined,
935
1089
  timeline: workspaceTimeline(activities, reasoning, answer, current && activeTaskStatuses.has(row.status)).map((item) => {
936
1090
  if (item.kind === "execution")
937
1091
  return item;
938
1092
  if (item.kind === "reasoning")
939
- return { id: item.id, kind: item.kind, rich: this.render(task, item.text, true) };
940
- const images = item.kind === "user" ? this.attachments(task, item.images) : undefined;
941
- const rich = item.text && item.kind === "assistant" ? this.render(task, item.text, true) : undefined;
1093
+ return { id: item.id, kind: item.kind, title: item.title,
1094
+ detail: item.detail ? this.render(task, item.detail, true) : undefined };
942
1095
  const requestId = item.kind === "user" && item.id.startsWith("steer:workspace:") ? item.id.slice("steer:workspace:".length) : undefined;
943
- return { id: item.id, kind: item.kind, text: rich ? undefined : item.text, images, rich, requestId,
944
- files: this.attachmentLinks(task.localSessionId, requestId) };
1096
+ const submitted = this.savedPrompt(task.localSessionId, requestId);
1097
+ const original = row.ownerTask === task.localSessionId ? submitted : this.savedPrompt(row.ownerTask, requestId);
1098
+ const storedImages = submitted?.attachments.images;
1099
+ const images = item.kind === "user" ? this.attachments(task, storedImages?.length ? storedImages : item.images) : undefined;
1100
+ const rich = item.text && item.kind === "assistant" ? this.render(task, item.text, true) : undefined;
1101
+ return { id: item.id, kind: item.kind, text: rich ? undefined : displaySubmittedPrompt(item.text, original), images, rich, requestId,
1102
+ startedAt: item.kind === "user" ? toolTimestamp(item.startedAt) : undefined,
1103
+ files: this.attachmentLinks(task.localSessionId, requestId),
1104
+ quotes: original?.quotes };
945
1105
  }),
946
- hasDetails: row.changeCount > 0, fileChangeCount: row.changeCount || undefined,
947
- detailRevision: row.changeSummary && row.changeCount ? hash(row.changeSummary) : undefined,
948
- compact: Boolean(row.compact),
949
- error: row.error || row.notice ? displayRuntimeError(row.error || row.notice) : undefined, summary: row.detail === "summary",
950
- delivered: row.status === "completed" && row.answer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined, };
1106
+ hasDetails: changeCount > 0, fileChangeCount: changeCount || undefined,
1107
+ detailRevision: changeSummary && changeCount ? hash(changeSummary) : undefined,
1108
+ compact: recorded ? Boolean(recorded.activitiesTruncated) : Boolean(row.compact),
1109
+ error: row.error || row.notice ? displayRuntimeError(row.error || row.notice) : undefined, summary: !recorded && row.detail === "summary",
1110
+ delivered: row.status === "completed" && finalAnswer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined, };
951
1111
  }
952
- async toolPage(task, state, toolId, offset, revision) {
1112
+ async toolPage(task, state, toolId, offset, revision, patch) {
953
1113
  const journal = this.options.store.previews;
954
- const read = (snapshot) => journal.toolTextPage(snapshot.previewTurnId ?? snapshot.turnId, toolId, offset, MAX_EXECUTION_CHARS);
1114
+ const read = (snapshot) => journal.toolTextPage(snapshot.previewTurnId ?? snapshot.turnId, toolId, patch ? 0 : offset, patch ? 0 : MAX_EXECUTION_CHARS);
955
1115
  let page = await read(state);
956
1116
  if (!page && state.historyDetail === "summary" && this.options.loadTurnDetails && !journal.has(state.previewTurnId ?? state.turnId)) {
957
1117
  state = await this.options.loadTurnDetails(state.turnId) ?? state;
@@ -960,8 +1120,15 @@ export class WorkspaceSessions {
960
1120
  if (page && "busy" in page)
961
1121
  throw new RequestError(429, "正在读取其他工具记录,请稍后重试。");
962
1122
  const activity = state.activities?.find((item) => item.kind === "tool" && item.id === toolId);
963
- const files = offset === 0 ? page?.files ?? (activity?.kind === "tool" ? activity.tool.files : undefined) : undefined;
964
- const fileDetails = files?.length ? this.toolFiles(task, state.projectCwd ?? task.cwd, files) : {};
1123
+ const files = page?.files ?? (activity?.kind === "tool" ? activity.tool.files : undefined);
1124
+ if (patch) {
1125
+ const file = files?.slice(0, MAX_TOOL_FILE_ENTRIES).find((file) => file.patch && toolPatchId(file) === patch);
1126
+ if (!file?.patch)
1127
+ throw new RequestError(404, "此工具的文件补丁已不可用。");
1128
+ const notice = file.patchTruncated ? '<div class="workspace-notice">仅显示已保存的补丁开头。</div>' : "";
1129
+ return { html: notice + renderRecordedDiff(file.patch, file.moveTo || file.path, file.path, file.additions, file.deletions) };
1130
+ }
1131
+ const fileDetails = offset === 0 && files?.length ? this.toolFiles(task, state.projectCwd ?? task.cwd, files) : {};
965
1132
  if (page) {
966
1133
  if (revision && revision !== page.revision)
967
1134
  throw new RequestError(409, "工具日志已更新,请从开头重新读取。");
@@ -990,15 +1157,16 @@ export class WorkspaceSessions {
990
1157
  const entries = files.slice(0, MAX_TOOL_FILE_ENTRIES).map(({ path: recordedPath, moveTo, additions, deletions, patch, patchTruncated }) => {
991
1158
  const target = path.resolve(cwd, moveTo || recordedPath);
992
1159
  const patchHtml = patch ? highlightRecordedPatch(patch, target, recordedPath) : undefined;
1160
+ const patchId = patch ? toolPatchId({ path: recordedPath, moveTo }) : undefined;
993
1161
  const name = (primary && this.relativeWorkspaceEntry(primary, target)) || target;
994
1162
  for (const { root, source } of roots) {
995
1163
  const entry = this.projectFileEntry(root, target);
996
1164
  if (entry) {
997
1165
  const original = moveTo ? this.projectFileEntry(root, path.resolve(cwd, recordedPath)) : undefined;
998
- return { name, entry, source, original, additions, deletions, patch, patchHtml, patchTruncated };
1166
+ return { name, entry, source, original, additions, deletions, patch, patchHtml, patchTruncated, patchId };
999
1167
  }
1000
1168
  }
1001
- return { name, additions, deletions, patch, patchHtml, patchTruncated };
1169
+ return { name, additions, deletions, patch, patchHtml, patchTruncated, patchId };
1002
1170
  });
1003
1171
  return { files: entries, filesTruncated: files.length > entries.length || undefined };
1004
1172
  }
@@ -1052,18 +1220,68 @@ export class WorkspaceSessions {
1052
1220
  return;
1053
1221
  const files = new Set(paths.filter((file) => typeof file === "string" && !!file));
1054
1222
  return [...files].slice(0, 20).map((file) => {
1055
- const url = this.imageUrl(file) ?? this.imageUrl(file, task);
1056
- return url ? url.pathname + url.search : null;
1223
+ const inbound = this.imageUrl(file);
1224
+ const url = inbound ?? this.imageUrl(file, task);
1225
+ if (!url)
1226
+ return null;
1227
+ if (inbound && /\.png$/iu.test(file)) {
1228
+ const size = this.inboundPngSize(url.searchParams.get("entry"));
1229
+ if (size)
1230
+ url.hash = `size=${size.join("x")}`;
1231
+ }
1232
+ return url.pathname + url.search + url.hash;
1057
1233
  });
1058
1234
  }
1235
+ inboundPngSize(entry) {
1236
+ if (this.attachmentSizes.has(entry))
1237
+ return this.attachmentSizes.get(entry);
1238
+ let size = null;
1239
+ try {
1240
+ const file = resolveWorkspacePath(this.imageRoot(), entry);
1241
+ const stat = statSync(file);
1242
+ if (stat.isFile()) {
1243
+ const fd = openSync(file, "r");
1244
+ try {
1245
+ const bytes = Buffer.alloc(Math.min(WORKSPACE_PNG_HEADER_BYTES, stat.size));
1246
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
1247
+ size = workspacePngDisplaySize(new DataView(bytes.buffer, bytes.byteOffset, length)) ?? null;
1248
+ }
1249
+ finally {
1250
+ closeSync(fd);
1251
+ }
1252
+ }
1253
+ }
1254
+ catch { /* Display dimensions are optional when an attachment is unavailable. */ }
1255
+ if (this.attachmentSizes.size >= 256)
1256
+ this.attachmentSizes.delete(this.attachmentSizes.keys().next().value);
1257
+ this.attachmentSizes.set(entry, size);
1258
+ return size;
1259
+ }
1260
+ savedPrompt(task, request) {
1261
+ if (!request)
1262
+ return;
1263
+ const record = this.options.store.getTaskMetadata(task, workspacePromptKind, request);
1264
+ if (record)
1265
+ return savedWorkspacePrompt.parse(JSON.parse(record));
1266
+ }
1059
1267
  attachmentEntries(task, request) {
1060
1268
  const saved = this.options.store.getTaskMetadata(task, attachmentKind, request);
1061
1269
  if (saved)
1062
1270
  return z.array(attachmentEntry).parse(JSON.parse(saved));
1271
+ const files = this.scheduledAttachments(task, request)?.files;
1272
+ if (files?.length)
1273
+ return this.promptFileEntries(files);
1274
+ }
1275
+ quotesForRequest(task, request) {
1276
+ return this.savedPrompt(task, request)?.quotes ?? this.scheduledAttachments(task, request)?.quotes;
1277
+ }
1278
+ scheduledAttachments(task, request) {
1279
+ if (!request)
1280
+ return;
1063
1281
  const run = this.options.store.schedules.getRun(`schedule_run_${request}`);
1064
1282
  const job = run && this.options.store.schedules.get(run.jobId);
1065
- if (job?.localSessionId === task && job.attachments?.files.length)
1066
- return this.promptFileEntries(job.attachments.files);
1283
+ if (job?.localSessionId === task)
1284
+ return job.attachments;
1067
1285
  }
1068
1286
  attachmentLinks(task, request) {
1069
1287
  if (!request)
@@ -1114,8 +1332,10 @@ export class WorkspaceSessions {
1114
1332
  const cacheKey = hash(`${task.localSessionId}\0${task.cwd}\0${short}\0${text}`), cached = this.rendered.get(cacheKey);
1115
1333
  if (cached)
1116
1334
  return cached;
1117
- const truncated = text.length > 48_000;
1118
- const env = {}, tokens = markdown.parse(text.slice(0, 48_000), env);
1335
+ const plain = () => ({ html: `<p>${markdown.utils.escapeHtml(text).replace(/\r?\n/gu, "<br>\n")}</p>` });
1336
+ if (text.length > 48_000)
1337
+ return plain();
1338
+ const env = {}, tokens = markdown.parse(text, env);
1119
1339
  const imagePrefix = this.base.origin + this.base.pathname + "/image?";
1120
1340
  const visit = (items) => {
1121
1341
  for (const item of items) {
@@ -1160,9 +1380,7 @@ export class WorkspaceSessions {
1160
1380
  }, (file) => this.imageUrl(file, task));
1161
1381
  visit(tokens);
1162
1382
  const html = markdown.renderer.render(tokens, markdown.options, env);
1163
- const result = html.length <= (short ? 12_000 : 220_000)
1164
- ? { html, truncated }
1165
- : { html: `<p>${markdown.utils.escapeHtml(text.slice(0, short ? 4_000 : 24_000))}</p>`, truncated: true };
1383
+ const result = html.length <= (short ? 12_000 : 220_000) ? { html } : plain();
1166
1384
  if (this.rendered.size >= 48)
1167
1385
  this.rendered.delete(this.rendered.keys().next().value);
1168
1386
  this.rendered.set(cacheKey, result);
@@ -1186,9 +1404,10 @@ export class WorkspaceSessions {
1186
1404
  // Reconnects always reconcile with an authoritative snapshot; no per-token replay is needed.
1187
1405
  this.event(stream, "sync", { revision: WORKSPACE_REVISION, instance: WORKSPACE_INSTANCE });
1188
1406
  }
1189
- poll() {
1190
- if (!this.streams.size && !this.grants.size)
1407
+ async poll() {
1408
+ if (this.polling || (!this.streams.size && !this.grants.size))
1191
1409
  return;
1410
+ this.polling = true;
1192
1411
  try {
1193
1412
  const at = Date.now();
1194
1413
  if (at >= this.nextPrune) {
@@ -1218,26 +1437,38 @@ export class WorkspaceSessions {
1218
1437
  stream.catalogue = this.catalogue;
1219
1438
  this.event(stream, "tasks", {});
1220
1439
  }
1221
- if (stream.task) {
1222
- if (!tails.has(stream.task)) {
1223
- const task = this.options.store.getSession(stream.task);
1440
+ const { task: taskId, generation } = stream;
1441
+ if (taskId) {
1442
+ if (!tails.has(taskId)) {
1443
+ const task = this.options.store.getSession(taskId);
1224
1444
  if (task && this.eligible(task)) {
1225
- const head = this.head(task), turn = head ? this.turn(task, head, true) : null;
1226
- tails.set(stream.task, { task: { ...this.describe(task), promptPreview: workspacePromptPreview(turn?.prompt),
1445
+ const head = this.head(task);
1446
+ const queue = this.describeQueue(task.localSessionId);
1447
+ const queueKey = JSON.stringify(queue.queuedPrompts.map(({ id, revision, hasAttachments, dispatching }) => [id, revision, hasAttachments, dispatching]));
1448
+ const turn = head ? await this.turn(task, head, true) : null;
1449
+ if (!this.timer)
1450
+ return;
1451
+ const value = { task: { ...this.describe(task), promptPreview: workspacePromptPreview(turn?.prompt),
1227
1452
  metrics: this.conversationMetrics(task, head),
1228
1453
  directories: listTaskDirectories(this.options.store, task.localSessionId) },
1229
- ...this.describeQueue(task.localSessionId), turn,
1454
+ turn,
1230
1455
  execution: this.activeExecution(task, head, turn?.status),
1231
1456
  plan: head ? this.options.store.workspaceTurnPlan(head) : [],
1232
- parent: head ? this.options.store.getTurnParent(head, task.localSessionId) : undefined });
1457
+ parent: head ? this.options.store.getTurnParent(head, task.localSessionId) : undefined };
1458
+ tails.set(taskId, { value, queue, queueKey });
1233
1459
  }
1234
1460
  else
1235
- tails.set(stream.task, null);
1461
+ tails.set(taskId, null);
1236
1462
  }
1237
- const next = JSON.stringify(tails.get(stream.task));
1238
- if (next !== stream.tail) {
1463
+ if (stream.task !== taskId || stream.generation !== generation || stream.response.writableEnded || stream.grant.signal.aborted)
1464
+ continue;
1465
+ const tail = tails.get(taskId);
1466
+ const next = JSON.stringify(tail?.value ?? null), queueChanged = tail?.queueKey !== stream.queue;
1467
+ if (next !== stream.tail || queueChanged) {
1239
1468
  stream.tail = next;
1240
- this.event(stream, "tail", { taskId: stream.task, generation: stream.generation, value: tails.get(stream.task) });
1469
+ stream.queue = tail?.queueKey;
1470
+ const value = tail ? (queueChanged ? { ...tail.value, ...tail.queue } : tail.value) : null;
1471
+ this.event(stream, "tail", { taskId, generation, value });
1241
1472
  }
1242
1473
  }
1243
1474
  if (at - stream.heartbeat > 15_000) {
@@ -1249,6 +1480,9 @@ export class WorkspaceSessions {
1249
1480
  catch (error) {
1250
1481
  this.options.logger.warn({ error }, "Failed to refresh Workspace events.");
1251
1482
  }
1483
+ finally {
1484
+ this.polling = false;
1485
+ }
1252
1486
  }
1253
1487
  event(stream, kind, payload) {
1254
1488
  if (stream.response.writableEnded)
@@ -1285,17 +1519,28 @@ export class WorkspaceSessions {
1285
1519
  store.beginWorkspaceRequest(input.request, task.localSessionId, fingerprint);
1286
1520
  this.lastSubmissionAt = Math.max(Date.now(), (this.lastSubmissionAt ?? 0) + 1);
1287
1521
  this.running.add(input.request);
1288
- let ambiguous = input.action === "stop", directory;
1522
+ let ambiguous = input.action === "stop", directory, persisted = false;
1289
1523
  try {
1290
- let localImagePaths, localFiles = [];
1291
- if (images.length || files.length) {
1524
+ const existing = previous ? this.savedPrompt(task.localSessionId, input.request) : undefined;
1525
+ let attachments = existing?.attachments ?? { images: [], files: [] };
1526
+ if (!existing && (images.length || files.length)) {
1292
1527
  const saved = await this.writePromptAttachments(images, files);
1293
1528
  directory = saved.directory;
1294
- localImagePaths = saved.attachments.images.length ? saved.attachments.images : undefined;
1295
- localFiles = saved.attachments.files;
1296
- if (localFiles.length) {
1297
- store.setTaskMetadata(task.localSessionId, attachmentKind, input.request, JSON.stringify(this.promptFileEntries(localFiles)));
1529
+ attachments = saved.attachments;
1530
+ }
1531
+ const localImagePaths = attachments.images.length ? attachments.images : undefined;
1532
+ const localFiles = attachments.files;
1533
+ if (localFiles.length && !existing) {
1534
+ store.setTaskMetadata(task.localSessionId, attachmentKind, input.request, JSON.stringify(this.promptFileEntries(localFiles)));
1535
+ }
1536
+ const quotes = input.action !== "stop" && input.quotes?.length ? input.quotes : undefined;
1537
+ if (input.action !== "stop" && (input.action !== "queue" || quotes?.length)) {
1538
+ if (!existing) {
1539
+ store.setTaskMetadata(task.localSessionId, workspacePromptKind, input.request, JSON.stringify({
1540
+ text: input.text, action: input.action, turn: input.action === "steer" ? input.turn : undefined, attachments, quotes,
1541
+ }));
1298
1542
  }
1543
+ persisted = true;
1299
1544
  }
1300
1545
  if (input.action === "stop") {
1301
1546
  const result = await this.options.controller.controlStopTask(task.localSessionId, input.turn);
@@ -1303,15 +1548,16 @@ export class WorkspaceSessions {
1303
1548
  }
1304
1549
  else if (input.action === "queue") {
1305
1550
  ambiguous = true;
1306
- await this.options.controller.controlQueueTaskPrompt(task.localSessionId, input.text, localImagePaths, input.request, ...(localFiles.length ? [localFiles] : []));
1551
+ await this.options.controller.controlQueueTaskPrompt(task.localSessionId, input.text, localImagePaths, input.request, localFiles.length ? localFiles : undefined, quotes);
1307
1552
  store.updateWorkspaceRequest(input.request, "accepted");
1308
1553
  }
1309
1554
  else {
1310
1555
  await this.options.controller.controlSendTaskPrompt(task.localSessionId, input.text, {
1311
1556
  requestId: input.request, localImagePaths, ...(localFiles.length ? { files: localFiles } : {}),
1557
+ ...(quotes ? { quotes } : {}),
1312
1558
  ...(input.action === "steer" ? { expectedTurnId: input.turn } : {}),
1313
- onPosting: () => { ambiguous = true; },
1314
- onPosted: () => { store.updateWorkspaceRequest(input.request, "pending", true); },
1559
+ onSubmitting: () => { ambiguous = true; },
1560
+ onPosted: () => { store.markWorkspaceRequestPosted(input.request); },
1315
1561
  });
1316
1562
  store.updateWorkspaceRequest(input.request, "accepted");
1317
1563
  }
@@ -1319,8 +1565,9 @@ export class WorkspaceSessions {
1319
1565
  catch (error) {
1320
1566
  const message = displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "操作未完成。");
1321
1567
  const stale = input.action === "steer" && error instanceof TurnNotSubmittedError;
1322
- store.updateWorkspaceRequest(input.request, stale ? "stale" : ambiguous ? "unknown" : "failed", false, message);
1323
- if (directory && (!ambiguous || stale)) {
1568
+ const unknown = ambiguous && !(error instanceof TurnNotSubmittedError);
1569
+ store.updateWorkspaceRequest(input.request, stale ? "stale" : unknown ? "unknown" : "failed", false, message);
1570
+ if (directory && !persisted && (!unknown || stale)) {
1324
1571
  if (files.length)
1325
1572
  store.removeTaskMetadata(task.localSessionId, attachmentKind, input.request);
1326
1573
  await this.removePromptAttachments(directory);