@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,9 +1,10 @@
1
1
  import type { ToolStatus } from "../runtime/types.js";
2
+ import type { TurnViewState } from "../presentation/turnViewTypes.js";
2
3
  import { toolTimestamp } from "../utils/toolTimestamp.js";
3
- import type { PreviewToolHeading } from "./ToolCommandDisplay.js";
4
+ import { previewToolHeading, type PreviewToolHeading } from "./ToolCommandDisplay.js";
4
5
 
5
6
  export type WorkspaceActivity = { id: string } & (
6
- | { kind: "assistant" | "user" | "system" | "reasoning"; text: string | null; images: unknown }
7
+ | { kind: "assistant" | "user" | "system" | "reasoning"; text: string | null; images: unknown; startedAt?: number | null }
7
8
  | { kind: "tool"; heading: PreviewToolHeading; toolKind: string | null; status: ToolStatus; startedAt?: number | null; completedAt?: number | null }
8
9
  );
9
10
  export interface WorkspaceReasoning {
@@ -11,6 +12,24 @@ export interface WorkspaceReasoning {
11
12
  after: string | null;
12
13
  parts: Array<{ index: number; text: string }>;
13
14
  }
15
+
16
+ export function recordedWorkspaceTimeline(state: TurnViewState) {
17
+ const activities = state.activities.map((activity): WorkspaceActivity => {
18
+ const { id, kind } = activity;
19
+ if (kind !== "tool") return { id, kind, text: activity.text,
20
+ images: kind === "user" ? activity.localImagePaths : undefined,
21
+ startedAt: kind === "user" ? activity.startedAt : undefined };
22
+ const { tool } = activity;
23
+ const heading = previewToolHeading(tool, "命令");
24
+ return { id, kind, heading: { ...heading, title: heading.title.slice(0, 240) }, toolKind: tool.kind ?? null,
25
+ status: tool.status, startedAt: tool.startedAt, completedAt: tool.completedAt };
26
+ });
27
+ const reasoning = (state.reasoningItems ?? []).map((item): WorkspaceReasoning => ({
28
+ id: item.itemId, after: item.afterActivityId ?? null,
29
+ parts: item.summary.flatMap((text, index) => text?.trim() ? [{ index, text: text.slice(0, 512) }] : []),
30
+ }));
31
+ return { activities, reasoning };
32
+ }
14
33
  type WorkspaceTool = { id: string; title: string; kind: string; command?: true; status: ToolStatus; startedAt?: number; completedAt?: number };
15
34
  interface ExecutionGroup {
16
35
  kind: "execution";
@@ -18,16 +37,20 @@ interface ExecutionGroup {
18
37
  title: string;
19
38
  tools: WorkspaceTool[];
20
39
  }
40
+ type WorkspaceMessage = { id: string; kind: "assistant" | "user" | "system"; text: string | null; images: unknown; startedAt?: number | null };
41
+ type ThinkingSummary = { title?: string; detail?: string };
21
42
 
22
43
  const reasoningPart = /^reasoning:(.+):(\d+)$/u;
23
44
  const isNativeReasoning = (activity: WorkspaceActivity) => activity.kind === "reasoning" && !activity.id.startsWith("commentary:");
24
45
 
25
- function reasoningTitle(summary: string | null): string | undefined {
26
- const line = summary?.trim().split(/\r?\n/u, 1)[0]?.replace(/^#{1,6}\s+/u, "").trim() ?? "";
46
+ function reasoningSummary(excerpt: string): ThinkingSummary {
47
+ const [first, ...body] = excerpt.split(/\r?\n/u);
48
+ const line = first!.replace(/^#{1,6}\s+/u, "").trim();
27
49
  const title = /^(?:\*\*(.+)\*\*|__(.+)__)$/u.exec(line);
28
- if (!title && /^(?:\*\*|__|#{1,6}$)/u.test(line)) return undefined;
50
+ const detail = body.join("\n").trim() || undefined;
51
+ if (!title && /^(?:\*\*|__|#{1,6}$)/u.test(line)) return { detail };
29
52
  const text = title?.[1] ?? title?.[2] ?? line;
30
- return text.length > 140 ? `${text.slice(0, 139)}…` : text || undefined;
53
+ return text.length > 140 ? { title: `${text.slice(0, 139)}…`, detail: excerpt } : { title: text || undefined, detail };
31
54
  }
32
55
 
33
56
  function reasoningUpdates(activities: WorkspaceActivity[], saved: WorkspaceReasoning[]) {
@@ -42,11 +65,12 @@ function reasoningUpdates(activities: WorkspaceActivity[], saved: WorkspaceReaso
42
65
  const section = match ? Number(match[2]) : 0;
43
66
  parts.set(section, { position: index, text: activity.text });
44
67
  }
45
- const result = new Map<number, { title?: string; excerpt: string }>();
68
+ const result = new Map<number, ThinkingSummary>();
46
69
  const add = (index: number, text: string | null) => {
47
70
  const excerpt = text?.trim().slice(0, 512);
48
71
  if (!excerpt || /^[*_#\s]+$/u.test(excerpt)) return;
49
- result.set(index, { title: reasoningTitle(excerpt) ?? result.get(index)?.title, excerpt });
72
+ const { title, detail } = reasoningSummary(excerpt);
73
+ result.set(index, { title: title ?? result.get(index)?.title, detail });
50
74
  };
51
75
  for (const item of saved) {
52
76
  const parts = markers.get(item.id);
@@ -73,12 +97,12 @@ export function workspaceTimeline(
73
97
  activities: WorkspaceActivity[], saved: WorkspaceReasoning[], answer?: string | null, showThinking = false,
74
98
  ) {
75
99
  const reasoningAt = reasoningUpdates(activities, saved);
76
- const rows: Array<ExecutionGroup | Exclude<WorkspaceActivity, { kind: "tool" }>> = [];
77
- let group: ExecutionGroup | undefined, title: string | undefined, thinking: string | undefined;
100
+ const rows: Array<ExecutionGroup | WorkspaceMessage | { kind: "reasoning"; id: string; title: string; detail?: string }> = [];
101
+ let group: ExecutionGroup | undefined, title: string | undefined, thinking: ThinkingSummary | undefined;
78
102
  for (let index = 0; index <= activities.length; index++) {
79
103
  const next = reasoningAt.get(index);
80
104
  if (next) {
81
- thinking = next.excerpt;
105
+ thinking = next;
82
106
  if (next.title) { title = next.title; if (group) group.title = title; }
83
107
  }
84
108
  const activity = activities[index];
@@ -96,14 +120,16 @@ export function workspaceTimeline(
96
120
  } else {
97
121
  const kind = activity.kind === "assistant" && /^(?:model-queue|context-compaction):/u.test(activity.id) ? "system"
98
122
  : activity.kind === "reasoning" ? "assistant" : activity.kind;
99
- if (kind === "assistant" && activity.text === answer && index === activities.length - 1) { group = title = thinking = undefined; continue; }
123
+ if (kind === "assistant" && activity.text === answer && index === activities.length - 1) {
124
+ group = title = undefined; thinking = undefined; continue;
125
+ }
100
126
  if (!activity.text?.trim() && !(kind === "user" && Array.isArray(activity.images) && activity.images.length)) continue;
101
127
  rows.push({ ...activity, kind });
102
- group = title = thinking = undefined;
128
+ group = title = undefined; thinking = undefined;
103
129
  }
104
130
  }
105
- if (showThinking && !answer && thinking && !group) {
106
- rows.push({ kind: "reasoning", id: "workspace:thinking", text: thinking, images: null });
131
+ if (showThinking && !answer && thinking && !group && (title || thinking.detail)) {
132
+ rows.push({ kind: "reasoning", id: "workspace:thinking", title: title || "思考摘要", detail: thinking.detail });
107
133
  }
108
134
  return rows;
109
135
  }
@@ -33,6 +33,7 @@ export interface TurnPresenter {
33
33
  prompt?: string,
34
34
  localImagePaths?: string[],
35
35
  promptRequestId?: string,
36
+ localFirst?: boolean,
36
37
  ): Promise<string | undefined>;
37
38
  failPendingTurn(
38
39
  sessionId: string,
@@ -123,12 +124,14 @@ export class OutboundRouter {
123
124
  prompt?: string,
124
125
  localImagePaths?: string[],
125
126
  promptRequestId?: string,
127
+ localFirst?: boolean,
126
128
  ): Promise<string | undefined> {
127
129
  const route = this.route(contextKey);
128
130
  this.sessionRoutes.set(sessionId, route);
129
131
  this.sessionContextKeys.set(sessionId, contextKey);
130
132
  if (replyTarget) this.sessionReplyTargets.set(sessionId, replyTarget);
131
133
  else this.sessionReplyTargets.delete(sessionId);
134
+ if (localFirst) return route.presenter.startPendingTurn(sessionId, contextKey, taskTitle, replyTarget, prompt, localImagePaths, promptRequestId, true);
132
135
  if (promptRequestId) return route.presenter.startPendingTurn(sessionId, contextKey, taskTitle, replyTarget, prompt, localImagePaths, promptRequestId);
133
136
  return route.presenter.startPendingTurn(sessionId, contextKey, taskTitle, replyTarget, prompt, ...(localImagePaths ? [localImagePaths] : []));
134
137
  }
@@ -486,17 +486,19 @@ function approvalHistoryText(request: ApprovalRequest, decision?: ApprovalDecisi
486
486
  ].filter(Boolean).join("\n\n");
487
487
  }
488
488
 
489
- export function appendSteerMessage(state: TurnViewState, id: string, text: string, localImagePaths?: string[]): TurnViewState {
489
+ export function appendSteerMessage(state: TurnViewState, id: string, text: string, localImagePaths?: string[], startedAt?: number): TurnViewState {
490
490
  const normalized = text.trim();
491
491
  if (!normalized && !localImagePaths?.length) return state;
492
492
  const activities = state.activities ?? [];
493
493
  const index = activities.findIndex((activity) => activity.id === id);
494
494
  const previous = activities[index];
495
495
  const images = localImagePaths ?? (previous?.kind === "user" ? previous.localImagePaths : undefined);
496
+ const start = (previous?.kind === "user" ? previous.startedAt : undefined) ?? startedAt;
496
497
  const activityUpdate = upsertActivity(activities, index, {
497
498
  kind: "user",
498
499
  id,
499
500
  text: bound(normalized),
501
+ ...(start === undefined ? {} : { startedAt: start }),
500
502
  ...(images?.length ? { localImagePaths: [...new Set(images)] } : {}),
501
503
  });
502
504
  return {
@@ -22,7 +22,7 @@ export type SystemActivityCategory = "context_compaction" | "model_queue";
22
22
  export type TurnActivity =
23
23
  | { kind: "assistant"; id: string; text: string }
24
24
  | { kind: "system"; category: SystemActivityCategory; id: string; text: string }
25
- | { kind: "user"; id: string; text: string; localImagePaths?: string[] }
25
+ | { kind: "user"; id: string; text: string; localImagePaths?: string[]; startedAt?: number }
26
26
  | { kind: "reasoning"; id: string; text: string }
27
27
  | { kind: "tool"; id: string; tool: ToolState };
28
28
 
@@ -54,6 +54,7 @@ import { RECENT_CONTEXT_LIMIT, RECENT_CONTEXT_IMAGE_LIMIT, RECENT_CONTEXT_TEXT_L
54
54
  import { allowsFeishuUser } from "../feishu/ownerAccess.js";
55
55
  import type { ScheduleCommand, ScheduledJob, ScheduleInput } from "../scheduling/types.js";
56
56
  import { scheduleCommandSchema, scheduleDisplayPrompt } from "../scheduling/types.js";
57
+ import { appendPromptQuotes, promptQuoteInstruction, type PromptQuote } from "../utils/promptQuotes.js";
57
58
  import { appendDownloadedFiles, defaultResourcePromptFromCounts, queuedPromptContent } from "../utils/promptAttachments.js";
58
59
  import type { SettingsCatalog, SettingsSnapshot, SettingsStore } from "../config/SettingsStore.js";
59
60
  import { renderSettingsCard } from "../feishu/SettingsCard.js";
@@ -135,12 +136,26 @@ interface StartTurnOptions {
135
136
  messageId?: string;
136
137
  displayPrompt?: string;
137
138
  workspaceRequestId?: string;
139
+ onWorkspaceClaim?: () => void;
140
+ onWorkspaceSubmitting?: () => void;
138
141
  preserveAttemptOnFailure?: boolean;
139
142
  approvedPlanTurnId?: string;
140
143
  responseContinuationTurnId?: string;
141
144
  recoveryContinuationTurnId?: string;
142
145
  }
143
146
 
147
+ interface WorkspacePromptSubmission {
148
+ requestId: string;
149
+ expectedTurnId?: string;
150
+ localImagePaths?: string[];
151
+ files?: Array<{ fileName: string; filePath: string }>;
152
+ quotes?: PromptQuote[];
153
+ queuedPrompt?: QueuedPromptRecord;
154
+ onClaim?: () => void;
155
+ onSubmitting(): void;
156
+ onPosted(): void;
157
+ }
158
+
144
159
  interface PendingMessageReference {
145
160
  contextKey: string;
146
161
  userId?: string;
@@ -1639,33 +1654,36 @@ export class ProxySessionController {
1639
1654
  return { session, snapshot, remote };
1640
1655
  }
1641
1656
 
1642
- async controlSetTaskTitle(localSessionId: string, title: string): Promise<string> {
1657
+ async controlSetTaskTitle(localSessionId: string, title: string, source: "cli" | "workspace" = "cli"): Promise<string> {
1643
1658
  const normalizedTitle = normalizeTaskTitle(title);
1644
1659
  if (!normalizedTitle) throw new Error("The task title cannot be empty.");
1645
1660
  const record = this.store.getSession(localSessionId);
1646
- if (!record || record.status === "closed") throw new Error(`Task not found: ${localSessionId}`);
1647
- const loaded = await this.loadSession(record);
1648
- if (loaded.runtime.setTitle) await loaded.runtime.setTitle(record.localSessionId, normalizedTitle);
1649
- else loaded.session.title = normalizedTitle;
1661
+ if (!record || (record.status === "closed" && source === "cli")) throw new Error(`Task not found: ${localSessionId}`);
1662
+ if (record.status !== "closed") {
1663
+ const loaded = await this.loadSession(record);
1664
+ if (loaded.runtime.setTitle) await loaded.runtime.setTitle(record.localSessionId, normalizedTitle);
1665
+ else loaded.session.title = normalizedTitle;
1666
+ }
1650
1667
  this.store.updateRuntimeSession(record.localSessionId, { title: normalizedTitle });
1651
1668
  this.outbound.updateSessionTitle(record.localSessionId, normalizedTitle);
1652
1669
  this.store.audit(record.contextKey, "session_title_changed", {
1653
1670
  localSessionId: record.localSessionId,
1654
1671
  title: normalizedTitle,
1655
- source: "cli",
1672
+ source,
1656
1673
  });
1657
1674
  return `Task title changed to: ${normalizedTitle}`;
1658
1675
  }
1659
1676
 
1660
- async controlSendTaskPrompt(localSessionId: string, text: string, workspace?: {
1661
- requestId: string; expectedTurnId?: string; localImagePaths?: string[]; files?: Array<{ fileName: string; filePath: string }>;
1662
- onPosting(): void; onPosted(): void;
1663
- }): Promise<string> {
1677
+ async controlSendTaskPrompt(localSessionId: string, text: string, workspace?: WorkspacePromptSubmission): Promise<string> {
1664
1678
  const images = workspace?.localImagePaths;
1665
1679
  const files = workspace?.files;
1666
- const promptText = text.trim() || (files?.length ? defaultResourcePromptFromCounts(images?.length ?? 0, files.length) : "");
1680
+ const quotes = workspace?.quotes;
1681
+ const queued = workspace?.queuedPrompt;
1682
+ const promptText = queued ? queued.displayPrompt ?? queued.text
1683
+ : text.trim() || promptQuoteInstruction(quotes) || (files?.length ? defaultResourcePromptFromCounts(images?.length ?? 0, files.length) : "");
1684
+ const modelPrompt = queued?.text ?? appendPromptQuotes(promptText, quotes);
1667
1685
  const echoedPrompt = files?.length ? `${promptText}\n\n附件:${files.map((file) => file.fileName).join("、")}` : promptText;
1668
- if (!promptText && !images?.length) throw new Error("The Prompt cannot be empty.");
1686
+ if (!modelPrompt.trim() && !images?.length) throw new Error("The Prompt cannot be empty.");
1669
1687
  const record = this.store.getSession(localSessionId);
1670
1688
  if (!record || record.status === "closed") throw new Error(`Task not found: ${localSessionId}`);
1671
1689
  const runtime = this.runtimes.forAgent(record.agentName);
@@ -1673,7 +1691,7 @@ export class ProxySessionController {
1673
1691
  const expectedTurnId = workspace?.expectedTurnId;
1674
1692
  assertWorkspaceSteerTurn(expectedTurnId, activeTurnId);
1675
1693
  const routedContextKey = this.outbound.getSessionContextKey(localSessionId);
1676
- const responseContextKey = (activeTurnId ? this.store.getTurnContextKey(activeTurnId) ?? routedContextKey : undefined)
1694
+ const responseContextKey = queued?.contextKey ?? (activeTurnId ? this.store.getTurnContextKey(activeTurnId) ?? routedContextKey : undefined)
1677
1695
  ?? (record.lastTurnId ? this.store.getTurnContextKey(record.lastTurnId) : undefined)
1678
1696
  ?? routedContextKey
1679
1697
  ?? record.contextKey;
@@ -1684,17 +1702,25 @@ export class ProxySessionController {
1684
1702
  ? turnViewSnapshot(this.store.getTurnSnapshot(activeTurnId))
1685
1703
  : undefined;
1686
1704
  const routedReplyTarget = this.outbound.getSessionReplyTarget(localSessionId);
1687
- const existingReplyTarget = activeSnapshot?.replyTarget
1705
+ const existingReplyTarget = queued ? (queued.replyMessageId ? { messageId: queued.replyMessageId, replyInThread: true as const } : undefined)
1706
+ : activeSnapshot?.replyTarget
1688
1707
  ?? (activeTurnId ? routedReplyTarget : undefined)
1689
1708
  ?? lastSnapshot?.replyTarget
1690
1709
  ?? routedReplyTarget;
1691
- if (isThreadContextKey(responseContextKey) && !existingReplyTarget) {
1710
+ const threaded = isThreadContextKey(responseContextKey);
1711
+ if (threaded && !existingReplyTarget && !workspace) {
1692
1712
  throw new Error("Could not resolve the target task's thread reply location. The Prompt was not sent.");
1693
1713
  }
1694
1714
  const scopedRecord = this.store.getSessionForContext(localSessionId, responseContextKey)
1695
1715
  ?? { ...record, contextKey: responseContextKey };
1696
1716
  const previous = this.messageQueues.get(responseContextKey) ?? Promise.resolve();
1697
- const next = previous.catch(() => undefined).then(async () => {
1717
+ const send = async () => {
1718
+ if (queued) {
1719
+ const current = this.store.getQueuedPrompt(localSessionId, queued.promptId);
1720
+ if (!current || current.text !== queued.text || current.displayPrompt !== queued.displayPrompt) {
1721
+ throw new TurnNotSubmittedError("排队消息已被修改或离开队列。");
1722
+ }
1723
+ }
1698
1724
  this.outbound.registerSession(
1699
1725
  scopedRecord.localSessionId,
1700
1726
  responseContextKey,
@@ -1707,41 +1733,88 @@ export class ProxySessionController {
1707
1733
  );
1708
1734
  if (workspace && this.store.getSession(localSessionId)?.status === "closed") throw new Error("任务已归档。");
1709
1735
  assertWorkspaceSteerTurn(expectedTurnId, runtime.getSession(localSessionId)?.activeTurnId);
1710
- const executionGeneration = expectedTurnId ? this.store.executionGeneration(localSessionId) : undefined;
1711
- const promptMessageId = await this.outbound.withReplyTarget(
1736
+ const post = () => this.outbound.withReplyTarget(
1712
1737
  responseContextKey,
1713
1738
  existingReplyTarget,
1714
- () => {
1715
- if (images?.length) return this.outbound.sendPromptImages(responseContextKey, echoedPrompt, images, () => workspace?.onPosting());
1716
- workspace?.onPosting();
1717
- return this.outbound.sendText(responseContextKey, echoedPrompt);
1718
- },
1739
+ () => images?.length
1740
+ ? this.outbound.sendPromptImages(responseContextKey, echoedPrompt, images)
1741
+ : this.outbound.sendText(responseContextKey, echoedPrompt),
1719
1742
  );
1720
- workspace?.onPosted();
1721
- if (executionGeneration !== undefined) {
1722
- this.assertExecutionGeneration(localSessionId, executionGeneration);
1723
- assertWorkspaceSteerTurn(expectedTurnId, runtime.getSession(localSessionId)?.activeTurnId);
1724
- }
1725
- const turnReplyTarget = isThreadContextKey(responseContextKey)
1743
+ const promptMessageId = workspace ? undefined : await post();
1744
+ const turnReplyTarget = threaded
1726
1745
  ? promptMessageId
1727
1746
  ? { messageId: promptMessageId, replyInThread: true as const }
1728
1747
  : existingReplyTarget
1729
1748
  : undefined;
1730
- await this.promptSession(scopedRecord, responseContextKey, files?.length ? appendDownloadedFiles(promptText, files) : promptText,
1731
- undefined, turnReplyTarget, images, files?.length ? promptText : undefined, workspace);
1749
+ await this.promptSession(scopedRecord, responseContextKey, !queued && files?.length ? appendDownloadedFiles(modelPrompt, files) : modelPrompt,
1750
+ queued?.messageId, turnReplyTarget, images, queued?.displayPrompt ?? (files?.length || quotes?.length ? promptText : undefined), workspace);
1751
+ if (workspace && !queued?.messageId) this.deliverWorkspacePrompt(post, localSessionId, workspace, !threaded || Boolean(existingReplyTarget));
1732
1752
  this.store.audit(responseContextKey, "task_prompt_sent", {
1733
1753
  localSessionId,
1734
1754
  source: workspace ? "workspace" : "cli",
1735
1755
  requestId: workspace?.requestId,
1736
1756
  });
1737
- });
1757
+ };
1758
+ const next = previous.catch(() => undefined).then(() => queued ? this.serializeQueuedPromptStart(localSessionId, send) : send());
1738
1759
  this.messageQueues.set(responseContextKey, next);
1739
1760
  try {
1740
1761
  await next;
1741
1762
  } finally {
1742
1763
  if (this.messageQueues.get(responseContextKey) === next) this.messageQueues.delete(responseContextKey);
1743
1764
  }
1744
- return `The Prompt was posted to the original chat and submitted to the task: ${record.title ?? record.remoteSessionId ?? record.localSessionId}`;
1765
+ const target = record.title ?? record.remoteSessionId ?? record.localSessionId;
1766
+ return workspace ? `The Prompt was submitted to the task: ${target}`
1767
+ : `The Prompt was posted to the original chat and submitted to the task: ${target}`;
1768
+ }
1769
+
1770
+ async controlSendWorkspaceQueuedPrompt(prompt: QueuedPromptRecord, submission: Pick<WorkspacePromptSubmission, "requestId" | "onSubmitting" | "onPosted">): Promise<void> {
1771
+ const scheduled = this.store.schedules.getRun(prompt.promptId);
1772
+ const requestId = prompt.promptId.startsWith("workspace:") ? prompt.promptId.slice("workspace:".length)
1773
+ : scheduled ? scheduled.id.slice("schedule_run_".length) : submission.requestId;
1774
+ let claimed = false, submitting = false;
1775
+ let finishDispatch: (() => void) | undefined;
1776
+ try {
1777
+ await this.controlSendTaskPrompt(prompt.localSessionId, prompt.displayPrompt ?? prompt.text, {
1778
+ ...submission, requestId, queuedPrompt: prompt, localImagePaths: prompt.localImagePaths,
1779
+ onClaim: () => {
1780
+ if (claimed) return;
1781
+ if (scheduled) this.assertScheduleTarget(this.store.schedules.require(scheduled.jobId));
1782
+ if (!this.store.claimQueuedPromptForImmediateSend(prompt)) throw new TurnNotSubmittedError("排队消息已被修改或离开队列。");
1783
+ claimed = true;
1784
+ finishDispatch = this.store.trackQueuedPromptDispatch(prompt);
1785
+ },
1786
+ onSubmitting: () => {
1787
+ submitting = true;
1788
+ submission.onSubmitting();
1789
+ },
1790
+ });
1791
+ if (scheduled) this.store.schedules.finish(scheduled.id, "cancelled", "本次排队消息已改为手动发送。");
1792
+ } catch (error) {
1793
+ const known = error instanceof TurnNotSubmittedError ? error
1794
+ : error instanceof Error && error.cause instanceof TurnNotSubmittedError ? new TurnNotSubmittedError(error.message) : undefined;
1795
+ if (claimed && (!submitting || known)) this.store.restoreQueuedPromptAfterImmediateSend(prompt);
1796
+ else if (claimed && scheduled) this.store.schedules.finish(scheduled.id, "unknown", "手动发送的提交结果待核实。");
1797
+ throw known ?? error;
1798
+ } finally {
1799
+ finishDispatch?.();
1800
+ if (claimed) void this.refreshPromptQueueCards(prompt.localSessionId).catch(error => {
1801
+ this.logger.warn({ error, promptId: prompt.promptId }, "Failed to refresh the prompt queue after an immediate send.");
1802
+ });
1803
+ }
1804
+ }
1805
+
1806
+ private deliverWorkspacePrompt(
1807
+ post: () => Promise<string | undefined>, sessionId: string, request: { requestId: string; onPosted(): void }, routed: boolean,
1808
+ ): void {
1809
+ const details = { sessionId, requestId: request.requestId };
1810
+ if (!routed) {
1811
+ this.logger.warn(details, "Workspace Prompt submitted locally without a Feishu thread reply target.");
1812
+ return;
1813
+ }
1814
+ this.inboundActionsInFlight += 1;
1815
+ void Promise.resolve().then(post).then(() => request.onPosted()).catch((error: unknown) => {
1816
+ this.logger.warn({ ...details, error }, "Failed to deliver a Workspace Prompt to Feishu.");
1817
+ }).finally(() => { this.inboundActionsInFlight -= 1; });
1745
1818
  }
1746
1819
 
1747
1820
  async controlCreateTaskGroup(
@@ -2182,15 +2255,16 @@ export class ProxySessionController {
2182
2255
  }
2183
2256
 
2184
2257
  async controlQueueTaskPrompt(localSessionId: string, text: string, localImagePaths?: string[], workspaceRequestId?: string,
2185
- files?: Array<{ fileName: string; filePath: string }>): Promise<{ promptId: string; queued: number }> {
2186
- const promptText = text.trim() || (files?.length ? defaultResourcePromptFromCounts(localImagePaths?.length ?? 0, files.length) : "");
2258
+ files?: Array<{ fileName: string; filePath: string }>, quotes?: PromptQuote[]): Promise<{ promptId: string; queued: number }> {
2259
+ const promptText = text.trim() || promptQuoteInstruction(quotes) || (files?.length ? defaultResourcePromptFromCounts(localImagePaths?.length ?? 0, files.length) : "");
2260
+ const modelPrompt = appendPromptQuotes(promptText, quotes);
2187
2261
  if (!promptText && !localImagePaths?.length) throw new Error("The queued Prompt cannot be empty.");
2188
2262
  const record = this.requireControlSession(localSessionId);
2189
2263
  const contextKey = this.controlSessionContextKey(record);
2190
2264
  const replyTarget = this.controlSessionReplyTarget(record);
2191
- const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, files?.length ? appendDownloadedFiles(promptText, files) : promptText, {
2265
+ const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, files?.length ? appendDownloadedFiles(modelPrompt, files) : modelPrompt, {
2192
2266
  replyTarget, localImagePaths, promptId: workspaceRequestId ? `workspace:${workspaceRequestId}` : undefined,
2193
- displayPrompt: files?.length ? promptText : undefined,
2267
+ displayPrompt: files?.length || quotes?.length ? promptText : undefined,
2194
2268
  });
2195
2269
  this.store.audit(contextKey, "queued_prompt_added", {
2196
2270
  promptId: queued.promptId,
@@ -3544,14 +3618,16 @@ export class ProxySessionController {
3544
3618
  replyTarget?: MessageReplyTarget,
3545
3619
  localImagePaths?: string[],
3546
3620
  displayPrompt?: string,
3547
- workspace?: { requestId: string; expectedTurnId?: string },
3621
+ workspace?: Pick<WorkspacePromptSubmission, "requestId" | "expectedTurnId" | "onClaim" | "onSubmitting" | "queuedPrompt">,
3548
3622
  ): Promise<void> {
3549
3623
  this.recoverySupersededSessions.add(record.localSessionId);
3550
3624
  const executionGeneration = this.store.executionGeneration(record.localSessionId);
3551
3625
  const workspaceRequestId = workspace?.requestId;
3552
3626
  const workspaceMessageId = workspaceRequestId ? `workspace:${workspaceRequestId}` : undefined;
3553
- const startOptions = { messageId, displayPrompt, executionGeneration, workspaceRequestId };
3627
+ const startOptions = { messageId, displayPrompt, executionGeneration, workspaceRequestId,
3628
+ onWorkspaceClaim: workspace?.onClaim, onWorkspaceSubmitting: workspace?.onSubmitting };
3554
3629
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
3630
+ if (workspace?.queuedPrompt) throw new TurnNotSubmittedError("当前任务正在重试或切换,请稍后再发送。");
3555
3631
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
3556
3632
  localImagePaths,
3557
3633
  messageId,
@@ -3586,6 +3662,7 @@ export class ProxySessionController {
3586
3662
  displayPrompt ?? text,
3587
3663
  localImagePaths,
3588
3664
  workspaceRequestId,
3665
+ Boolean(workspace),
3589
3666
  );
3590
3667
  }
3591
3668
  let loaded: LoadedSession;
@@ -3620,6 +3697,7 @@ export class ProxySessionController {
3620
3697
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
3621
3698
  const notificationTurn = Boolean(turnViewSnapshot(this.store.getTurnSnapshot(activeTurnId))?.taskNotificationCard);
3622
3699
  if ((activeContextKey && activeContextKey !== contextKey) || notificationTurn) {
3700
+ if (workspace?.queuedPrompt) throw new TurnNotSubmittedError("当前轮次无法接收这条消息,可在会话空闲后再发送。");
3623
3701
  this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
3624
3702
  localImagePaths,
3625
3703
  messageId,
@@ -3631,6 +3709,8 @@ export class ProxySessionController {
3631
3709
  return;
3632
3710
  }
3633
3711
  try {
3712
+ workspace?.onClaim?.();
3713
+ workspace?.onSubmitting();
3634
3714
  await loaded.runtime.steerTurn(record.localSessionId, activeTurnId, runtimePrompt(text, localImagePaths));
3635
3715
  await this.presentSteerMessage(record.localSessionId, activeTurnId, displayPrompt ?? text, workspaceMessageId ?? messageId, localImagePaths);
3636
3716
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, activeTurnId);
@@ -3639,7 +3719,7 @@ export class ProxySessionController {
3639
3719
  if (!(error instanceof TurnNotSubmittedError)) {
3640
3720
  throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
3641
3721
  }
3642
- if (workspace?.expectedTurnId) throw error;
3722
+ if (workspace?.expectedTurnId || workspace?.queuedPrompt) throw error;
3643
3723
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
3644
3724
  let current = loaded.runtime.getSession(record.localSessionId);
3645
3725
  try {
@@ -3656,6 +3736,7 @@ export class ProxySessionController {
3656
3736
  if (current.activeTurnId !== activeTurnId && !notificationTurn) {
3657
3737
  try {
3658
3738
  this.assertExecutionGeneration(record.localSessionId, executionGeneration);
3739
+ workspace?.onSubmitting();
3659
3740
  await loaded.runtime.steerTurn(
3660
3741
  record.localSessionId,
3661
3742
  current.activeTurnId,
@@ -4817,7 +4898,7 @@ export class ProxySessionController {
4817
4898
  messageId: options.messageId,
4818
4899
  replyMessageId: replyTarget?.messageId,
4819
4900
  executionGeneration,
4820
- });
4901
+ }, options.onWorkspaceClaim);
4821
4902
  }
4822
4903
  let turnId: string;
4823
4904
  let runtimeText = text;
@@ -4849,6 +4930,7 @@ export class ProxySessionController {
4849
4930
  cardPrompt,
4850
4931
  localImagePaths,
4851
4932
  options.workspaceRequestId,
4933
+ Boolean(options.onWorkspaceSubmitting),
4852
4934
  );
4853
4935
  } catch (error) {
4854
4936
  if (options.scheduleRunId) {
@@ -4891,6 +4973,7 @@ export class ProxySessionController {
4891
4973
  this.store.schedules.saveRun({ ...run!, status: "submitting" });
4892
4974
  }
4893
4975
  this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
4976
+ options.onWorkspaceSubmitting?.();
4894
4977
  turnId = await loaded.runtime.startTurn(
4895
4978
  loaded.record.localSessionId,
4896
4979
  options.approvedPlanTurnId
@@ -6022,8 +6105,12 @@ export class ProxySessionController {
6022
6105
  clearTimeout(retryTimer);
6023
6106
  this.queuedPromptRetryTimers.delete(sessionId);
6024
6107
  }
6108
+ return this.serializeQueuedPromptStart(sessionId, () => this.startNextQueuedPromptIfIdle(sessionId));
6109
+ }
6110
+
6111
+ private serializeQueuedPromptStart(sessionId: string, start: () => Promise<void>): Promise<void> {
6025
6112
  const previous = this.queuedPromptStarts.get(sessionId) ?? Promise.resolve();
6026
- const next = previous.catch(() => undefined).then(() => this.startNextQueuedPromptIfIdle(sessionId));
6113
+ const next = previous.catch(() => undefined).then(start);
6027
6114
  this.queuedPromptStarts.set(sessionId, next);
6028
6115
  return next.finally(() => {
6029
6116
  if (this.queuedPromptStarts.get(sessionId) === next) this.queuedPromptStarts.delete(sessionId);
@@ -6065,6 +6152,7 @@ export class ProxySessionController {
6065
6152
  const baseRecord = this.store.getSession(sessionId);
6066
6153
  if (!baseRecord || baseRecord.status === "closed") return;
6067
6154
  let prompt: QueuedPromptRecord | undefined;
6155
+ let finishDispatch: (() => void) | undefined;
6068
6156
  try {
6069
6157
  let loaded = await this.loadSession(baseRecord, Boolean(this.store.getPendingProviderSettings(sessionId)));
6070
6158
  const remoteActivity = await this.assertSessionTurnOwnership(loaded.record, loaded.runtime);
@@ -6078,6 +6166,7 @@ export class ProxySessionController {
6078
6166
  this.assertExecutionGeneration(sessionId, executionGeneration);
6079
6167
  prompt = this.store.takeNextQueuedPrompt(sessionId);
6080
6168
  if (!prompt) return;
6169
+ finishDispatch = this.store.trackQueuedPromptDispatch(prompt);
6081
6170
  const scheduledRun = this.store.schedules.getRun(prompt.promptId);
6082
6171
  let workspaceRequestId = prompt.promptId.startsWith("workspace:") ? prompt.promptId.slice("workspace:".length) : undefined;
6083
6172
  const record = this.store.getSessionForContext(sessionId, prompt.contextKey) ?? baseRecord;
@@ -6087,7 +6176,7 @@ export class ProxySessionController {
6087
6176
  if (!this.store.schedules.canSubmit(scheduledRun.id)
6088
6177
  || this.lifecycle?.canStartScheduledTasks?.() === false) throw new Error("定时任务已取消、过期或正在安全重启。");
6089
6178
  const job = this.store.schedules.require(scheduledRun.jobId);
6090
- if (job.attachments?.files.length) workspaceRequestId = scheduledRun.id.slice("schedule_run_".length);
6179
+ if (job.attachments?.files.length || job.attachments?.quotes?.length) workspaceRequestId = scheduledRun.id.slice("schedule_run_".length);
6091
6180
  this.assertScheduleTarget(job);
6092
6181
  let missingAttachment = false;
6093
6182
  try {
@@ -6095,7 +6184,7 @@ export class ProxySessionController {
6095
6184
  const available = await Promise.all(attachmentPaths.map(async file => (await fs.stat(file).catch(() => undefined))?.isFile()));
6096
6185
  missingAttachment = available.some(value => !value);
6097
6186
  if (missingAttachment) throw new Error("定时任务的附件已不可用。");
6098
- await this.notifySchedule(job, scheduleDisplayPrompt(job, queuedPromptContent(prompt).text), prompt.localImagePaths);
6187
+ await this.notifySchedule(job, scheduleDisplayPrompt(job, queuedPromptContent(prompt, job.attachments?.quotes).text), prompt.localImagePaths);
6099
6188
  } catch (error) {
6100
6189
  const reason = missingAttachment ? "定时任务的附件已不可用" : "原会话的 Prompt 发送失败";
6101
6190
  const currentJob = this.store.schedules.get(job.id);
@@ -6156,6 +6245,8 @@ export class ProxySessionController {
6156
6245
  if (this.store.countQueuedPrompts(sessionId) > 0) {
6157
6246
  queueMicrotask(() => void this.scheduleNextQueuedPrompt(sessionId));
6158
6247
  }
6248
+ } finally {
6249
+ finishDispatch?.();
6159
6250
  }
6160
6251
  }
6161
6252
 
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type Database from "better-sqlite3";
3
3
  import { appendDownloadedFiles, defaultResourcePromptFromCounts } from "../utils/promptAttachments.js";
4
+ import { appendPromptQuotes, promptQuoteInstruction } from "../utils/promptQuotes.js";
4
5
  import {
5
6
  nextScheduleTime,
6
7
  scheduleDisplayPrompt,
@@ -47,8 +48,8 @@ export class ScheduledTaskStore {
47
48
  }
48
49
  if (!spec.prompt) {
49
50
  const attachments = upload?.attachments;
50
- if (!attachments || (!attachments.images.length && !attachments.files.length)) throw new Error("请输入 Prompt 或添加附件。");
51
- spec.prompt = defaultResourcePromptFromCounts(attachments.images.length, attachments.files.length);
51
+ if (!attachments || (!attachments.images.length && !attachments.files.length && !attachments.quotes?.length)) throw new Error("请输入 Prompt 或添加附件。");
52
+ spec.prompt = promptQuoteInstruction(attachments.quotes) || defaultResourcePromptFromCounts(attachments.images.length, attachments.files.length);
52
53
  }
53
54
  const nextRunAt = nextScheduleTime(spec, now);
54
55
  if (nextRunAt === undefined) throw new Error("执行时间必须在将来。");
@@ -184,7 +185,7 @@ export class ScheduledTaskStore {
184
185
  const job = this.require(id, revision);
185
186
  if (!spec.prompt) {
186
187
  if (!job.attachments) throw new Error("请输入 Prompt 或添加附件。");
187
- spec.prompt = defaultResourcePromptFromCounts(job.attachments.images.length, job.attachments.files.length);
188
+ spec.prompt = promptQuoteInstruction(job.attachments.quotes) || defaultResourcePromptFromCounts(job.attachments.images.length, job.attachments.files.length);
188
189
  }
189
190
  this.cancelPending(id, "计划已编辑,等待重新确认。");
190
191
  return this.update(
@@ -291,6 +292,7 @@ export class ScheduledTaskStore {
291
292
  if (!detail) {
292
293
  const files = job.attachments?.files ?? [];
293
294
  const images = job.attachments?.images ?? [];
295
+ const prompt = appendPromptQuotes(job.spec.prompt, job.attachments?.quotes);
294
296
  this.db
295
297
  .prepare(
296
298
  `INSERT INTO queued_prompts (prompt_id, local_session_id, context_key, prompt_text,
@@ -300,7 +302,7 @@ export class ScheduledTaskStore {
300
302
  run.id,
301
303
  job.localSessionId,
302
304
  job.contextKey,
303
- files.length ? appendDownloadedFiles(job.spec.prompt, files) : job.spec.prompt,
305
+ files.length ? appendDownloadedFiles(prompt, files) : prompt,
304
306
  `[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${scheduleDisplayPrompt(job)}`,
305
307
  JSON.stringify(images),
306
308
  job.replyMessageId ?? null,
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { CronExpressionParser } from "cron-parser";
3
+ import type { PromptQuote } from "../utils/promptQuotes.js";
3
4
 
4
5
  export const scheduleInputSchema = z
5
6
  .object({
@@ -98,6 +99,7 @@ export interface ScheduledJob {
98
99
  export interface ScheduledPromptAttachments {
99
100
  images: string[];
100
101
  files: Array<{ fileName: string; filePath: string }>;
102
+ quotes?: PromptQuote[];
101
103
  }
102
104
  export type ScheduledRunStatus =
103
105
  | "queued"
@@ -152,7 +154,8 @@ export function latestScheduleTime(spec: ScheduleSpec, now: number): number {
152
154
  export function scheduleDisplayPrompt(job: ScheduledJob, prompt = job.spec.prompt): string {
153
155
  const names = job.attachments?.files.map(file => file.fileName) ?? [];
154
156
  const images = job.attachments?.images.length ?? 0;
155
- const attachments = [...(images ? [`${images} 张图片`] : []), ...names];
157
+ const quotes = job.attachments?.quotes?.length ?? 0;
158
+ const attachments = [...(images ? [`${images} 张图片`] : []), ...names, ...(quotes ? [`${quotes} 条引用或批注`] : [])];
156
159
  return [prompt, ...(attachments.length ? [`附件:${attachments.join("、")}`] : [])].join("\n\n");
157
160
  }
158
161