@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.
- package/CHANGELOG.md +14 -0
- package/README.md +37 -18
- package/README.zh.md +37 -18
- package/assets/workspace-sessions.js +959 -229
- package/assets/workspace.css +241 -57
- package/assets/workspace.js +1463 -227
- package/dist/feishu/FeishuTurnPresenter.js +26 -9
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +69 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +10 -7
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/PreviewSyntaxHighlight.js +1 -1
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +30 -7
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +28 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -1
- package/dist/local-files/WorkspacePage.js +5 -2
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +343 -96
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +34 -10
- package/dist/local-files/WorkspaceTimeline.js.map +1 -1
- package/dist/presentation/OutboundRouter.js +3 -1
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +3 -1
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +130 -45
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +6 -4
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +2 -1
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +77 -13
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +24 -13
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/utils/promptAttachments.js +4 -2
- package/dist/utils/promptAttachments.js.map +1 -1
- package/dist/utils/promptQuotes.js +47 -0
- package/dist/utils/promptQuotes.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/src/feishu/FeishuTurnPresenter.ts +27 -8
- package/src/local-files/GitDiffPreview.ts +72 -8
- package/src/local-files/LocalFileViewerServer.ts +10 -7
- package/src/local-files/PreviewSyntaxHighlight.ts +1 -1
- package/src/local-files/TurnPreviewPage.ts +35 -7
- package/src/local-files/WorkspaceImages.ts +25 -0
- package/src/local-files/WorkspacePage.ts +5 -2
- package/src/local-files/WorkspaceSessions.ts +318 -101
- package/src/local-files/WorkspaceTimeline.ts +41 -15
- package/src/presentation/OutboundRouter.ts +3 -0
- package/src/presentation/TurnStateReducer.ts +3 -1
- package/src/presentation/turnViewTypes.ts +1 -1
- package/src/proxy/ProxySessionController.ts +135 -44
- package/src/scheduling/ScheduledTaskStore.ts +6 -4
- package/src/scheduling/types.ts +4 -1
- package/src/state/StateStore.ts +83 -17
- package/src/state/TurnPreviewJournal.ts +27 -14
- package/src/utils/promptAttachments.ts +5 -2
- package/src/utils/promptQuotes.ts +48 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const lineNumber = z.string().regex(/^\d{1,10}(?:–\d{1,10})?$/u);
|
|
3
|
+
const quoteSource = z.union([
|
|
4
|
+
z.object({ path: z.string().min(1).max(4096), directory: z.literal(true).optional(), wholeLines: z.literal(true).optional(), line: lineNumber.optional(),
|
|
5
|
+
originalLine: lineNumber.optional(), originalPath: z.string().min(1).max(4096).optional() }).strict(),
|
|
6
|
+
z.object({ label: z.string().trim().min(1).max(160), turn: z.string().max(400).optional() }).strict(),
|
|
7
|
+
z.object({ label: z.string().trim().min(1).max(160), url: z.url({ protocol: /^https?$/u }).max(4096) }).strict(),
|
|
8
|
+
]);
|
|
9
|
+
const excerpt = z.string().max(100_000).refine(text => Boolean(text.trim()));
|
|
10
|
+
const sessionSource = z.object({
|
|
11
|
+
sessionId: z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u),
|
|
12
|
+
title: z.string().trim().min(1).max(200),
|
|
13
|
+
}).strict();
|
|
14
|
+
export const promptQuotesSchema = z.array(z.discriminatedUnion("kind", [
|
|
15
|
+
z.object({ kind: z.literal("reference"), source: z.union([quoteSource, sessionSource]), quote: excerpt.optional() }).strict(),
|
|
16
|
+
z.object({ kind: z.literal("annotation"), source: quoteSource, quote: excerpt, note: z.string().trim().min(1).max(8_000) }).strict(),
|
|
17
|
+
])).max(4);
|
|
18
|
+
function indented(text) {
|
|
19
|
+
return text.split(/\r?\n/u).map(line => ` ${line}`).join("\n");
|
|
20
|
+
}
|
|
21
|
+
function quoteSourceText(source) {
|
|
22
|
+
if ("sessionId" in source)
|
|
23
|
+
return `会话标题:${source.title}\n会话 ID:${source.sessionId}`;
|
|
24
|
+
if ("path" in source)
|
|
25
|
+
return [source.directory ? `目录路径:${source.path}` : source.path,
|
|
26
|
+
source.line && `第 ${source.line} 行`, source.originalLine && `变更前第 ${source.originalLine} 行`,
|
|
27
|
+
source.originalPath && `变更前的文件:${source.originalPath}`].filter(Boolean).join(" · ");
|
|
28
|
+
if ("url" in source)
|
|
29
|
+
return `${source.label}\n${source.url}`;
|
|
30
|
+
return source.turn ? `${source.label}\n轮次:${source.turn}` : source.label;
|
|
31
|
+
}
|
|
32
|
+
export function promptQuoteInstruction(quotes = []) {
|
|
33
|
+
if (quotes.some(item => item.kind === "annotation"))
|
|
34
|
+
return "请阅读所附批注,并处理其中提出的要求。";
|
|
35
|
+
return quotes.length ? "请查看所附引用。" : "";
|
|
36
|
+
}
|
|
37
|
+
export function appendPromptQuotes(prompt, quotes = []) {
|
|
38
|
+
return [prompt, ...quotes.map(item => {
|
|
39
|
+
const { source } = item;
|
|
40
|
+
const locationOnly = "path" in source && (source.directory || source.wholeLines && Boolean(source.line || source.originalLine));
|
|
41
|
+
return [item.kind === "annotation" ? "批注来源:" : "引用来源:", indented(quoteSourceText(source)),
|
|
42
|
+
...(item.quote && !locationOnly ? ["原文:", indented(item.quote)] : []),
|
|
43
|
+
...(item.kind === "annotation" ? ["用户批注:", indented(item.note)] : []),
|
|
44
|
+
].join("\n");
|
|
45
|
+
})].join("\n\n");
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=promptQuotes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"promptQuotes.js","sourceRoot":"","sources":["../../src/utils/promptQuotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;AACjE,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC;IAC1B,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,UAAU,CAAC,QAAQ,EAAE;QACtJ,YAAY,EAAE,UAAU,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;IACvG,CAAC,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAA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,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aACtE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACf,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC"}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@keyou007/agent-bot",
|
|
3
|
-
"version": "0.1.27-alpha.
|
|
3
|
+
"version": "0.1.27-alpha.5",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@keyou007/agent-bot",
|
|
9
|
-
"version": "0.1.27-alpha.
|
|
9
|
+
"version": "0.1.27-alpha.5",
|
|
10
10
|
"license": "GPL-3.0-only",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@agentclientprotocol/sdk": "1.2.1",
|
package/package.json
CHANGED
|
@@ -77,6 +77,7 @@ interface TurnEntry {
|
|
|
77
77
|
reactionId?: string;
|
|
78
78
|
reactionEmoji?: string;
|
|
79
79
|
scheduler?: CardUpdateScheduler<TurnViewState>;
|
|
80
|
+
localFirst?: boolean;
|
|
80
81
|
elapsedTimer?: ReturnType<typeof setInterval>;
|
|
81
82
|
finalizing?: Promise<void>;
|
|
82
83
|
lastFinalizedStatus?: TurnViewState["status"];
|
|
@@ -168,10 +169,11 @@ export class FeishuTurnPresenter {
|
|
|
168
169
|
prompt?: string,
|
|
169
170
|
localImagePaths?: string[],
|
|
170
171
|
promptRequestId?: string,
|
|
172
|
+
localFirst?: boolean,
|
|
171
173
|
): Promise<string | undefined> {
|
|
172
174
|
const existing = this.pendingEntries.get(sessionId);
|
|
173
175
|
if (existing) {
|
|
174
|
-
await existing.initializing;
|
|
176
|
+
if (!localFirst) await existing.initializing;
|
|
175
177
|
if (existing.continuing) {
|
|
176
178
|
existing.state = { ...existing.state, status: "running", error: undefined, completedAt: undefined, durationMs: undefined };
|
|
177
179
|
this.persist(existing.state.turnId, sessionId, existing.state, existing.contextKey);
|
|
@@ -206,11 +208,15 @@ export class FeishuTurnPresenter {
|
|
|
206
208
|
this.sessionReasoningEfforts.get(sessionId),
|
|
207
209
|
);
|
|
208
210
|
if (promptRequestId) state.promptRequestId = promptRequestId;
|
|
209
|
-
const entry = { contextKey, state, initializing: Promise.resolve() }
|
|
211
|
+
const entry: TurnEntry = { contextKey, state, localFirst, initializing: Promise.resolve() };
|
|
210
212
|
this.entries.set(state.turnId, entry);
|
|
211
213
|
this.pendingEntries.set(sessionId, entry);
|
|
212
214
|
this.persist(state.turnId, sessionId, state, contextKey);
|
|
213
215
|
entry.initializing = this.initializeEntry(entry);
|
|
216
|
+
if (localFirst) {
|
|
217
|
+
entry.initializing = entry.initializing.catch(error => { this.options.onError?.(error); });
|
|
218
|
+
return state.turnId;
|
|
219
|
+
}
|
|
214
220
|
try {
|
|
215
221
|
await entry.initializing;
|
|
216
222
|
return state.turnId;
|
|
@@ -240,6 +246,14 @@ export class FeishuTurnPresenter {
|
|
|
240
246
|
durationMs: entry.continuing ? undefined : Math.max(0, completedAt - entry.state.startedAt),
|
|
241
247
|
};
|
|
242
248
|
this.persist(entry.state.turnId, sessionId, entry.state, entry.contextKey);
|
|
249
|
+
if (entry.localFirst && !replacementCard) {
|
|
250
|
+
void this.presentPendingFailure(entry).catch(error => this.options.onError?.(error));
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
return this.presentPendingFailure(entry, replacementCard);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async presentPendingFailure(entry: TurnEntry, replacementCard?: Record<string, unknown>): Promise<boolean> {
|
|
243
257
|
await entry.initializing;
|
|
244
258
|
try {
|
|
245
259
|
await entry.scheduler?.flush(entry.state);
|
|
@@ -299,6 +313,7 @@ export class FeishuTurnPresenter {
|
|
|
299
313
|
localImagePaths?: string[],
|
|
300
314
|
): Promise<void> {
|
|
301
315
|
const activityId = `steer:${messageId ?? createId("message")}`;
|
|
316
|
+
const startedAt = Date.now();
|
|
302
317
|
let entry = this.entries.get(turnId);
|
|
303
318
|
const saved = entry?.state ?? this.store.getTurnSnapshot(turnId);
|
|
304
319
|
if (isTurnViewState(saved) && saved.taskNotificationCard) return;
|
|
@@ -325,19 +340,23 @@ export class FeishuTurnPresenter {
|
|
|
325
340
|
status: "running" as const,
|
|
326
341
|
};
|
|
327
342
|
this.store.previews?.seed(initial);
|
|
328
|
-
this.store.previews?.user(initial.previewTurnId ?? turnId, activityId, text, localImagePaths);
|
|
329
|
-
const state = this.cardState(appendSteerMessageToState(initial, activityId, text, localImagePaths));
|
|
330
|
-
entry = { contextKey, state, initializing: Promise.resolve() }
|
|
343
|
+
this.store.previews?.user(initial.previewTurnId ?? turnId, activityId, text, localImagePaths, startedAt);
|
|
344
|
+
const state = this.cardState(appendSteerMessageToState(initial, activityId, text, localImagePaths, startedAt));
|
|
345
|
+
entry = { contextKey, state, localFirst: messageId?.startsWith("workspace:"), initializing: Promise.resolve() };
|
|
331
346
|
this.entries.set(turnId, entry);
|
|
332
347
|
this.persist(turnId, sessionId, state, contextKey);
|
|
333
348
|
entry.initializing = this.initializeEntry(entry);
|
|
349
|
+
if (entry.localFirst) {
|
|
350
|
+
entry.initializing = entry.initializing.catch(error => { this.options.onError?.(error); });
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
334
353
|
await entry.initializing;
|
|
335
354
|
return;
|
|
336
355
|
}
|
|
337
356
|
|
|
338
357
|
await entry.initializing;
|
|
339
|
-
this.store.previews?.user(entry.state.previewTurnId ?? turnId, activityId, text, localImagePaths);
|
|
340
|
-
entry.state = this.cardState(appendSteerMessageToState(entry.state, activityId, text, localImagePaths));
|
|
358
|
+
this.store.previews?.user(entry.state.previewTurnId ?? turnId, activityId, text, localImagePaths, startedAt);
|
|
359
|
+
entry.state = this.cardState(appendSteerMessageToState(entry.state, activityId, text, localImagePaths, startedAt));
|
|
341
360
|
this.persist(turnId, sessionId, entry.state, entry.contextKey);
|
|
342
361
|
if (!entry.historySnapshot) entry.scheduler?.update(entry.state, "critical");
|
|
343
362
|
}
|
|
@@ -444,7 +463,7 @@ export class FeishuTurnPresenter {
|
|
|
444
463
|
}
|
|
445
464
|
|
|
446
465
|
await entry.initializing;
|
|
447
|
-
if (!entry.scheduler && !(event.type === "turn_completed" && entry.state.taskNotificationCard)) return;
|
|
466
|
+
if (!entry.scheduler && !entry.localFirst && !(event.type === "turn_completed" && entry.state.taskNotificationCard)) return;
|
|
448
467
|
|
|
449
468
|
if (event.type === "turn_status_unknown" && entry.state.status === "unknown") {
|
|
450
469
|
if (this.pendingEntries.get(event.sessionId) === entry) this.pendingEntries.delete(event.sessionId);
|
|
@@ -56,9 +56,10 @@ export async function readGitFileDiff(filePath: string): Promise<string | undefi
|
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
type DiffLine = { kind: "context" | "addition" | "deletion"; text: string; oldNumber?: number; newNumber?: number };
|
|
59
|
+
type DiffLine = { kind: "context" | "addition" | "deletion"; text: string; oldNumber?: number; newNumber?: number; hunk?: string };
|
|
60
60
|
|
|
61
61
|
const PATCH_HUNK_START = /(?=^@@(?:[ \t]|$))/mu;
|
|
62
|
+
export const PATCH_HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/u;
|
|
62
63
|
|
|
63
64
|
export function highlightRecordedPatch(patch: string, filePath: string, originalPath: string): string | undefined {
|
|
64
65
|
if (Buffer.byteLength(patch, "utf8") > MAX_PREVIEW_HIGHLIGHT_BYTES) return undefined;
|
|
@@ -108,7 +109,7 @@ export function renderGitFileDiff(diff: string, currentText: string, highlight?:
|
|
|
108
109
|
// Git identifies edits; fill the gaps from the complete current file, checking hunk coordinates and text.
|
|
109
110
|
for (let index = 1; index < lines.length; index += 1) {
|
|
110
111
|
const line = lines[index]!;
|
|
111
|
-
const hunk =
|
|
112
|
+
const hunk = PATCH_HUNK_HEADER.exec(line);
|
|
112
113
|
if (!hunk) {
|
|
113
114
|
if (line === "\") continue;
|
|
114
115
|
if (inHunks || line.startsWith("@@") || line.startsWith("diff --git ") || line === "GIT binary patch") return undefined;
|
|
@@ -137,19 +138,81 @@ export function renderGitFileDiff(diff: string, currentText: string, highlight?:
|
|
|
137
138
|
while (newLine <= source.length) if (!append("context", source[newLine - 1]!)) return undefined;
|
|
138
139
|
const before = highlight?.(rows.filter((row) => row.kind !== "addition").map((row) => row.text).join("\n"));
|
|
139
140
|
const after = highlight?.(source.join("\n"));
|
|
140
|
-
const
|
|
141
|
+
const oldNumberWidth = Math.max(2, String(oldLine - 1).length);
|
|
142
|
+
const newNumberWidth = Math.max(2, String(newLine - 1).length);
|
|
143
|
+
return renderDiffRows(rows, oldNumberWidth, newNumberWidth, "Git diff", (row) =>
|
|
144
|
+
row.kind === "deletion" ? before?.[row.oldNumber! - 1] : after?.[row.newNumber! - 1]);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function renderRecordedDiff(
|
|
148
|
+
patch: string, filePath: string, originalPath: string, additions?: number, deletions?: number,
|
|
149
|
+
): string {
|
|
150
|
+
const label = "本次修改";
|
|
151
|
+
const normalized = patch.replace(/\r\n?/gu, "\n");
|
|
152
|
+
const rows: Array<DiffLine & { highlighted?: string }> = [];
|
|
153
|
+
if (PATCH_HUNK_START.test(normalized)) {
|
|
154
|
+
for (const block of normalized.split(PATCH_HUNK_START)) {
|
|
155
|
+
const [header, ...lines] = splitLines(block);
|
|
156
|
+
const range = header && PATCH_HUNK_HEADER.exec(header);
|
|
157
|
+
if (!range) continue;
|
|
158
|
+
let oldNumber = Number(range[1]), newNumber = Number(range[3]);
|
|
159
|
+
let oldRemaining = Number(range[2] ?? 1), newRemaining = Number(range[4] ?? 1);
|
|
160
|
+
if (![oldNumber, newNumber, oldRemaining, newRemaining].every(Number.isSafeInteger)) continue;
|
|
161
|
+
const hunk: DiffLine[] = [];
|
|
162
|
+
for (const line of lines) {
|
|
163
|
+
if (line === "\") continue;
|
|
164
|
+
const marker = line[0];
|
|
165
|
+
if (marker !== " " && marker !== "+" && marker !== "-") break;
|
|
166
|
+
if ((marker !== "+" && oldRemaining-- <= 0) || (marker !== "-" && newRemaining-- <= 0)) break;
|
|
167
|
+
hunk.push({ kind: marker === "+" ? "addition" : marker === "-" ? "deletion" : "context", text: line.slice(1),
|
|
168
|
+
oldNumber: marker === "+" ? undefined : oldNumber++, newNumber: marker === "-" ? undefined : newNumber++,
|
|
169
|
+
hunk: hunk.length ? undefined : header });
|
|
170
|
+
}
|
|
171
|
+
const before = highlightTextLines(hunk.filter((row) => row.kind !== "addition").map((row) => row.text).join("\n"), originalPath);
|
|
172
|
+
const after = highlightTextLines(hunk.filter((row) => row.kind !== "deletion").map((row) => row.text).join("\n"), filePath);
|
|
173
|
+
let oldIndex = 0, newIndex = 0;
|
|
174
|
+
for (const row of hunk) {
|
|
175
|
+
const left = row.kind === "addition" ? undefined : before[oldIndex++];
|
|
176
|
+
const right = row.kind === "deletion" ? undefined : after[newIndex++];
|
|
177
|
+
rows.push({ ...row, highlighted: right ?? left });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
} else if (!/^diff --git |^--- [^\n]*\n\+\+\+ /u.test(normalized)) {
|
|
181
|
+
// Whole-file additions and deletions are recorded as file contents instead of hunks.
|
|
182
|
+
const kind = additions && deletions === 0 ? "addition" : deletions && additions === 0 ? "deletion" : undefined;
|
|
183
|
+
if (kind) {
|
|
184
|
+
const highlighted = highlightTextLines(normalized, kind === "addition" ? filePath : originalPath);
|
|
185
|
+
splitLines(normalized).forEach((text, index) => rows.push({ kind, text, highlighted: highlighted[index],
|
|
186
|
+
...(kind === "addition" ? { newNumber: index + 1 } : { oldNumber: index + 1 }) }));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!rows.length) {
|
|
190
|
+
return `<pre class="code" aria-label="${label}"><code>${highlightRecordedPatch(patch, filePath, originalPath) ?? escapeHtml(patch)}</code></pre>`;
|
|
191
|
+
}
|
|
192
|
+
let oldWidth = 2, newWidth = 2;
|
|
193
|
+
for (const row of rows) {
|
|
194
|
+
oldWidth = Math.max(oldWidth, String(row.oldNumber ?? "").length);
|
|
195
|
+
newWidth = Math.max(newWidth, String(row.newNumber ?? "").length);
|
|
196
|
+
}
|
|
197
|
+
return renderDiffRows(rows, oldWidth, newWidth, label, (_row, index) => rows[index]?.highlighted);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function renderDiffRows(
|
|
201
|
+
rows: DiffLine[], oldNumberWidth: number, newNumberWidth: number, label: string,
|
|
202
|
+
highlight: (row: DiffLine, index: number) => string | undefined,
|
|
203
|
+
): string {
|
|
204
|
+
const content = rows.map((row, index) => {
|
|
141
205
|
const id = row.newNumber !== undefined ? `L${row.newNumber}` : `D${row.oldNumber}`;
|
|
142
206
|
const oldNumber = `<span class="diff-number" aria-hidden="true">${row.oldNumber ?? ""}</span>`;
|
|
143
207
|
const newNumber = row.newNumber !== undefined
|
|
144
208
|
? `<a class="diff-number" href="#${id}" aria-label="Line ${row.newNumber}">${row.newNumber}</a>`
|
|
145
209
|
: '<span class="diff-number" aria-hidden="true"></span>';
|
|
146
210
|
const marker = row.kind === "addition" ? "+" : row.kind === "deletion" ? "-" : " ";
|
|
147
|
-
const text = row
|
|
148
|
-
|
|
211
|
+
const text = highlight(row, index);
|
|
212
|
+
const header = row.hunk ? `<span class="line diff-hunk">${escapeHtml(row.hunk)}</span>` : "";
|
|
213
|
+
return `${header}<span class="line diff-${row.kind}" id="${id}">${oldNumber}${newNumber}<span class="diff-marker" aria-hidden="true">${marker}</span><span class="diff-text">${text ?? escapeHtml(row.text)}</span></span>`;
|
|
149
214
|
}).join("");
|
|
150
|
-
|
|
151
|
-
const newNumberWidth = Math.max(2, String(newLine - 1).length);
|
|
152
|
-
return `<pre class="code git-diff" aria-label="Git diff" style="--old-line-number-width:${oldNumberWidth}ch;--new-line-number-width:${newNumberWidth}ch"><code>${content}</code></pre>`;
|
|
215
|
+
return `<pre class="code git-diff" aria-label="${label}" style="--old-line-number-width:${oldNumberWidth}ch;--new-line-number-width:${newNumberWidth}ch"><code>${content}</code></pre>`;
|
|
153
216
|
}
|
|
154
217
|
|
|
155
218
|
function splitLines(value: string): string[] {
|
|
@@ -166,6 +229,7 @@ export const GIT_DIFF_PREVIEW_CSS = `
|
|
|
166
229
|
.git-diff .diff-number:first-child { width:var(--old-line-number-width, 2ch); }
|
|
167
230
|
.git-diff .diff-marker { flex:0 0 2em; width:2em; text-align:center; user-select:none; }
|
|
168
231
|
.git-diff .diff-text { white-space:pre; }
|
|
232
|
+
.git-diff .diff-hunk { padding-inline-start:6px; color:var(--git-diff-gutter-text, light-dark(#6e7781, #8b949e)); }
|
|
169
233
|
.git-diff .diff-addition { background:var(--git-diff-added-bg, light-dark(#dafbe1, #033a16)); color:var(--git-diff-added-text, light-dark(#116329, #aff5b4)); }
|
|
170
234
|
.git-diff .diff-deletion { background:var(--git-diff-removed-bg, light-dark(#ffebe9, #67060c)); color:var(--git-diff-removed-text, light-dark(#a40e26, #ffdcd7)); }
|
|
171
235
|
@media (max-width:640px) { .git-diff .diff-number { padding:0 4px; } }
|
|
@@ -47,6 +47,7 @@ const WORKSPACE_QUERY = z.object({
|
|
|
47
47
|
api: z.string().optional(), entry: z.string().default(""),
|
|
48
48
|
page: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
49
49
|
mode: z.enum(["all", "staged", "unstaged"]).default("all"), original: z.string().optional(),
|
|
50
|
+
source: z.literal("1").optional(),
|
|
50
51
|
prefetch: z.enum(["0", "1"]).optional(), query: z.string().trim().max(160).optional(),
|
|
51
52
|
refresh: z.enum(["1"]).optional(),
|
|
52
53
|
instance: z.string().regex(/^[a-f0-9]{16}$/u).optional(),
|
|
@@ -1144,7 +1145,7 @@ export class LocalFileViewerServer {
|
|
|
1144
1145
|
}
|
|
1145
1146
|
const parsed = WORKSPACE_QUERY.safeParse(Object.fromEntries(url.searchParams));
|
|
1146
1147
|
if (!parsed.success) throw new WorkspaceError("工作台参数无效:" + parsed.error.issues.map((issue) => issue.message).join(";"));
|
|
1147
|
-
const { api, entry, page, mode, original, prefetch, query, instance, refresh } = parsed.data;
|
|
1148
|
+
const { api, entry, page, mode, original, prefetch, query, instance, refresh, source } = parsed.data;
|
|
1148
1149
|
if (scopedBase && (api === "terminal" || api === "web-title")) throw new WorkspaceError("该目录只支持文件浏览。", 404);
|
|
1149
1150
|
if (api === "events") {
|
|
1150
1151
|
if (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)) {
|
|
@@ -1192,7 +1193,7 @@ export class LocalFileViewerServer {
|
|
|
1192
1193
|
const file = resolveWorkspacePath(root, entry, true);
|
|
1193
1194
|
const before = classifyContentSample(versions.before, true), after = classifyContentSample(versions.after, true);
|
|
1194
1195
|
let html: string;
|
|
1195
|
-
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff
|
|
1196
|
+
if (before.kind === "binary" || after.kind === "binary") html = '<div class="workspace-notice">这个文件是二进制格式,无法显示文本 Diff。</div>';
|
|
1196
1197
|
else {
|
|
1197
1198
|
const previous = decodeText(versions.before, before.encoding, true), current = decodeText(versions.after, after.encoding, true);
|
|
1198
1199
|
html = renderWorkspaceDiff(await createWorkspaceDiff(root, previous, current), current, (value) => highlightTextLines(value, file));
|
|
@@ -1212,18 +1213,20 @@ export class LocalFileViewerServer {
|
|
|
1212
1213
|
raw.searchParams.set("api", "raw"); raw.searchParams.set("entry", entry);
|
|
1213
1214
|
const classification = classifyFileContent(file, stat.size);
|
|
1214
1215
|
const type = binaryContentTypeFor(path.extname(file).toLowerCase());
|
|
1216
|
+
const canTogglePreview = classification.kind === "text" && isMarkdownFile(file);
|
|
1215
1217
|
let html: string;
|
|
1216
1218
|
if (classification.kind === "text") {
|
|
1217
1219
|
const preview = readTextPreview(file, stat.size, classification.encoding);
|
|
1218
1220
|
const lines = preview.text.split(/\r\n?|\n/u);
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
+
const text = lines.slice(0, 10_000).join("\n");
|
|
1222
|
+
html = (preview.truncated || lines.length > 10_000 ? '<div class="workspace-notice">文件较大,仅显示前 2 MiB 或 10000 行。</div>' : "")
|
|
1223
|
+
+ (canTogglePreview && source !== "1" ? this.renderWorkspaceMarkdown(root, file, text, workspaceUrl) : renderText(text, file));
|
|
1221
1224
|
} else if (type.startsWith("image/")) {
|
|
1222
1225
|
html = '<div class="workspace-media"><img src="' + escapeAttribute(raw.toString()) + '" alt="' + escapeAttribute(path.basename(file)) + '"></div>';
|
|
1223
1226
|
} else if (type === "application/pdf") {
|
|
1224
|
-
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '"
|
|
1227
|
+
html = '<object class="workspace-pdf" type="application/pdf" data="' + escapeAttribute(raw.toString()) + '">当前浏览器无法显示 PDF 预览。</object>';
|
|
1225
1228
|
} else {
|
|
1226
|
-
html = '<div class="workspace-notice"
|
|
1229
|
+
html = '<div class="workspace-notice">这个文件是二进制格式,当前没有可用的预览。</div>';
|
|
1227
1230
|
}
|
|
1228
1231
|
let change: WorkspaceChange | undefined, gitError: string | undefined;
|
|
1229
1232
|
try {
|
|
@@ -1231,7 +1234,7 @@ export class LocalFileViewerServer {
|
|
|
1231
1234
|
const normalize = (value: string) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
1232
1235
|
change = (await readWorkspaceGitStatus(root)).changes.find(item => normalize(item.path) === normalize(relative));
|
|
1233
1236
|
} catch (error) { gitError = error instanceof Error ? error.message : String(error); }
|
|
1234
|
-
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), change, gitError }, headOnly, request);
|
|
1237
|
+
this.sendWorkspaceJson(response, 200, { html, rawUrl: raw.toString(), canTogglePreview, change, gitError }, headOnly, request);
|
|
1235
1238
|
}
|
|
1236
1239
|
|
|
1237
1240
|
private renderWorkspaceMarkdown(root: string, file: string, value: string, workspaceUrl: string): string {
|
|
@@ -86,7 +86,7 @@ export function highlightLines(value: string, language: string): string[] {
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
function splitHighlightedLines(value: string): string[] {
|
|
89
|
+
export function splitHighlightedLines(value: string): string[] {
|
|
90
90
|
const lines: string[] = [];
|
|
91
91
|
const openTags: string[] = [];
|
|
92
92
|
const tokenPattern = /<span class="[^"]+">|<\/span>|\n/gu;
|
|
@@ -1065,8 +1065,41 @@ function fileDelta(file: { additions?: number; deletions?: number }): string {
|
|
|
1065
1065
|
return additions || deletions ? `<span class="file-delta">${additions}${deletions}</span>` : "";
|
|
1066
1066
|
}
|
|
1067
1067
|
|
|
1068
|
+
type TurnUsage = Partial<Record<"totalTokens" | "cachedInputTokens" | "totalTokensIncludingCache" | "modelCallCount" | "totalToolCount", number | null>>;
|
|
1069
|
+
type TurnUsageField = { text: string; title?: string };
|
|
1070
|
+
|
|
1071
|
+
export function turnUsageFields(usage: TurnUsage, language: TurnPreviewLanguage = "zh") {
|
|
1072
|
+
const labels = previewLabels(language);
|
|
1073
|
+
const tokens: TurnUsageField[] = [], activity: TurnUsageField[] = [];
|
|
1074
|
+
if (usage.totalTokens != null) {
|
|
1075
|
+
const amount = `${formatTokenCount(usage.totalTokens)} tokens`;
|
|
1076
|
+
tokens.push(usage.cachedInputTokens == null ? { text: amount, title: labels.turnTokens } : {
|
|
1077
|
+
text: `${labels.nonCachedTokens} ${amount}`, title: `${labels.nonCachedTokens}: ${formatNumber(usage.totalTokens)} tokens`,
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
if (usage.totalTokensIncludingCache != null) {
|
|
1081
|
+
tokens.push({
|
|
1082
|
+
text: `${labels.totalTokens} ${formatTokenCount(usage.totalTokensIncludingCache)} tokens`,
|
|
1083
|
+
title: `${labels.totalTokens}: ${formatNumber(usage.totalTokensIncludingCache)} tokens`,
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
if (usage.modelCallCount != null && Number.isSafeInteger(usage.modelCallCount) && usage.modelCallCount >= 0) {
|
|
1087
|
+
activity.push({
|
|
1088
|
+
text: `${labels.modelCalls} ${formatNumber(usage.modelCallCount)}${language === "zh" ? " 次" : ""}`,
|
|
1089
|
+
title: labels.modelCallsDescription,
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
if (usage.totalToolCount != null && usage.totalToolCount > 0) {
|
|
1093
|
+
activity.push({ text: `${formatNumber(usage.totalToolCount)} ${labels.tools}` });
|
|
1094
|
+
}
|
|
1095
|
+
return { tokens, activity };
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1068
1098
|
function renderMetadata(state: TurnViewState, language: TurnPreviewLanguage): string {
|
|
1069
1099
|
const labels = previewLabels(language);
|
|
1100
|
+
const usage = turnUsageFields(state, language);
|
|
1101
|
+
const renderField = ({ text, title }: TurnUsageField) =>
|
|
1102
|
+
`<span${title ? ` title="${escapeAttribute(title)}"` : ""}>${escapeHtml(text)}</span>`;
|
|
1070
1103
|
const completedAt = state.completedAt ?? (isTerminal(state.status) && state.durationMs !== undefined
|
|
1071
1104
|
? state.startedAt + state.durationMs
|
|
1072
1105
|
: undefined);
|
|
@@ -1075,15 +1108,10 @@ function renderMetadata(state: TurnViewState, language: TurnPreviewLanguage): st
|
|
|
1075
1108
|
elapsed,
|
|
1076
1109
|
state.modelProvider?.trim() ? `<span title="Provider">${escapeHtml(state.modelProvider.trim())}</span>` : "",
|
|
1077
1110
|
state.model?.trim() ? `<span title="${escapeAttribute(labels.model)}">${escapeHtml(state.model.trim())}</span>` : "",
|
|
1078
|
-
|
|
1079
|
-
? `<span title="${escapeAttribute(labels.turnTokens)}">${formatTokenCount(state.totalTokens)} tokens</span>`
|
|
1080
|
-
: `<span title="${escapeAttribute(labels.nonCachedTokens)}: ${formatNumber(state.totalTokens)} tokens">${escapeHtml(labels.nonCachedTokens)} ${formatTokenCount(state.totalTokens)} tokens</span>`,
|
|
1081
|
-
state.totalTokensIncludingCache === undefined ? "" : `<span title="${escapeAttribute(labels.totalTokens)}: ${formatNumber(state.totalTokensIncludingCache)} tokens">${escapeHtml(labels.totalTokens)} ${formatTokenCount(state.totalTokensIncludingCache)} tokens</span>`,
|
|
1111
|
+
...usage.tokens.map(renderField),
|
|
1082
1112
|
state.latestContextTokens !== undefined && Number.isFinite(state.latestContextTokens) && state.latestContextTokens >= 0
|
|
1083
1113
|
? `<span title="${escapeAttribute(labels.contextTokens)}: ${formatNumber(state.latestContextTokens)} tokens">${escapeHtml(labels.contextTokens)} ${formatTokenCount(state.latestContextTokens)} tokens</span>` : "",
|
|
1084
|
-
|
|
1085
|
-
? `<span title="${escapeAttribute(labels.modelCallsDescription)}">${escapeHtml(labels.modelCalls)} ${formatNumber(state.modelCallCount)}${language === "zh" ? " 次" : ""}</span>` : "",
|
|
1086
|
-
(state.totalToolCount ?? 0) > 0 ? `<span>${formatNumber(state.totalToolCount ?? 0)} ${escapeHtml(labels.tools)}</span>` : "",
|
|
1114
|
+
...usage.activity.map(renderField),
|
|
1087
1115
|
].filter(Boolean);
|
|
1088
1116
|
return fields.join("");
|
|
1089
1117
|
}
|
|
@@ -8,3 +8,28 @@ export function workspaceImageExtension(bytes: Buffer): string | undefined {
|
|
|
8
8
|
if (bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP"
|
|
9
9
|
&& ["VP8 ", "VP8L", "VP8X"].includes(bytes.toString("ascii", 12, 16))) return ".webp";
|
|
10
10
|
}
|
|
11
|
+
|
|
12
|
+
export const WORKSPACE_PNG_HEADER_BYTES = 64 * 1024;
|
|
13
|
+
|
|
14
|
+
export function workspacePngDisplaySize(view: DataView): [number, number] | undefined {
|
|
15
|
+
if (view.byteLength < 33 || view.getUint32(0) !== 0x89504e47 || view.getUint32(4) !== 0x0d0a1a0a
|
|
16
|
+
|| view.getUint32(8) !== 13 || view.getUint32(12) !== 0x49484452) return;
|
|
17
|
+
const width = view.getUint32(16), height = view.getUint32(20);
|
|
18
|
+
if (!width || !height || Math.max(width, height) > 1_000_000) return;
|
|
19
|
+
for (let offset = 33; offset + 12 <= view.byteLength;) {
|
|
20
|
+
const length = view.getUint32(offset), type = view.getUint32(offset + 4), data = offset + 8;
|
|
21
|
+
if (type === 0x49444154 || type === 0x49454e44 || data + length + 4 > view.byteLength) return;
|
|
22
|
+
if (type === 0x70485973) { // pHYs specifies physical density when its unit is meters.
|
|
23
|
+
if (length !== 9 || view.getUint8(data + 8) !== 1) return;
|
|
24
|
+
const pixelsPerMeter = view.getUint32(data);
|
|
25
|
+
if (pixelsPerMeter !== view.getUint32(data + 4)) return;
|
|
26
|
+
const dpi = Math.round(pixelsPerMeter * 0.0254);
|
|
27
|
+
if (dpi <= 96) return;
|
|
28
|
+
return [Math.max(1, Math.round(width * 96 / dpi)), Math.max(1, Math.round(height * 96 / dpi))];
|
|
29
|
+
}
|
|
30
|
+
offset = data + length + 4;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const WORKSPACE_IMAGE_CLIENT_SCRIPT = `const workspacePngHeaderBytes = ${WORKSPACE_PNG_HEADER_BYTES};
|
|
35
|
+
const workspacePngDisplaySize = ${workspacePngDisplaySize.toString()};\n`;
|
|
@@ -2,13 +2,16 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { readPackageVersion } from "../cli/packageVersion.js";
|
|
5
|
-
import { GIT_DIFF_PREVIEW_CSS } from "./GitDiffPreview.js";
|
|
5
|
+
import { GIT_DIFF_PREVIEW_CSS, PATCH_HUNK_HEADER } from "./GitDiffPreview.js";
|
|
6
6
|
import { DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
|
|
7
7
|
import { previewCodeFontCss } from "./PreviewCodeFont.js";
|
|
8
8
|
import { MARKDOWN_EXPORT_CLIENT_SCRIPT } from "./MarkdownExport.js";
|
|
9
9
|
import { LIVE_MARKUP_CLIENT_SCRIPT } from "./LiveMarkup.js";
|
|
10
|
+
import { WORKSPACE_IMAGE_CLIENT_SCRIPT } from "./WorkspaceImages.js";
|
|
11
|
+
import { splitHighlightedLines } from "./PreviewSyntaxHighlight.js";
|
|
10
12
|
|
|
11
|
-
export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + MARKDOWN_EXPORT_CLIENT_SCRIPT + LIVE_MARKUP_CLIENT_SCRIPT
|
|
13
|
+
export const WORKSPACE_SCRIPT = DIAGRAM_PREVIEW_CLIENT_SCRIPT + MARKDOWN_EXPORT_CLIENT_SCRIPT + LIVE_MARKUP_CLIENT_SCRIPT + WORKSPACE_IMAGE_CLIENT_SCRIPT
|
|
14
|
+
+ `const workspaceHighlightedLines = ${splitHighlightedLines.toString()};\nconst workspacePatchHunkHeader = ${PATCH_HUNK_HEADER};\n`
|
|
12
15
|
+ fs.readFileSync(new URL("../../assets/workspace-drafts.js", import.meta.url), "utf8")
|
|
13
16
|
+ fs.readFileSync(new URL("../../assets/workspace-sessions.js", import.meta.url), "utf8")
|
|
14
17
|
+ fs.readFileSync(new URL("../../assets/workspace.js", import.meta.url), "utf8");
|