@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,5 +1,6 @@
1
1
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
3
4
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
5
  import type { Duplex } from "node:stream";
5
6
  import path from "node:path";
@@ -16,21 +17,24 @@ import { scheduleDisplayPrompt, scheduleInputSchema, type ScheduledJob, type Sch
16
17
  import type { ToolState } from "../runtime/types.js";
17
18
  import type { QueuedPromptRecord, SessionRecord, StateStore } from "../state/StateStore.js";
18
19
  import type { FileSummary, TurnViewState } from "../presentation/turnViewTypes.js";
20
+ import { isTerminalTurnStatus } from "../presentation/turnStatus.js";
19
21
  import { toolTextFields } from "../state/TurnToolText.js";
20
22
  import { formatPreviewToolCommand, normalizeToolOutput } from "./ToolCommandDisplay.js";
21
- import { workspaceTimeline, type WorkspaceActivity, type WorkspaceReasoning } from "./WorkspaceTimeline.js";
22
- import { workspaceImageExtension } from "./WorkspaceImages.js";
23
+ import { recordedWorkspaceTimeline, workspaceTimeline, type WorkspaceActivity, type WorkspaceReasoning } from "./WorkspaceTimeline.js";
24
+ import { WORKSPACE_PNG_HEADER_BYTES, workspaceImageExtension, workspacePngDisplaySize } from "./WorkspaceImages.js";
23
25
  import type { LocalFileViewerServer, LocalFileViewerService } from "./LocalFileViewerServer.js";
24
26
  import { isFileUrl, rewriteMarkdownFileLinks } from "./MarkdownFileLinks.js";
25
27
  import { highlightPreviewCode } from "./PreviewSyntaxHighlight.js";
26
- import { highlightRecordedPatch } from "./GitDiffPreview.js";
28
+ import { highlightRecordedPatch, renderRecordedDiff } from "./GitDiffPreview.js";
27
29
  import { WORKSPACE_INSTANCE, WORKSPACE_INSTANCE_HEADER, WORKSPACE_REVISION, WORKSPACE_REVISION_HEADER } from "./WorkspacePage.js";
28
30
  import { resolveWorkspaceDirectoryAddress, resolveWorkspacePath, WorkspaceError } from "./WorkspaceFiles.js";
29
31
  import { directWorkspaceOrigin } from "./WorkspaceOrigin.js";
30
32
  import { turnAnswerFilename } from "./MarkdownExport.js";
33
+ import { turnUsageFields } from "./TurnPreviewPage.js";
31
34
  import { toolTimestamp } from "../utils/toolTimestamp.js";
32
35
  import { formatStorageSize } from "../utils/formatStorageSize.js";
33
36
  import { defaultResourcePromptFromCounts, queuedPromptContent } from "../utils/promptAttachments.js";
37
+ import { promptQuoteInstruction, promptQuotesSchema } from "../utils/promptQuotes.js";
34
38
  import type { TerminalWorkspaceAccess } from "../terminal/TerminalServer.js";
35
39
 
36
40
  const TTL = 8 * 60 * 60_000;
@@ -41,12 +45,29 @@ const MAX_EXECUTION_CHARS = 32_000;
41
45
  const MAX_TOOL_FILE_ENTRIES = 200;
42
46
  const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
43
47
  const MAX_ATTACHMENT_TOTAL = 12 * 1024 * 1024;
44
- const MAX_OPERATION_BYTES = Math.ceil(MAX_ATTACHMENT_TOTAL / 3) * 4 + 150_000;
48
+ const MAX_OPERATION_BYTES = Math.ceil(MAX_ATTACHMENT_TOTAL / 3) * 4 + 1024 * 1024;
45
49
  const attachmentData = z.string().max(Math.ceil(MAX_ATTACHMENT_BYTES / 3) * 4);
46
50
  const attachmentKind = "workspace-prompt-files";
51
+ const workspacePromptKind = "workspace-prompt";
47
52
  const id = z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u);
53
+ const toolPatchId = (file: Pick<NonNullable<ToolState["files"]>[number], "path" | "moveTo">) =>
54
+ hash(JSON.stringify([file.path, file.moveTo])).slice(0, 32);
48
55
  const key = z.uuid();
49
56
  const imageEntry = z.string().min(1).max(4096).regex(/^[^\x00-\x1f\x7f]+$/u);
57
+ const savedWorkspacePrompt = z.object({
58
+ action: z.enum(["send", "steer", "queue"]),
59
+ text: z.string(),
60
+ turn: id.optional(),
61
+ quotes: promptQuotesSchema.optional(),
62
+ attachments: z.object({
63
+ images: z.array(z.string()),
64
+ files: z.array(z.object({ fileName: z.string(), filePath: z.string() })),
65
+ }),
66
+ });
67
+ function displaySubmittedPrompt(text: string | null, saved?: z.output<typeof savedWorkspacePrompt>) {
68
+ if (saved?.quotes?.length && !saved.text && text === promptQuoteInstruction(saved.quotes)) return "";
69
+ return text ?? saved?.text;
70
+ }
50
71
  const directoryPanelKind = "workspace-directory-panel";
51
72
  const directoryPanelKey = "state";
52
73
  const maxDirectoryTabs = 24;
@@ -69,14 +90,18 @@ const taskSetting = z.object({ task: id, setting: z.enum(["model", "thinking"]),
69
90
  const turnAction = z.object({ task: id, turn: id, action: z.enum(["reset", "fork"]) }).strict();
70
91
  const queueRevision = z.string().regex(/^[a-f0-9]{64}$/u);
71
92
  const queueCancel = z.object({ task: id, prompt: id, request: key, revision: queueRevision.optional() }).strict();
93
+ const queueSend = z.object({ task: id, prompt: id, request: key, revision: queueRevision }).strict();
72
94
  const queueEdit = z.object({ task: id, prompt: id, revision: queueRevision, text: z.string().trim().max(24_000) }).strict();
73
95
  const attachmentEntry = z.object({ name: z.string().min(1).max(255), entry: imageEntry });
74
96
  const uploadFields = {
75
97
  images: z.array(attachmentData.min(1)).max(4).optional(),
76
- files: z.array(z.object({ name: attachmentEntry.shape.name, data: attachmentData }).strict()).max(4).optional() };
98
+ files: z.array(z.object({ name: attachmentEntry.shape.name, data: attachmentData }).strict()).max(4).optional(),
99
+ quotes: promptQuotesSchema.optional() };
100
+ const promptAttachmentCount = (input: { images?: unknown[]; files?: unknown[]; quotes?: unknown[] }) =>
101
+ (input.images?.length ?? 0) + (input.files?.length ?? 0) + (input.quotes?.length ?? 0);
77
102
  const scheduleCreate = z.object({ task: id, request: key, schedule: scheduleInputSchema, ...uploadFields }).strict()
78
- .refine(input => Boolean(input.schedule.prompt || input.images?.length || input.files?.length)
79
- && (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4, "请输入 Prompt 或添加至多 4 个附件。");
103
+ .refine(input => Boolean(input.schedule.prompt || promptAttachmentCount(input))
104
+ && promptAttachmentCount(input) <= 4, "请输入 Prompt 或添加至多 4 个附件。");
80
105
  const scheduleActionFields = { task: id, job: id, revision: z.int().positive() };
81
106
  const scheduleAction = z.discriminatedUnion("action", [
82
107
  z.object({ ...scheduleActionFields, action: z.literal("edit"), schedule: scheduleInputSchema }).strict(),
@@ -87,8 +112,7 @@ const instruction = z.discriminatedUnion("action", [
87
112
  z.object({ action: z.enum(["send", "queue"]), ...promptFields }).strict(),
88
113
  z.object({ action: z.literal("steer"), turn: id, ...promptFields }).strict(),
89
114
  z.object({ action: z.literal("stop"), task: id, request: key, turn: id }).strict(),
90
- ]).refine((input) => input.action === "stop" || (Boolean(input.text || input.images?.length || input.files?.length)
91
- && (input.images?.length ?? 0) + (input.files?.length ?? 0) <= 4));
115
+ ]).refine((input) => input.action === "stop" || (Boolean(input.text || promptAttachmentCount(input)) && promptAttachmentCount(input) <= 4));
92
116
  const markdown = new MarkdownIt({ html: false, breaks: true, linkify: true, highlight: highlightPreviewCode });
93
117
  markdown.renderer.rules.table_open = (tokens, index, options, _env, renderer) =>
94
118
  '<div class="markdown-table-scroll" role="region" aria-label="Markdown 表格" tabindex="0">' + renderer.renderToken(tokens, index, options);
@@ -154,7 +178,7 @@ interface Grant extends TerminalWorkspaceAccess {
154
178
  }
155
179
  interface Stream {
156
180
  grant: Grant; response: ServerResponse; version: number; generation: number;
157
- task?: string; tail?: string; catalogue: number; heartbeat: number;
181
+ task?: string; tail?: string; queue?: string; catalogue: number; heartbeat: number;
158
182
  }
159
183
  interface WorkspaceSessionOptions {
160
184
  store: StateStore;
@@ -162,8 +186,8 @@ interface WorkspaceSessionOptions {
162
186
  owner(): string | undefined;
163
187
  password(): string | undefined;
164
188
  controller: Pick<ProxySessionController, "controlSendTaskPrompt" | "controlQueueTaskPrompt" | "controlStopTask"
165
- | "controlWorkspaceAgents" | "controlWorkspaceDraftSettings" | "controlCreateWorkspaceTask" | "controlTaskSettings"
166
- | "controlResetTaskToTurn" | "controlForkWorkspaceTask" | "controlCancelWorkspaceQueue" | "controlEditWorkspaceQueue" | "controlCreateWorkspaceSchedule"
189
+ | "controlWorkspaceAgents" | "controlWorkspaceDraftSettings" | "controlCreateWorkspaceTask" | "controlTaskSettings" | "controlSetTaskTitle"
190
+ | "controlResetTaskToTurn" | "controlForkWorkspaceTask" | "controlCancelWorkspaceQueue" | "controlEditWorkspaceQueue" | "controlSendWorkspaceQueuedPrompt" | "controlCreateWorkspaceSchedule"
167
191
  | "controlEditWorkspaceSchedule" | "controlWorkspaceScheduleAction">;
168
192
  loadTurnDetails?: ProxySessionController["loadTurnDetails"];
169
193
  canSubmit(): boolean; // Closed during startup or the final shutdown handoff, not while waiting for a safe restart.
@@ -185,12 +209,14 @@ export class WorkspaceSessions implements LocalFileViewerService {
185
209
  private readonly turnActions = new Set<string>();
186
210
  private readonly imageSecret = randomBytes(32);
187
211
  private readonly failures: { address: string; at: number }[] = [];
188
- private readonly rendered = new Map<string, { html: string; truncated: boolean }>();
212
+ private readonly rendered = new Map<string, { html: string }>();
213
+ private readonly attachmentSizes = new Map<string, [number, number] | null>();
189
214
  private readonly metricsCache = new Map<string, { head?: string; expires: number; value: ConversationMetrics }>();
190
215
  private catalogue = 0;
191
216
  private catalogueHash = "";
192
217
  private nextCatalogue = 0;
193
218
  private timer?: NodeJS.Timeout;
219
+ private polling = false;
194
220
  private nextPrune = 0;
195
221
  private operationBodies = 0;
196
222
  private lastSubmissionAt: number | undefined;
@@ -203,12 +229,13 @@ export class WorkspaceSessions implements LocalFileViewerService {
203
229
  }
204
230
  start(): string {
205
231
  this.base = new URL(this.viewer.mountService("workspace-app", this).publicBaseUrl);
206
- this.timer = setInterval(() => this.poll(), 400);
232
+ this.timer = setInterval(() => void this.poll(), 400);
207
233
  this.timer.unref();
208
234
  return this.base.pathname;
209
235
  }
210
236
  async close(): Promise<void> {
211
237
  clearInterval(this.timer);
238
+ this.timer = undefined;
212
239
  for (const stream of this.streams.values()) stream.response.end();
213
240
  this.streams.clear();
214
241
  for (const response of this.directoryStreams.keys()) response.end();
@@ -393,6 +420,15 @@ export class WorkspaceSessions implements LocalFileViewerService {
393
420
  });
394
421
  return;
395
422
  }
423
+ if (route === "/task-title" && request.method === "POST") {
424
+ const input = parse(z.object({ task: id, title: z.string().trim().min(1).max(120) }).strict(), await this.body(request));
425
+ const task = this.task(input.task);
426
+ await this.controlAction(grant, async () => {
427
+ await this.options.controller.controlSetTaskTitle(task.localSessionId, input.title, "workspace");
428
+ this.json(response, 200, { title: this.task(task.localSessionId).title });
429
+ });
430
+ return;
431
+ }
396
432
  if (route === "/task-settings") {
397
433
  const input = request.method === "POST" ? parse(taskSetting, await this.body(request)) : undefined;
398
434
  const task = this.task(input?.task ?? parse(id, url.searchParams.get("task")));
@@ -416,7 +452,9 @@ export class WorkspaceSessions implements LocalFileViewerService {
416
452
  if (after && (before || anchor)) throw new RequestError(400, "对话分页参数冲突。");
417
453
  const stream = after ? this.streams.get(url.searchParams.get("page") ?? "") : undefined;
418
454
  const version = stream?.grant === grant && stream.task === task.localSessionId ? stream.version : undefined;
419
- this.json(response, 200, { ...this.history(task, origin, before, anchor, after), version }); return;
455
+ const history = await this.history(task, origin, before, anchor, after);
456
+ if (!this.valid(grant)) throw new RequestError(401, "工作台会话已过期。");
457
+ this.json(response, 200, { ...history, version }); return;
420
458
  }
421
459
  if (route === "/focus" && request.method === "POST") {
422
460
  const input = parse(selection, await this.body(request));
@@ -424,25 +462,31 @@ export class WorkspaceSessions implements LocalFileViewerService {
424
462
  if (!stream || stream.grant !== grant) throw new RequestError(409, "实时连接尚未就绪。");
425
463
  if (input.generation < stream.generation) throw new RequestError(409, "所选任务已变更。");
426
464
  const task = input.task ? this.task(input.task) : undefined;
427
- stream.task = task?.localSessionId; stream.generation = input.generation; stream.tail = undefined;
428
- this.json(response, 200, { ...(task && this.history(task, origin, undefined, input.anchor)), version: stream.version, generation: stream.generation }); return;
465
+ stream.task = task?.localSessionId; stream.generation = input.generation; stream.tail = stream.queue = undefined;
466
+ const version = stream.version;
467
+ const history = task && await this.history(task, origin, undefined, input.anchor);
468
+ if (!this.valid(grant)) throw new RequestError(401, "工作台会话已过期。");
469
+ if (stream.task !== input.task || stream.generation !== input.generation) throw new RequestError(409, "所选任务已变更。");
470
+ this.json(response, 200, { ...history, version, generation: input.generation }); return;
429
471
  }
430
472
  if (route === "/queue" && request.method === "GET") {
431
473
  const task = this.task(parse(id, url.searchParams.get("task")));
432
474
  const promptId = parse(id, url.searchParams.get("prompt"));
433
475
  const prompt = this.requireQueuedPrompt(task.localSessionId, promptId);
434
- const run = this.options.store.schedules.getRun(promptId);
435
- const requestId = run ? run.id.slice("schedule_run_".length)
436
- : promptId.startsWith("workspace:") ? key.safeParse(promptId.slice("workspace:".length)).data : undefined;
476
+ const requestId = this.queuedPromptRequest(promptId);
437
477
  const files = this.attachmentLinks(task.localSessionId, requestId);
438
- this.json(response, 200, { text: run ? queuedPromptContent(prompt).text : files?.length ? prompt.displayPrompt ?? prompt.text : prompt.text,
439
- revision: queuePromptRevision(prompt), files, images: this.attachments(task, prompt.localImagePaths) });
478
+ const quotes = this.quotesForRequest(task.localSessionId, requestId);
479
+ const text = quotes?.length || promptId.startsWith("schedule_run_") ? queuedPromptContent(prompt, quotes).text
480
+ : files?.length ? prompt.displayPrompt ?? prompt.text : prompt.text;
481
+ this.json(response, 200, { text,
482
+ revision: queuePromptRevision(prompt), files, quotes, images: this.attachments(task, prompt.localImagePaths) });
440
483
  return;
441
484
  }
442
485
  if (route === "/queue/edit" && request.method === "GET") {
443
486
  const task = this.task(parse(id, url.searchParams.get("task")));
444
487
  const prompt = this.requireQueuedPrompt(task.localSessionId, parse(id, url.searchParams.get("prompt")));
445
- this.json(response, 200, { text: queuedPromptContent(prompt).text, revision: queuePromptRevision(prompt) });
488
+ const quotes = this.quotesForRequest(task.localSessionId, this.queuedPromptRequest(prompt.promptId));
489
+ this.json(response, 200, { text: queuedPromptContent(prompt, quotes).text, revision: queuePromptRevision(prompt) });
446
490
  return;
447
491
  }
448
492
  if (route === "/queue/edit" && request.method === "POST") {
@@ -450,12 +494,13 @@ export class WorkspaceSessions implements LocalFileViewerService {
450
494
  await this.controlAction(grant, async () => {
451
495
  this.task(input.task);
452
496
  const prompt = this.requireQueuedPrompt(input.task, input.prompt);
453
- const content = queuedPromptContent(prompt);
497
+ const quotes = this.quotesForRequest(input.task, this.queuedPromptRequest(prompt.promptId));
498
+ const content = queuedPromptContent(prompt, quotes);
454
499
  if (input.text === content.text) { this.json(response, 200, this.describeQueuedPrompt(prompt)); return; }
455
500
  if (input.revision !== queuePromptRevision(prompt)) throw new RequestError(409, "这条消息已被修改,请重新打开编辑。");
456
501
  const images = prompt.localImagePaths?.length ?? 0;
457
- if (!input.text && !images && !content.fileCount) throw new RequestError(400, "请输入消息内容。");
458
- const text = input.text || (content.fileCount ? defaultResourcePromptFromCounts(images, content.fileCount) : "");
502
+ if (!input.text && !images && !content.fileCount && !quotes?.length) throw new RequestError(400, "请输入消息内容。");
503
+ const text = input.text || promptQuoteInstruction(quotes) || (content.fileCount ? defaultResourcePromptFromCounts(images, content.fileCount) : "");
459
504
  const run = this.options.store.schedules.getRun(prompt.promptId);
460
505
  const job = run && this.options.store.schedules.get(run.jobId);
461
506
  const displayPrompt = job && run
@@ -482,6 +527,11 @@ export class WorkspaceSessions implements LocalFileViewerService {
482
527
  });
483
528
  return;
484
529
  }
530
+ if (route === "/queue/send" && request.method === "POST") {
531
+ const input = parse(queueSend, await this.body(request));
532
+ await this.controlAction(grant, async () => this.json(response, 200, await this.sendQueuedPrompt(input)));
533
+ return;
534
+ }
485
535
  if (route === "/schedules" && request.method === "GET") {
486
536
  const task = this.task(parse(id, url.searchParams.get("task")));
487
537
  const offset = parse(z.coerce.number().int().min(0).max(1_000_000), url.searchParams.get("offset") ?? 0);
@@ -558,7 +608,8 @@ export class WorkspaceSessions implements LocalFileViewerService {
558
608
  const toolId = parse(id, url.searchParams.get("tool"));
559
609
  const offset = parse(z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER - MAX_EXECUTION_CHARS), url.searchParams.get("offset") ?? 0);
560
610
  const revision = parse(z.string().max(64).optional(), url.searchParams.get("revision") ?? undefined);
561
- const page = await this.toolPage(task, state, toolId, offset, revision);
611
+ const patch = parse(z.string().regex(/^[a-f0-9]{32}$/u).optional(), url.searchParams.get("patch") ?? undefined);
612
+ const page = await this.toolPage(task, state, toolId, offset, revision, patch);
562
613
  if (grant.signal.aborted || !this.valid(grant)) throw new RequestError(401, "工作台会话已过期。");
563
614
  const currentHead = this.head(this.task(task.localSessionId));
564
615
  if (currentHead !== head && currentHead !== turn && this.options.store.workspaceTurnPage(task.localSessionId, currentHead, turn, 1).beforeMissing) {
@@ -567,12 +618,14 @@ export class WorkspaceSessions implements LocalFileViewerService {
567
618
  this.json(response, 200, page);
568
619
  return;
569
620
  }
570
- const cwd = state.projectCwd ?? task.cwd;
571
- const changes = this.toolFiles(task, cwd, workspaceFileSummary(state, cwd));
621
+ const saved = await this.recordedTurn(turn, state.previewTurnId, state.continuedToTurnId) ?? state;
622
+ if (!this.valid(grant)) throw new RequestError(401, "工作台会话已过期。");
623
+ this.requireBranchTurn(this.task(task.localSessionId), turn);
624
+ const cwd = saved.projectCwd ?? task.cwd;
625
+ const changes = this.toolFiles(task, cwd, workspaceFileSummary(saved, cwd));
572
626
  this.json(response, 200, {
573
- plan: (state.plan ?? []).slice(0, 30),
627
+ plan: (saved.plan ?? []).slice(0, 30),
574
628
  changes: changes.files, changesTruncated: changes.filesTruncated,
575
- compact: Boolean(state.previewJournal || state.activitiesTruncated || state.historyDetail === "summary"),
576
629
  }); return;
577
630
  }
578
631
  if (route === "/operation" && request.method === "GET") {
@@ -688,7 +741,7 @@ export class WorkspaceSessions implements LocalFileViewerService {
688
741
  const { name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes } = job.spec;
689
742
  return { id: job.id, revision: job.revision, name, prompt, at, startsAt, endsAt, timeZone, cron, maxDelayMinutes, catchUpMinutes,
690
743
  status: job.status, nextRunAt: job.nextRunAt, notice: job.notice,
691
- images: job.attachments?.images.length, files: job.attachments?.files.map(file => file.fileName) };
744
+ images: job.attachments?.images.length, files: job.attachments?.files.map(file => file.fileName), quotes: job.attachments?.quotes?.length };
692
745
  }
693
746
  private scheduleForTask(task: string, id: string, owner: string): ScheduledJob {
694
747
  const job = this.options.store.schedules.get(id);
@@ -709,14 +762,15 @@ export class WorkspaceSessions implements LocalFileViewerService {
709
762
  return previous;
710
763
  }
711
764
  const { images, files } = this.decodeAttachments(input.images ?? [], input.files ?? []);
712
- if (!images.length && !files.length) return create();
765
+ const quotes = input.quotes?.length ? input.quotes : undefined;
766
+ if (!images.length && !files.length) return create(quotes ? { images: [], files: [], quotes } : undefined);
713
767
  if (previous) throw new RequestError(409, "该请求标识已用于另一项计划。");
714
768
  const { directory, attachments } = await this.writePromptAttachments(images, files);
715
769
  let keep = false;
716
770
  try {
717
771
  if (!this.valid(grant)) throw new RequestError(401, "工作台会话已过期,未创建计划。");
718
772
  const alreadyCreated = store.getByRequest(input.request);
719
- const job = create(attachments);
773
+ const job = create(quotes ? { ...attachments, quotes } : attachments);
720
774
  keep = !alreadyCreated;
721
775
  return job;
722
776
  } finally {
@@ -729,14 +783,56 @@ export class WorkspaceSessions implements LocalFileViewerService {
729
783
  if (!prompt) throw new RequestError(404, "这条消息已离开队列。");
730
784
  return prompt;
731
785
  }
786
+ private async sendQueuedPrompt(input: z.infer<typeof queueSend>) {
787
+ const task = this.task(input.task), store = this.options.store;
788
+ const fingerprint = hash(JSON.stringify(["send-queued-prompt", input]));
789
+ const previous = store.workspaceRequest(input.request);
790
+ if (previous) {
791
+ if (previous.fingerprint !== fingerprint) throw new RequestError(409, "该请求标识已用于另一项操作。");
792
+ return this.operation(input.request, previous);
793
+ }
794
+ if (task.status === "closed") throw new RequestError(409, "任务已归档,无法发送消息。");
795
+ const prompt = this.requireQueuedPrompt(input.task, input.prompt);
796
+ if (queuePromptRevision(prompt) !== input.revision) throw new RequestError(409, "排队消息已被修改,请重新发送。");
797
+ store.beginWorkspaceRequest(input.request, input.task, fingerprint);
798
+ this.lastSubmissionAt = Math.max(Date.now(), (this.lastSubmissionAt ?? 0) + 1);
799
+ this.running.add(input.request);
800
+ let submitting = false;
801
+ try {
802
+ await this.options.controller.controlSendWorkspaceQueuedPrompt(prompt, {
803
+ requestId: input.request, onSubmitting: () => { submitting = true; },
804
+ onPosted: () => { store.markWorkspaceRequestPosted(input.request); },
805
+ });
806
+ store.updateWorkspaceRequest(input.request, "accepted");
807
+ } catch (error) {
808
+ const unknown = submitting && !(error instanceof TurnNotSubmittedError);
809
+ store.updateWorkspaceRequest(input.request, unknown ? "unknown" : "failed", false,
810
+ displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "发送排队消息失败。"));
811
+ } finally { this.running.delete(input.request); }
812
+ return this.operation(input.request, store.workspaceRequest(input.request)!);
813
+ }
732
814
  private describeQueuedPrompt(prompt: QueuedPromptRecord) {
733
- const { text, fileCount } = queuedPromptContent(prompt);
734
- return { id: prompt.promptId, text: (prompt.displayPrompt ?? text).slice(0, 180),
735
- ...(fileCount || prompt.localImagePaths?.length ? { hasAttachments: true } : {}) };
815
+ const quotes = this.quotesForRequest(prompt.localSessionId, this.queuedPromptRequest(prompt.promptId));
816
+ const { text, fileCount } = queuedPromptContent(prompt, quotes);
817
+ const preview = (prompt.displayPrompt ?? text).slice(0, 180);
818
+ return { id: prompt.promptId, text: preview, revision: queuePromptRevision(prompt),
819
+ ...(text === preview ? {} : { editText: text }),
820
+ ...(fileCount || prompt.localImagePaths?.length || quotes?.length ? { hasAttachments: true } : {}) };
821
+ }
822
+ private queuedPromptRequest(promptId: string) {
823
+ const prefix = promptId.startsWith("workspace:") ? "workspace:" : "schedule_run_";
824
+ if (promptId.startsWith(prefix)) return key.safeParse(promptId.slice(prefix.length)).data;
736
825
  }
737
826
  private describeQueue(task: string) {
738
- const queuedPrompts = this.options.store.listQueuedPrompts(task).map(prompt => this.describeQueuedPrompt(prompt));
739
- return { queued: queuedPrompts.length, queuedPrompts };
827
+ const store = this.options.store, queued = store.listQueuedPrompts(task);
828
+ const remaining = new Set(queued.map(prompt => prompt.promptId));
829
+ const dispatching = store.listQueuedPromptDispatches(task).filter(prompt => !remaining.has(prompt.promptId));
830
+ const queuedPrompts = [
831
+ ...queued.map(prompt => ({ prompt, dispatching: false })),
832
+ ...dispatching.map(prompt => ({ prompt, dispatching: true })),
833
+ ].sort((a, b) => Date.parse(a.prompt.createdAt) - Date.parse(b.prompt.createdAt))
834
+ .map(({ prompt, dispatching }) => ({ ...this.describeQueuedPrompt(prompt), dispatching: dispatching || undefined }));
835
+ return { queued: queued.length, queuedPrompts };
740
836
  }
741
837
  private describe(task: SessionRecord, fileOrigin?: string) {
742
838
  const project = this.project(task);
@@ -809,23 +905,24 @@ export class WorkspaceSessions implements LocalFileViewerService {
809
905
  return { ...row, status: liveStatus ?? row.status,
810
906
  promptPreview: executing && !liveStatus ? null : workspacePromptPreview(summary?.prompt) };
811
907
  }
812
- private history(task: SessionRecord, origin: string, before?: string, anchor?: string, after?: string) {
908
+ private async history(task: SessionRecord, origin: string, before?: string, anchor?: string, after?: string) {
813
909
  const head = this.head(task), store = this.options.store;
910
+ const describedTask = this.describe(task, origin);
814
911
  const anchored = Boolean(anchor && anchor !== head && !store.workspaceTurnPage(task.localSessionId, head, anchor, 1).beforeMissing);
815
912
  const page = after ? store.workspaceTurnsAfter(task.localSessionId, head, after, MAX_HISTORY)
816
913
  : store.workspaceTurnPage(task.localSessionId, anchored ? anchor : head, before, MAX_HISTORY);
817
914
  if ("cursorMissing" in page ? page.cursorMissing : page.beforeMissing) throw new RequestError(409, "对话分支已有变更,请重新加载历史。");
818
- const turns: NonNullable<ReturnType<WorkspaceSessions["turn"]>>[] = [];
915
+ const turns: NonNullable<Awaited<ReturnType<WorkspaceSessions["turn"]>>>[] = [];
819
916
  let bytes = 0;
820
917
  for (const turnId of page.ids) {
821
- const turn = this.turn(task, turnId, turnId === head);
918
+ const turn = await this.turn(task, turnId, turnId === head, true);
822
919
  if (!turn) continue;
823
920
  const cost = Buffer.byteLength(JSON.stringify(turn));
824
921
  if (turns.length && bytes + cost > HISTORY_BYTES) break;
825
922
  turns.push(turn); bytes += cost;
826
923
  }
827
924
  const summary = head ? store.getTurnPromptSummary(head) : undefined;
828
- return { task: { ...this.describe(task, origin), promptPreview: workspacePromptPreview(summary?.prompt),
925
+ return { task: { ...describedTask, promptPreview: workspacePromptPreview(summary?.prompt),
829
926
  metrics: this.conversationMetrics(task, head) }, head, headStatus: summary?.status,
830
927
  execution: this.activeExecution(task, head, summary?.status),
831
928
  plan: head ? store.workspaceTurnPlan(head) : [],
@@ -836,43 +933,94 @@ export class WorkspaceSessions implements LocalFileViewerService {
836
933
  const store = this.options.store;
837
934
  const snapshot = store.workspaceTurnExecution(turnId);
838
935
  const submission = store.provenance.forTurn(turnId, task.localSessionId);
936
+ const tokens = snapshot ? turnUsageFields(snapshot).tokens : [];
839
937
  return {
840
938
  startedAt: toolTimestamp(snapshot?.startedAt) ?? toolTimestamp(submission?.submittedAt),
841
939
  model: submission?.settings.model ?? snapshot?.model ?? undefined,
842
940
  thinking: submission?.settings.reasoningEffort ?? snapshot?.thinking ?? undefined,
941
+ tokenUsage: tokens.length ? tokens.map(({ text }) => text).join(" · ") : undefined,
843
942
  };
844
943
  }
845
- private turn(task: SessionRecord, turnId: string, current = false) {
944
+ private async recordedTurn(turnId: string, journalId?: string | null, continuedToTurnId?: string | null) {
945
+ const journal = this.options.store.previews;
946
+ journalId ??= turnId;
947
+ if (!journal.has(journalId)) return undefined;
948
+ try {
949
+ const saved = await journal.loadAsync(journalId, false, continuedToTurnId ? turnId : undefined);
950
+ return saved?.turnId === turnId ? saved : undefined;
951
+ }
952
+ catch (error) {
953
+ this.options.logger.warn({ error, turnId: journalId }, "Failed to read the Workspace turn journal.");
954
+ return undefined;
955
+ }
956
+ }
957
+ private async turn(task: SessionRecord, turnId: string, current = false, hydrate = false) {
846
958
  const row = this.options.store.workspaceTurnText(turnId);
847
959
  if (!row) return undefined;
848
- const activities = JSON.parse(row.activities) as WorkspaceActivity[];
849
- const reasoning = JSON.parse(row.reasoning) as WorkspaceReasoning[];
850
- const answer = row.answer || row.live;
851
- return { id: turnId, status: row.status, startedAt: row.startedAt, prompt: row.prompt?.slice(0, 24_000),
960
+ let recorded = await this.recordedTurn(turnId, row.journalId, row.continuedToTurnId);
961
+ if (!recorded && hydrate && row.detail === "summary") {
962
+ try {
963
+ const history = await this.options.loadTurnDetails?.(turnId);
964
+ if (history?.historyDetail === "full") recorded = history;
965
+ } catch (error) {
966
+ this.options.logger.warn({ error, turnId }, "Failed to load the Workspace turn history.");
967
+ }
968
+ }
969
+ const savedPrompt = this.savedPrompt(task.localSessionId, row.promptRequestId ?? undefined);
970
+ const originalPrompt = row.ownerTask === task.localSessionId ? savedPrompt : this.savedPrompt(row.ownerTask, row.promptRequestId ?? undefined);
971
+ const { activities, reasoning } = recorded ? recordedWorkspaceTimeline(recorded) : {
972
+ activities: JSON.parse(row.activities) as WorkspaceActivity[], reasoning: JSON.parse(row.reasoning) as WorkspaceReasoning[],
973
+ };
974
+ const finalAnswer = row.answer || recorded?.finalResponse;
975
+ const answer = finalAnswer || recorded?.assistantText || row.live;
976
+ const changes = recorded && workspaceFileSummary(recorded, recorded.projectCwd ?? task.cwd);
977
+ const changeCount = changes?.length ?? row.changeCount;
978
+ const changeSummary = changes ? JSON.stringify(changes) : row.changeSummary;
979
+ const startedAt = toolTimestamp(row.startedAt);
980
+ const terminal = isTerminalTurnStatus(row.status);
981
+ const recordedDuration = terminal && row.durationMs !== null && Number.isFinite(row.durationMs) && row.durationMs >= 0
982
+ ? row.durationMs : undefined;
983
+ const completedAt = terminal ? toolTimestamp(row.completedAt)
984
+ ?? (startedAt !== undefined && recordedDuration !== undefined ? startedAt + recordedDuration : undefined) : undefined;
985
+ const durationMs = recordedDuration ?? (startedAt !== undefined && completedAt !== undefined && completedAt >= startedAt
986
+ ? completedAt - startedAt : undefined);
987
+ const usage = terminal ? turnUsageFields(row) : undefined;
988
+ return { id: turnId, status: row.status, startedAt, completedAt, durationMs,
989
+ prompt: displaySubmittedPrompt(row.prompt, originalPrompt)?.slice(0, 24_000),
990
+ usage: usage && (usage.tokens.length || usage.activity.length) ? [...usage.tokens, ...usage.activity] : undefined,
852
991
  promptRequestId: row.promptRequestId ?? undefined,
992
+ promptQuotes: originalPrompt?.quotes ?? this.scheduledAttachments(row.ownerTask, row.promptRequestId ?? undefined)?.quotes,
853
993
  promptFiles: this.attachmentLinks(task.localSessionId, row.promptRequestId ?? undefined),
854
- promptImages: this.attachments(task, row.promptImages ? JSON.parse(row.promptImages) : undefined),
855
- answer: answer ? this.render(task, answer) : undefined, final: Boolean(answer && (row.answer || row.status === "completed")),
856
- answerExport: Boolean(row.answer), previewUrl: row.answer ? this.viewer.createTurnPreviewUrl(turnId) : undefined,
994
+ promptImages: this.attachments(task, savedPrompt?.attachments.images.length ? savedPrompt.attachments.images
995
+ : row.promptImages ? JSON.parse(row.promptImages) : undefined),
996
+ answer: answer ? this.render(task, answer) : undefined, final: Boolean(answer && (finalAnswer || row.status === "completed")),
997
+ answerExport: Boolean(finalAnswer), previewUrl: finalAnswer ? this.viewer.createTurnPreviewUrl(turnId) : undefined,
857
998
  timeline: workspaceTimeline(activities, reasoning, answer, current && activeTaskStatuses.has(row.status)).map((item) => {
858
999
  if (item.kind === "execution") return item;
859
- if (item.kind === "reasoning") return { id: item.id, kind: item.kind, rich: this.render(task, item.text!, true) };
860
- const images = item.kind === "user" ? this.attachments(task, item.images) : undefined;
861
- const rich = item.text && item.kind === "assistant" ? this.render(task, item.text, true) : undefined;
1000
+ if (item.kind === "reasoning") return { id: item.id, kind: item.kind, title: item.title,
1001
+ detail: item.detail ? this.render(task, item.detail, true) : undefined };
862
1002
  const requestId = item.kind === "user" && item.id.startsWith("steer:workspace:") ? item.id.slice("steer:workspace:".length) : undefined;
863
- return { id: item.id, kind: item.kind, text: rich ? undefined : item.text, images, rich, requestId,
864
- files: this.attachmentLinks(task.localSessionId, requestId) };
1003
+ const submitted = this.savedPrompt(task.localSessionId, requestId);
1004
+ const original = row.ownerTask === task.localSessionId ? submitted : this.savedPrompt(row.ownerTask, requestId);
1005
+ const storedImages = submitted?.attachments.images;
1006
+ const images = item.kind === "user" ? this.attachments(task, storedImages?.length ? storedImages : item.images) : undefined;
1007
+ const rich = item.text && item.kind === "assistant" ? this.render(task, item.text, true) : undefined;
1008
+ return { id: item.id, kind: item.kind, text: rich ? undefined : displaySubmittedPrompt(item.text, original), images, rich, requestId,
1009
+ startedAt: item.kind === "user" ? toolTimestamp(item.startedAt) : undefined,
1010
+ files: this.attachmentLinks(task.localSessionId, requestId),
1011
+ quotes: original?.quotes };
865
1012
  }),
866
- hasDetails: row.changeCount > 0, fileChangeCount: row.changeCount || undefined,
867
- detailRevision: row.changeSummary && row.changeCount ? hash(row.changeSummary) : undefined,
868
- compact: Boolean(row.compact),
869
- error: row.error || row.notice ? displayRuntimeError(row.error || row.notice!) : undefined, summary: row.detail === "summary",
870
- delivered: row.status === "completed" && row.answer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined,
1013
+ hasDetails: changeCount > 0, fileChangeCount: changeCount || undefined,
1014
+ detailRevision: changeSummary && changeCount ? hash(changeSummary) : undefined,
1015
+ compact: recorded ? Boolean(recorded.activitiesTruncated) : Boolean(row.compact),
1016
+ error: row.error || row.notice ? displayRuntimeError(row.error || row.notice!) : undefined, summary: !recorded && row.detail === "summary",
1017
+ delivered: row.status === "completed" && finalAnswer ? Boolean(this.options.store.getTurnDelivery(turnId)?.finalDelivered) : undefined,
871
1018
  };
872
1019
  }
873
- private async toolPage(task: SessionRecord, state: TurnViewState, toolId: string, offset: number, revision?: string) {
1020
+ private async toolPage(task: SessionRecord, state: TurnViewState, toolId: string, offset: number, revision?: string, patch?: string) {
874
1021
  const journal = this.options.store.previews;
875
- const read = (snapshot: TurnViewState) => journal.toolTextPage(snapshot.previewTurnId ?? snapshot.turnId, toolId, offset, MAX_EXECUTION_CHARS);
1022
+ const read = (snapshot: TurnViewState) => journal.toolTextPage(snapshot.previewTurnId ?? snapshot.turnId, toolId,
1023
+ patch ? 0 : offset, patch ? 0 : MAX_EXECUTION_CHARS);
876
1024
  let page = await read(state);
877
1025
  if (!page && state.historyDetail === "summary" && this.options.loadTurnDetails && !journal.has(state.previewTurnId ?? state.turnId)) {
878
1026
  state = await this.options.loadTurnDetails(state.turnId) ?? state;
@@ -880,8 +1028,14 @@ export class WorkspaceSessions implements LocalFileViewerService {
880
1028
  }
881
1029
  if (page && "busy" in page) throw new RequestError(429, "正在读取其他工具记录,请稍后重试。");
882
1030
  const activity = state.activities?.find((item) => item.kind === "tool" && item.id === toolId);
883
- const files = offset === 0 ? page?.files ?? (activity?.kind === "tool" ? activity.tool.files : undefined) : undefined;
884
- const fileDetails = files?.length ? this.toolFiles(task, state.projectCwd ?? task.cwd, files) : {};
1031
+ const files = page?.files ?? (activity?.kind === "tool" ? activity.tool.files : undefined);
1032
+ if (patch) {
1033
+ const file = files?.slice(0, MAX_TOOL_FILE_ENTRIES).find((file) => file.patch && toolPatchId(file) === patch);
1034
+ if (!file?.patch) throw new RequestError(404, "此工具的文件补丁已不可用。");
1035
+ const notice = file.patchTruncated ? '<div class="workspace-notice">仅显示已保存的补丁开头。</div>' : "";
1036
+ return { html: notice + renderRecordedDiff(file.patch, file.moveTo || file.path, file.path, file.additions, file.deletions) };
1037
+ }
1038
+ const fileDetails = offset === 0 && files?.length ? this.toolFiles(task, state.projectCwd ?? task.cwd, files) : {};
885
1039
  if (page) {
886
1040
  if (revision && revision !== page.revision) throw new RequestError(409, "工具日志已更新,请从开头重新读取。");
887
1041
  const { toolKind, files: _files, ...text } = page;
@@ -909,15 +1063,16 @@ export class WorkspaceSessions implements LocalFileViewerService {
909
1063
  const entries = files.slice(0, MAX_TOOL_FILE_ENTRIES).map(({ path: recordedPath, moveTo, additions, deletions, patch, patchTruncated }) => {
910
1064
  const target = path.resolve(cwd, moveTo || recordedPath);
911
1065
  const patchHtml = patch ? highlightRecordedPatch(patch, target, recordedPath) : undefined;
1066
+ const patchId = patch ? toolPatchId({ path: recordedPath, moveTo }) : undefined;
912
1067
  const name = (primary && this.relativeWorkspaceEntry(primary, target)) || target;
913
1068
  for (const { root, source } of roots) {
914
1069
  const entry = this.projectFileEntry(root, target);
915
1070
  if (entry) {
916
1071
  const original = moveTo ? this.projectFileEntry(root, path.resolve(cwd, recordedPath)) : undefined;
917
- return { name, entry, source, original, additions, deletions, patch, patchHtml, patchTruncated };
1072
+ return { name, entry, source, original, additions, deletions, patch, patchHtml, patchTruncated, patchId };
918
1073
  }
919
1074
  }
920
- return { name, additions, deletions, patch, patchHtml, patchTruncated };
1075
+ return { name, additions, deletions, patch, patchHtml, patchTruncated, patchId };
921
1076
  });
922
1077
  return { files: entries, filesTruncated: files.length > entries.length || undefined };
923
1078
  }
@@ -957,16 +1112,54 @@ export class WorkspaceSessions implements LocalFileViewerService {
957
1112
  if (!Array.isArray(paths) || !paths.length) return;
958
1113
  const files = new Set(paths.filter((file): file is string => typeof file === "string" && !!file));
959
1114
  return [...files].slice(0, 20).map((file) => {
960
- const url = this.imageUrl(file) ?? this.imageUrl(file, task);
961
- return url ? url.pathname + url.search : null;
1115
+ const inbound = this.imageUrl(file);
1116
+ const url = inbound ?? this.imageUrl(file, task);
1117
+ if (!url) return null;
1118
+ if (inbound && /\.png$/iu.test(file)) {
1119
+ const size = this.inboundPngSize(url.searchParams.get("entry")!);
1120
+ if (size) url.hash = `size=${size.join("x")}`;
1121
+ }
1122
+ return url.pathname + url.search + url.hash;
962
1123
  });
963
1124
  }
1125
+ private inboundPngSize(entry: string) {
1126
+ if (this.attachmentSizes.has(entry)) return this.attachmentSizes.get(entry);
1127
+ let size: [number, number] | null = null;
1128
+ try {
1129
+ const file = resolveWorkspacePath(this.imageRoot(), entry);
1130
+ const stat = statSync(file);
1131
+ if (stat.isFile()) {
1132
+ const fd = openSync(file, "r");
1133
+ try {
1134
+ const bytes = Buffer.alloc(Math.min(WORKSPACE_PNG_HEADER_BYTES, stat.size));
1135
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
1136
+ size = workspacePngDisplaySize(new DataView(bytes.buffer, bytes.byteOffset, length)) ?? null;
1137
+ } finally { closeSync(fd); }
1138
+ }
1139
+ } catch { /* Display dimensions are optional when an attachment is unavailable. */ }
1140
+ if (this.attachmentSizes.size >= 256) this.attachmentSizes.delete(this.attachmentSizes.keys().next().value!);
1141
+ this.attachmentSizes.set(entry, size);
1142
+ return size;
1143
+ }
1144
+ private savedPrompt(task: string, request?: string) {
1145
+ if (!request) return;
1146
+ const record = this.options.store.getTaskMetadata(task, workspacePromptKind, request);
1147
+ if (record) return savedWorkspacePrompt.parse(JSON.parse(record));
1148
+ }
964
1149
  private attachmentEntries(task: string, request: string) {
965
1150
  const saved = this.options.store.getTaskMetadata(task, attachmentKind, request);
966
1151
  if (saved) return z.array(attachmentEntry).parse(JSON.parse(saved));
1152
+ const files = this.scheduledAttachments(task, request)?.files;
1153
+ if (files?.length) return this.promptFileEntries(files);
1154
+ }
1155
+ private quotesForRequest(task: string, request?: string) {
1156
+ return this.savedPrompt(task, request)?.quotes ?? this.scheduledAttachments(task, request)?.quotes;
1157
+ }
1158
+ private scheduledAttachments(task: string, request?: string) {
1159
+ if (!request) return;
967
1160
  const run = this.options.store.schedules.getRun(`schedule_run_${request}`);
968
1161
  const job = run && this.options.store.schedules.get(run.jobId);
969
- if (job?.localSessionId === task && job.attachments?.files.length) return this.promptFileEntries(job.attachments.files);
1162
+ if (job?.localSessionId === task) return job.attachments;
970
1163
  }
971
1164
  private attachmentLinks(task: string, request?: string) {
972
1165
  if (!request) return;
@@ -1011,8 +1204,9 @@ export class WorkspaceSessions implements LocalFileViewerService {
1011
1204
  private render(task: SessionRecord, text: string, short = false) {
1012
1205
  const cacheKey = hash(`${task.localSessionId}\0${task.cwd}\0${short}\0${text}`), cached = this.rendered.get(cacheKey);
1013
1206
  if (cached) return cached;
1014
- const truncated = text.length > 48_000;
1015
- const env = {}, tokens = markdown.parse(text.slice(0, 48_000), env);
1207
+ const plain = () => ({ html: `<p>${markdown.utils.escapeHtml(text).replace(/\r?\n/gu, "<br>\n")}</p>` });
1208
+ if (text.length > 48_000) return plain();
1209
+ const env = {}, tokens = markdown.parse(text, env);
1016
1210
  const imagePrefix = this.base.origin + this.base.pathname + "/image?";
1017
1211
  const visit = (items: typeof tokens): void => {
1018
1212
  for (const item of items) {
@@ -1046,9 +1240,7 @@ export class WorkspaceSessions implements LocalFileViewerService {
1046
1240
  }, (file) => this.imageUrl(file, task));
1047
1241
  visit(tokens);
1048
1242
  const html = markdown.renderer.render(tokens, markdown.options, env);
1049
- const result = html.length <= (short ? 12_000 : 220_000)
1050
- ? { html, truncated }
1051
- : { html: `<p>${markdown.utils.escapeHtml(text.slice(0, short ? 4_000 : 24_000))}</p>`, truncated: true };
1243
+ const result = html.length <= (short ? 12_000 : 220_000) ? { html } : plain();
1052
1244
  if (this.rendered.size >= 48) this.rendered.delete(this.rendered.keys().next().value!);
1053
1245
  this.rendered.set(cacheKey, result); return result;
1054
1246
  }
@@ -1068,8 +1260,9 @@ export class WorkspaceSessions implements LocalFileViewerService {
1068
1260
  // Reconnects always reconcile with an authoritative snapshot; no per-token replay is needed.
1069
1261
  this.event(stream, "sync", { revision: WORKSPACE_REVISION, instance: WORKSPACE_INSTANCE });
1070
1262
  }
1071
- private poll(): void {
1072
- if (!this.streams.size && !this.grants.size) return;
1263
+ private async poll(): Promise<void> {
1264
+ if (this.polling || (!this.streams.size && !this.grants.size)) return;
1265
+ this.polling = true;
1073
1266
  try {
1074
1267
  const at = Date.now();
1075
1268
  if (at >= this.nextPrune) { this.nextPrune = at + 5_000; this.pruneGrants(); }
@@ -1085,29 +1278,39 @@ export class WorkspaceSessions implements LocalFileViewerService {
1085
1278
  })));
1086
1279
  if (this.catalogueHash !== next) { this.catalogueHash = next; this.catalogue++; }
1087
1280
  }
1088
- const tails = new Map<string, unknown>();
1281
+ const tails = new Map<string, { value: object; queue: ReturnType<WorkspaceSessions["describeQueue"]>; queueKey: string } | null>();
1089
1282
  for (const stream of this.streams.values()) {
1090
1283
  if (stream.catalogue !== this.catalogue) {
1091
1284
  stream.catalogue = this.catalogue; this.event(stream, "tasks", {});
1092
1285
  }
1093
- if (stream.task) {
1094
- if (!tails.has(stream.task)) {
1095
- const task = this.options.store.getSession(stream.task);
1286
+ const { task: taskId, generation } = stream;
1287
+ if (taskId) {
1288
+ if (!tails.has(taskId)) {
1289
+ const task = this.options.store.getSession(taskId);
1096
1290
  if (task && this.eligible(task)) {
1097
- const head = this.head(task), turn = head ? this.turn(task, head, true) : null;
1098
- tails.set(stream.task, { task: { ...this.describe(task), promptPreview: workspacePromptPreview(turn?.prompt),
1291
+ const head = this.head(task);
1292
+ const queue = this.describeQueue(task.localSessionId);
1293
+ const queueKey = JSON.stringify(queue.queuedPrompts.map(({ id, revision, hasAttachments, dispatching }) => [id, revision, hasAttachments, dispatching]));
1294
+ const turn = head ? await this.turn(task, head, true) : null;
1295
+ if (!this.timer) return;
1296
+ const value = { task: { ...this.describe(task), promptPreview: workspacePromptPreview(turn?.prompt),
1099
1297
  metrics: this.conversationMetrics(task, head),
1100
1298
  directories: listTaskDirectories(this.options.store, task.localSessionId) },
1101
- ...this.describeQueue(task.localSessionId), turn,
1299
+ turn,
1102
1300
  execution: this.activeExecution(task, head, turn?.status),
1103
1301
  plan: head ? this.options.store.workspaceTurnPlan(head) : [],
1104
- parent: head ? this.options.store.getTurnParent(head, task.localSessionId) : undefined });
1105
- } else tails.set(stream.task, null);
1302
+ parent: head ? this.options.store.getTurnParent(head, task.localSessionId) : undefined };
1303
+ tails.set(taskId, { value, queue, queueKey });
1304
+ } else tails.set(taskId, null);
1106
1305
  }
1107
- const next = JSON.stringify(tails.get(stream.task));
1108
- if (next !== stream.tail) {
1306
+ if (stream.task !== taskId || stream.generation !== generation || stream.response.writableEnded || stream.grant.signal.aborted) continue;
1307
+ const tail = tails.get(taskId);
1308
+ const next = JSON.stringify(tail?.value ?? null), queueChanged = tail?.queueKey !== stream.queue;
1309
+ if (next !== stream.tail || queueChanged) {
1109
1310
  stream.tail = next;
1110
- this.event(stream, "tail", { taskId: stream.task, generation: stream.generation, value: tails.get(stream.task) });
1311
+ stream.queue = tail?.queueKey;
1312
+ const value = tail ? (queueChanged ? { ...tail.value, ...tail.queue } : tail.value) : null;
1313
+ this.event(stream, "tail", { taskId, generation, value });
1111
1314
  }
1112
1315
  }
1113
1316
  if (at - stream.heartbeat > 15_000) {
@@ -1116,6 +1319,7 @@ export class WorkspaceSessions implements LocalFileViewerService {
1116
1319
  }
1117
1320
  }
1118
1321
  } catch (error) { this.options.logger.warn({ error }, "Failed to refresh Workspace events."); }
1322
+ finally { this.polling = false; }
1119
1323
  }
1120
1324
  private event(stream: Stream, kind: string, payload: object): void {
1121
1325
  if (stream.response.writableEnded) return;
@@ -1141,17 +1345,28 @@ export class WorkspaceSessions implements LocalFileViewerService {
1141
1345
  else store.beginWorkspaceRequest(input.request, task.localSessionId, fingerprint);
1142
1346
  this.lastSubmissionAt = Math.max(Date.now(), (this.lastSubmissionAt ?? 0) + 1);
1143
1347
  this.running.add(input.request);
1144
- let ambiguous = input.action === "stop", directory: string | undefined;
1348
+ let ambiguous = input.action === "stop", directory: string | undefined, persisted = false;
1145
1349
  try {
1146
- let localImagePaths: string[] | undefined, localFiles: ScheduledPromptAttachments["files"] = [];
1147
- if (images.length || files.length) {
1350
+ const existing = previous ? this.savedPrompt(task.localSessionId, input.request) : undefined;
1351
+ let attachments: ScheduledPromptAttachments = existing?.attachments ?? { images: [], files: [] };
1352
+ if (!existing && (images.length || files.length)) {
1148
1353
  const saved = await this.writePromptAttachments(images, files);
1149
1354
  directory = saved.directory;
1150
- localImagePaths = saved.attachments.images.length ? saved.attachments.images : undefined;
1151
- localFiles = saved.attachments.files;
1152
- if (localFiles.length) {
1153
- store.setTaskMetadata(task.localSessionId, attachmentKind, input.request, JSON.stringify(this.promptFileEntries(localFiles)));
1355
+ attachments = saved.attachments;
1356
+ }
1357
+ const localImagePaths = attachments.images.length ? attachments.images : undefined;
1358
+ const localFiles = attachments.files;
1359
+ if (localFiles.length && !existing) {
1360
+ store.setTaskMetadata(task.localSessionId, attachmentKind, input.request, JSON.stringify(this.promptFileEntries(localFiles)));
1361
+ }
1362
+ const quotes = input.action !== "stop" && input.quotes?.length ? input.quotes : undefined;
1363
+ if (input.action !== "stop" && (input.action !== "queue" || quotes?.length)) {
1364
+ if (!existing) {
1365
+ store.setTaskMetadata(task.localSessionId, workspacePromptKind, input.request, JSON.stringify({
1366
+ text: input.text, action: input.action, turn: input.action === "steer" ? input.turn : undefined, attachments, quotes,
1367
+ }));
1154
1368
  }
1369
+ persisted = true;
1155
1370
  }
1156
1371
  if (input.action === "stop") {
1157
1372
  const result = await this.options.controller.controlStopTask(task.localSessionId, input.turn);
@@ -1159,22 +1374,24 @@ export class WorkspaceSessions implements LocalFileViewerService {
1159
1374
  } else if (input.action === "queue") {
1160
1375
  ambiguous = true;
1161
1376
  await this.options.controller.controlQueueTaskPrompt(task.localSessionId, input.text, localImagePaths, input.request,
1162
- ...(localFiles.length ? [localFiles] as const : []));
1377
+ localFiles.length ? localFiles : undefined, quotes);
1163
1378
  store.updateWorkspaceRequest(input.request, "accepted");
1164
1379
  } else {
1165
1380
  await this.options.controller.controlSendTaskPrompt(task.localSessionId, input.text, {
1166
1381
  requestId: input.request, localImagePaths, ...(localFiles.length ? { files: localFiles } : {}),
1382
+ ...(quotes ? { quotes } : {}),
1167
1383
  ...(input.action === "steer" ? { expectedTurnId: input.turn } : {}),
1168
- onPosting: () => { ambiguous = true; },
1169
- onPosted: () => { store.updateWorkspaceRequest(input.request, "pending", true); },
1384
+ onSubmitting: () => { ambiguous = true; },
1385
+ onPosted: () => { store.markWorkspaceRequestPosted(input.request); },
1170
1386
  });
1171
1387
  store.updateWorkspaceRequest(input.request, "accepted");
1172
1388
  }
1173
1389
  } catch (error) {
1174
1390
  const message = displayRuntimeError(error instanceof Error ? error.message.slice(0, 1200) : "操作未完成。");
1175
1391
  const stale = input.action === "steer" && error instanceof TurnNotSubmittedError;
1176
- store.updateWorkspaceRequest(input.request, stale ? "stale" : ambiguous ? "unknown" : "failed", false, message);
1177
- if (directory && (!ambiguous || stale)) {
1392
+ const unknown = ambiguous && !(error instanceof TurnNotSubmittedError);
1393
+ store.updateWorkspaceRequest(input.request, stale ? "stale" : unknown ? "unknown" : "failed", false, message);
1394
+ if (directory && !persisted && (!unknown || stale)) {
1178
1395
  if (files.length) store.removeTaskMetadata(task.localSessionId, attachmentKind, input.request);
1179
1396
  await this.removePromptAttachments(directory);
1180
1397
  }