pi-render-btw 0.6.9 → 0.6.11
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 +8 -0
- package/README.md +18 -2
- package/extensions/btw/peek.test.ts +33 -0
- package/extensions/btw/peek.ts +157 -7
- package/extensions/btw/transcript-store.ts +423 -0
- package/extensions/btw-transcript.test.ts +260 -2
- package/extensions/btw.ts +970 -118
- package/package.json +2 -1
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
appendFileSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
unlinkSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
} from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
/** The on-disk format is deliberately independent from the Pi core session schema. */
|
|
14
|
+
export const BTW_TRANSCRIPT_SCHEMA_VERSION = 1 as const;
|
|
15
|
+
|
|
16
|
+
export type DurableTranscriptEntry = {
|
|
17
|
+
id: number;
|
|
18
|
+
turnId: number;
|
|
19
|
+
type:
|
|
20
|
+
| "turn-boundary"
|
|
21
|
+
| "user-message"
|
|
22
|
+
| "thinking"
|
|
23
|
+
| "assistant-text"
|
|
24
|
+
| "tool-call"
|
|
25
|
+
| "tool-result";
|
|
26
|
+
phase?: "start" | "end";
|
|
27
|
+
text?: string;
|
|
28
|
+
toolCallId?: string;
|
|
29
|
+
toolName?: string;
|
|
30
|
+
args?: string;
|
|
31
|
+
content?: string;
|
|
32
|
+
fullContent?: string;
|
|
33
|
+
truncated?: boolean;
|
|
34
|
+
isError?: boolean;
|
|
35
|
+
streaming?: boolean;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type DurableTranscriptSnapshot = {
|
|
39
|
+
schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
|
|
40
|
+
recordId: string;
|
|
41
|
+
threadId: string;
|
|
42
|
+
timestamp: number;
|
|
43
|
+
mode: "contextual" | "tangent";
|
|
44
|
+
entries: DurableTranscriptEntry[];
|
|
45
|
+
nextEntryId: number;
|
|
46
|
+
nextTurnId: number;
|
|
47
|
+
currentTurnId: number | null;
|
|
48
|
+
lastTurnId: number | null;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type ToolArtifactPhase = "start" | "update" | "end";
|
|
52
|
+
|
|
53
|
+
export type ToolArtifactWrite = {
|
|
54
|
+
toolCallId: string;
|
|
55
|
+
toolName: string;
|
|
56
|
+
phase: ToolArtifactPhase;
|
|
57
|
+
input?: unknown;
|
|
58
|
+
output?: unknown;
|
|
59
|
+
isError?: boolean;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type ToolArtifact = {
|
|
63
|
+
toolCallId: string;
|
|
64
|
+
toolName: string;
|
|
65
|
+
phase: ToolArtifactPhase;
|
|
66
|
+
isError: boolean;
|
|
67
|
+
input?: unknown;
|
|
68
|
+
output?: unknown;
|
|
69
|
+
details?: unknown;
|
|
70
|
+
diff?: string;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export type RestoredTranscript = {
|
|
74
|
+
snapshot: DurableTranscriptSnapshot;
|
|
75
|
+
/** Rebuilt from the persisted entries; maps are intentionally not serialized. */
|
|
76
|
+
toolCalls: Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }>;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
function safeSegment(value: string, fallback: string): string {
|
|
80
|
+
const normalized = value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
81
|
+
if (normalized === "." || normalized === "..") return fallback;
|
|
82
|
+
return normalized.slice(0, 96) || fallback;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function stableId(value: string): string {
|
|
86
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 16);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function jsonReplacer(_key: string, value: unknown): unknown {
|
|
90
|
+
if (typeof value === "bigint") return `${value}n`;
|
|
91
|
+
if (value instanceof Error) {
|
|
92
|
+
return { name: value.name, message: value.message, stack: value.stack };
|
|
93
|
+
}
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function stringifyJson(value: unknown): string {
|
|
98
|
+
try {
|
|
99
|
+
const serialized = JSON.stringify(value, jsonReplacer, 2);
|
|
100
|
+
return serialized === undefined ? "null" : serialized;
|
|
101
|
+
} catch {
|
|
102
|
+
return JSON.stringify(String(value), null, 2);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function writeJsonAtomic(filePath: string, value: unknown): void {
|
|
107
|
+
const temporaryPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
108
|
+
try {
|
|
109
|
+
writeFileSync(temporaryPath, `${stringifyJson(value)}\n`, "utf8");
|
|
110
|
+
renameSync(temporaryPath, filePath);
|
|
111
|
+
} catch {
|
|
112
|
+
// A best-effort fallback is preferable to losing the last tool result, but
|
|
113
|
+
// never leave a half-written temporary file to be mistaken for an artifact.
|
|
114
|
+
try {
|
|
115
|
+
writeFileSync(filePath, `${stringifyJson(value)}\n`, "utf8");
|
|
116
|
+
} finally {
|
|
117
|
+
try {
|
|
118
|
+
unlinkSync(temporaryPath);
|
|
119
|
+
} catch {
|
|
120
|
+
// Best effort cleanup only.
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function writeTextAtomic(filePath: string, value: string): void {
|
|
127
|
+
const temporaryPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
128
|
+
try {
|
|
129
|
+
writeFileSync(temporaryPath, value, "utf8");
|
|
130
|
+
renameSync(temporaryPath, filePath);
|
|
131
|
+
} catch {
|
|
132
|
+
try {
|
|
133
|
+
writeFileSync(filePath, value, "utf8");
|
|
134
|
+
} finally {
|
|
135
|
+
try {
|
|
136
|
+
unlinkSync(temporaryPath);
|
|
137
|
+
} catch {
|
|
138
|
+
// Best effort cleanup only.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function ensureProjectIgnore(projectDir: string): void {
|
|
145
|
+
const ignoreDir = path.join(projectDir, ".pi-subagents");
|
|
146
|
+
mkdirSync(ignoreDir, { recursive: true });
|
|
147
|
+
const ignorePath = path.join(ignoreDir, ".gitignore");
|
|
148
|
+
const existing = existsSync(ignorePath) ? readFileSync(ignorePath, "utf8") : "";
|
|
149
|
+
const rules = existing.split(/\r?\n/).map((line) => line.trim());
|
|
150
|
+
if (!rules.includes("*")) {
|
|
151
|
+
const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
|
|
152
|
+
appendFileSync(ignorePath, `${prefix}*\n`, "utf8");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
157
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function isFiniteInteger(value: unknown): value is number {
|
|
161
|
+
return typeof value === "number" && Number.isSafeInteger(value);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function validateEntry(value: unknown): DurableTranscriptEntry | null {
|
|
165
|
+
if (!isRecord(value) || !isFiniteInteger(value.id) || !isFiniteInteger(value.turnId)) return null;
|
|
166
|
+
const allowed = new Set([
|
|
167
|
+
"turn-boundary",
|
|
168
|
+
"user-message",
|
|
169
|
+
"thinking",
|
|
170
|
+
"assistant-text",
|
|
171
|
+
"tool-call",
|
|
172
|
+
"tool-result",
|
|
173
|
+
]);
|
|
174
|
+
if (typeof value.type !== "string" || !allowed.has(value.type)) return null;
|
|
175
|
+
if (value.type === "turn-boundary" && value.phase !== "start" && value.phase !== "end") return null;
|
|
176
|
+
const stringFields = ["text", "toolCallId", "toolName", "args", "content", "fullContent"];
|
|
177
|
+
for (const field of stringFields) {
|
|
178
|
+
if (value[field] !== undefined && typeof value[field] !== "string") return null;
|
|
179
|
+
}
|
|
180
|
+
if (value.truncated !== undefined && typeof value.truncated !== "boolean") return null;
|
|
181
|
+
if (value.isError !== undefined && typeof value.isError !== "boolean") return null;
|
|
182
|
+
if (value.streaming !== undefined && typeof value.streaming !== "boolean") return null;
|
|
183
|
+
|
|
184
|
+
// A current-schema snapshot is only useful when its entry can be rendered
|
|
185
|
+
// without inventing missing tool output. Reject the complete snapshot rather
|
|
186
|
+
// than manufacturing placeholders from corrupt persisted data.
|
|
187
|
+
if ((value.type === "user-message" || value.type === "thinking" || value.type === "assistant-text") && typeof value.text !== "string") return null;
|
|
188
|
+
if (value.type === "thinking" || value.type === "assistant-text") {
|
|
189
|
+
if (typeof value.streaming !== "boolean") return null;
|
|
190
|
+
}
|
|
191
|
+
if (value.type === "tool-call" &&
|
|
192
|
+
(typeof value.toolCallId !== "string" || typeof value.toolName !== "string" || typeof value.args !== "string")) return null;
|
|
193
|
+
if (value.type === "tool-result" &&
|
|
194
|
+
(typeof value.toolCallId !== "string" || typeof value.toolName !== "string" ||
|
|
195
|
+
typeof value.content !== "string" || typeof value.truncated !== "boolean" ||
|
|
196
|
+
typeof value.isError !== "boolean" || typeof value.streaming !== "boolean")) return null;
|
|
197
|
+
return value as unknown as DurableTranscriptEntry;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function validateSnapshot(value: unknown, expectedThreadId: string): DurableTranscriptSnapshot | null {
|
|
201
|
+
if (!isRecord(value)) return null;
|
|
202
|
+
if (value.schemaVersion !== BTW_TRANSCRIPT_SCHEMA_VERSION) return null;
|
|
203
|
+
if (value.threadId !== expectedThreadId || typeof value.recordId !== "string") return null;
|
|
204
|
+
if (!isFiniteInteger(value.timestamp) || (value.mode !== "contextual" && value.mode !== "tangent")) return null;
|
|
205
|
+
if (!Array.isArray(value.entries)) return null;
|
|
206
|
+
const entries = value.entries.map(validateEntry);
|
|
207
|
+
if (entries.some((entry) => entry === null)) return null;
|
|
208
|
+
const ids = new Set<number>();
|
|
209
|
+
for (const entry of entries) {
|
|
210
|
+
if (!entry || ids.has(entry.id)) return null;
|
|
211
|
+
ids.add(entry.id);
|
|
212
|
+
}
|
|
213
|
+
if (!isFiniteInteger(value.nextEntryId) || !isFiniteInteger(value.nextTurnId) ||
|
|
214
|
+
value.nextEntryId < 1 || value.nextTurnId < 1) return null;
|
|
215
|
+
if (ids.size > 0 && value.nextEntryId <= Math.max(...ids)) return null;
|
|
216
|
+
if (value.currentTurnId !== null && !isFiniteInteger(value.currentTurnId)) return null;
|
|
217
|
+
if (value.lastTurnId !== null && !isFiniteInteger(value.lastTurnId)) return null;
|
|
218
|
+
return {
|
|
219
|
+
schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
|
|
220
|
+
recordId: value.recordId,
|
|
221
|
+
threadId: expectedThreadId,
|
|
222
|
+
timestamp: value.timestamp,
|
|
223
|
+
mode: value.mode,
|
|
224
|
+
entries: entries as DurableTranscriptEntry[],
|
|
225
|
+
nextEntryId: value.nextEntryId,
|
|
226
|
+
nextTurnId: value.nextTurnId,
|
|
227
|
+
currentTurnId: value.currentTurnId as number | null,
|
|
228
|
+
lastTurnId: value.lastTurnId as number | null,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function rebuildToolCalls(entries: DurableTranscriptEntry[]): Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }> {
|
|
233
|
+
const toolCalls = new Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }>();
|
|
234
|
+
for (const entry of entries) {
|
|
235
|
+
if (entry.type === "tool-call" && entry.toolCallId) {
|
|
236
|
+
toolCalls.set(entry.toolCallId, { turnId: entry.turnId, callEntryId: entry.id });
|
|
237
|
+
} else if (entry.type === "tool-result" && entry.toolCallId) {
|
|
238
|
+
const current = toolCalls.get(entry.toolCallId) ?? {
|
|
239
|
+
turnId: entry.turnId,
|
|
240
|
+
callEntryId: entry.id,
|
|
241
|
+
};
|
|
242
|
+
current.resultEntryId = entry.id;
|
|
243
|
+
toolCalls.set(entry.toolCallId, current);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return toolCalls;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Project-local durable BTW store. The Pi session only stores small immutable
|
|
251
|
+
* locators; all potentially large tool payloads stay under .pi-subagents/btw.
|
|
252
|
+
*/
|
|
253
|
+
export class BtwTranscriptStore {
|
|
254
|
+
readonly threadId: string;
|
|
255
|
+
readonly threadDir: string;
|
|
256
|
+
readonly transcriptPath: string;
|
|
257
|
+
readonly toolsDir: string;
|
|
258
|
+
|
|
259
|
+
constructor(projectDir: string, sessionId: string) {
|
|
260
|
+
const normalizedProjectDir = path.resolve(projectDir || process.cwd());
|
|
261
|
+
ensureProjectIgnore(normalizedProjectDir);
|
|
262
|
+
this.threadId = safeSegment(sessionId, `session-${stableId(normalizedProjectDir)}`);
|
|
263
|
+
this.threadDir = path.join(normalizedProjectDir, ".pi-subagents", "btw", "threads", this.threadId);
|
|
264
|
+
this.transcriptPath = path.join(this.threadDir, "transcript.jsonl");
|
|
265
|
+
this.toolsDir = path.join(this.threadDir, "tools");
|
|
266
|
+
mkdirSync(this.toolsDir, { recursive: true });
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
appendSnapshot(snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">): DurableTranscriptSnapshot {
|
|
270
|
+
mkdirSync(this.threadDir, { recursive: true });
|
|
271
|
+
const recordId = `${Date.now().toString(36)}-${stableId(`${this.threadId}:${Date.now()}:${Math.random()}`)}`;
|
|
272
|
+
const persisted: DurableTranscriptSnapshot = {
|
|
273
|
+
schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
|
|
274
|
+
recordId,
|
|
275
|
+
threadId: this.threadId,
|
|
276
|
+
timestamp: Date.now(),
|
|
277
|
+
...snapshot,
|
|
278
|
+
};
|
|
279
|
+
// transcript.jsonl is line-delimited: keep each immutable snapshot on one
|
|
280
|
+
// physical line so a partial/corrupt record cannot hide later records.
|
|
281
|
+
appendFileSync(this.transcriptPath, `${JSON.stringify(persisted, jsonReplacer)}\n`, "utf8");
|
|
282
|
+
return persisted;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
readSnapshot(recordId?: string): RestoredTranscript | null {
|
|
286
|
+
if (!existsSync(this.transcriptPath)) return null;
|
|
287
|
+
let latest: DurableTranscriptSnapshot | null = null;
|
|
288
|
+
let content = "";
|
|
289
|
+
try {
|
|
290
|
+
content = readFileSync(this.transcriptPath, "utf8");
|
|
291
|
+
} catch {
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
for (const line of content.split(/\r?\n/)) {
|
|
295
|
+
if (!line.trim()) continue;
|
|
296
|
+
try {
|
|
297
|
+
const candidate = validateSnapshot(JSON.parse(line), this.threadId);
|
|
298
|
+
if (!candidate || (recordId && candidate.recordId !== recordId)) continue;
|
|
299
|
+
latest = candidate;
|
|
300
|
+
} catch {
|
|
301
|
+
// A corrupt line must not hide earlier valid snapshots.
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return latest ? { snapshot: latest, toolCalls: rebuildToolCalls(latest.entries) } : null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
writeToolArtifact(artifact: ToolArtifactWrite): void {
|
|
308
|
+
const toolDir = path.join(
|
|
309
|
+
this.toolsDir,
|
|
310
|
+
`${safeSegment(artifact.toolCallId, "tool")}-${stableId(artifact.toolCallId)}`,
|
|
311
|
+
);
|
|
312
|
+
mkdirSync(toolDir, { recursive: true });
|
|
313
|
+
const now = Date.now();
|
|
314
|
+
writeJsonAtomic(path.join(toolDir, "meta.json"), {
|
|
315
|
+
schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
|
|
316
|
+
toolCallId: artifact.toolCallId,
|
|
317
|
+
toolName: artifact.toolName,
|
|
318
|
+
phase: artifact.phase,
|
|
319
|
+
isError: artifact.isError ?? false,
|
|
320
|
+
updatedAt: now,
|
|
321
|
+
});
|
|
322
|
+
if (artifact.input !== undefined) writeJsonAtomic(path.join(toolDir, "input.json"), artifact.input);
|
|
323
|
+
if (artifact.output !== undefined) {
|
|
324
|
+
writeJsonAtomic(path.join(toolDir, "output.json"), artifact.output);
|
|
325
|
+
const details = isRecord(artifact.output) && artifact.output.details !== undefined
|
|
326
|
+
? artifact.output.details
|
|
327
|
+
: artifact.output;
|
|
328
|
+
writeJsonAtomic(path.join(toolDir, "details.json"), details);
|
|
329
|
+
const diff = findDiff(artifact.output);
|
|
330
|
+
const diffPath = path.join(toolDir, "diff.patch");
|
|
331
|
+
if (diff) {
|
|
332
|
+
writeTextAtomic(diffPath, `${diff.endsWith("\n") ? diff : `${diff}\n`}`);
|
|
333
|
+
} else if (existsSync(diffPath)) {
|
|
334
|
+
try {
|
|
335
|
+
unlinkSync(diffPath);
|
|
336
|
+
} catch {
|
|
337
|
+
// Best effort cleanup. A stale diff is never read as transcript data.
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
readToolArtifact(toolCallId: string): ToolArtifact | null {
|
|
344
|
+
const toolDir = path.join(
|
|
345
|
+
this.toolsDir,
|
|
346
|
+
`${safeSegment(toolCallId, "tool")}-${stableId(toolCallId)}`,
|
|
347
|
+
);
|
|
348
|
+
const metaPath = path.join(toolDir, "meta.json");
|
|
349
|
+
if (!existsSync(metaPath)) return null;
|
|
350
|
+
|
|
351
|
+
const readJson = (fileName: string): unknown | undefined => {
|
|
352
|
+
try {
|
|
353
|
+
return JSON.parse(readFileSync(path.join(toolDir, fileName), "utf8"));
|
|
354
|
+
} catch {
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const meta = readJson("meta.json");
|
|
359
|
+
if (!isRecord(meta) || meta.schemaVersion !== BTW_TRANSCRIPT_SCHEMA_VERSION ||
|
|
360
|
+
meta.toolCallId !== toolCallId || typeof meta.toolName !== "string" ||
|
|
361
|
+
(meta.phase !== "start" && meta.phase !== "update" && meta.phase !== "end")) {
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const artifact: ToolArtifact = {
|
|
366
|
+
toolCallId,
|
|
367
|
+
toolName: meta.toolName,
|
|
368
|
+
phase: meta.phase,
|
|
369
|
+
isError: meta.isError === true,
|
|
370
|
+
};
|
|
371
|
+
const input = readJson("input.json");
|
|
372
|
+
const output = readJson("output.json");
|
|
373
|
+
if (input !== undefined) artifact.input = input;
|
|
374
|
+
if (output !== undefined) {
|
|
375
|
+
artifact.output = output;
|
|
376
|
+
artifact.details = readJson("details.json");
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
const diff = readFileSync(path.join(toolDir, "diff.patch"), "utf8");
|
|
380
|
+
if (diff) artifact.diff = diff;
|
|
381
|
+
} catch {
|
|
382
|
+
// Diff is optional; absence is distinct from an empty diff.
|
|
383
|
+
}
|
|
384
|
+
return artifact;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function findDiff(value: unknown): string | null {
|
|
389
|
+
if (typeof value === "string") return null;
|
|
390
|
+
if (!isRecord(value)) return null;
|
|
391
|
+
for (const key of ["diff", "patch", "unifiedDiff", "diffPatch"]) {
|
|
392
|
+
if (typeof value[key] === "string") return value[key] as string;
|
|
393
|
+
}
|
|
394
|
+
if (value.details !== undefined) {
|
|
395
|
+
const nested = findDiff(value.details);
|
|
396
|
+
if (nested) return nested;
|
|
397
|
+
}
|
|
398
|
+
if (value.result !== undefined) return findDiff(value.result);
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export function makeTranscriptLocator(store: BtwTranscriptStore, snapshot: DurableTranscriptSnapshot): {
|
|
403
|
+
schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
|
|
404
|
+
threadId: string;
|
|
405
|
+
recordId: string;
|
|
406
|
+
} {
|
|
407
|
+
return {
|
|
408
|
+
schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
|
|
409
|
+
threadId: store.threadId,
|
|
410
|
+
recordId: snapshot.recordId,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function isTranscriptLocator(value: unknown): value is {
|
|
415
|
+
schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
|
|
416
|
+
threadId: string;
|
|
417
|
+
recordId: string;
|
|
418
|
+
} {
|
|
419
|
+
return isRecord(value) &&
|
|
420
|
+
value.schemaVersion === BTW_TRANSCRIPT_SCHEMA_VERSION &&
|
|
421
|
+
typeof value.threadId === "string" &&
|
|
422
|
+
typeof value.recordId === "string";
|
|
423
|
+
}
|
|
@@ -37,7 +37,7 @@ describe("BTW transcript message layout", () => {
|
|
|
37
37
|
{ id: 1, turnId: 1, type: "user-message", text: "Prompt" },
|
|
38
38
|
]);
|
|
39
39
|
|
|
40
|
-
expect(lines.slice(0, 2)).toEqual(["
|
|
40
|
+
expect(lines.slice(0, 2)).toEqual([" USER ", " Prompt"]);
|
|
41
41
|
});
|
|
42
42
|
|
|
43
43
|
it("keeps assistant heading and response on separate lines", () => {
|
|
@@ -45,7 +45,7 @@ describe("BTW transcript message layout", () => {
|
|
|
45
45
|
{ id: 1, turnId: 1, type: "assistant-text", text: "Response", streaming: false },
|
|
46
46
|
]);
|
|
47
47
|
|
|
48
|
-
expect(lines[0]).toBe("
|
|
48
|
+
expect(lines[0]).toBe(" ASSISTANT ");
|
|
49
49
|
expect(lines[1].startsWith(" Response")).toBe(true);
|
|
50
50
|
});
|
|
51
51
|
|
|
@@ -165,4 +165,262 @@ describe("BTW transcript message layout", () => {
|
|
|
165
165
|
expect(opened).toBe(1);
|
|
166
166
|
expect(component.getDraft()).toBe("draft prompt");
|
|
167
167
|
});
|
|
168
|
+
|
|
169
|
+
it("selects exactly one rendered block on an explicit normalized click", () => {
|
|
170
|
+
const component = new BtwOverlayComponent(
|
|
171
|
+
tui,
|
|
172
|
+
theme,
|
|
173
|
+
keybindings,
|
|
174
|
+
() => [
|
|
175
|
+
{ id: 1, turnId: 1, type: "user-message", text: "Prompt" },
|
|
176
|
+
{ id: 2, turnId: 1, type: "assistant-text", text: "Response", streaming: false },
|
|
177
|
+
] as any,
|
|
178
|
+
() => null,
|
|
179
|
+
() => "contextual",
|
|
180
|
+
() => {},
|
|
181
|
+
() => {},
|
|
182
|
+
() => {},
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
component.handleInput("\x10");
|
|
186
|
+
component.render(80);
|
|
187
|
+
const starts = (component as any).peekBlockStarts as number[];
|
|
188
|
+
const contentTop = (component as any).peekContentTop as number;
|
|
189
|
+
expect(starts).toHaveLength(2);
|
|
190
|
+
const before = (component as any).peekState.selectedIndex;
|
|
191
|
+
component.handleMouse({ action: "move", button: 0, x: 5, y: contentTop + starts[1] } as any);
|
|
192
|
+
expect((component as any).peekHoveredIndex).toBe(1);
|
|
193
|
+
expect((component as any).peekState.selectedIndex).toBe(before);
|
|
194
|
+
component.handleMouse({ action: "press", button: 0, x: 5, y: contentTop + starts[1] } as any);
|
|
195
|
+
component.handleMouse({ action: "release", button: 0, x: 5, y: contentTop + starts[1] } as any);
|
|
196
|
+
component.handleInput(`\x1b[<0;5;${contentTop + starts[1]}M`);
|
|
197
|
+
component.handleInput(`\x1b[<0;5;${contentTop + starts[1]}m`);
|
|
198
|
+
expect((component as any).peekState.selectedIndex).toBe(before);
|
|
199
|
+
component.handleMouse({ action: "click", button: 0, x: 5, y: contentTop + starts[1] } as any);
|
|
200
|
+
expect((component as any).peekState.selectedIndex).toBe(1);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("accepts the host TUI mouse shape and ignores separator clicks", () => {
|
|
204
|
+
const component = new BtwOverlayComponent(
|
|
205
|
+
tui,
|
|
206
|
+
theme,
|
|
207
|
+
keybindings,
|
|
208
|
+
() => [
|
|
209
|
+
{ id: 1, turnId: 1, type: "user-message", text: "Prompt" },
|
|
210
|
+
{ id: 2, turnId: 1, type: "assistant-text", text: "Response", streaming: false },
|
|
211
|
+
] as any,
|
|
212
|
+
() => null,
|
|
213
|
+
() => "contextual",
|
|
214
|
+
() => {},
|
|
215
|
+
() => {},
|
|
216
|
+
() => {},
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
component.handleInput("\x10");
|
|
220
|
+
component.render(80);
|
|
221
|
+
const starts = (component as any).peekBlockStarts as number[];
|
|
222
|
+
const ends = (component as any).peekBlockEnds as number[];
|
|
223
|
+
const contentTop = (component as any).peekContentTop as number;
|
|
224
|
+
component.handleMouse({
|
|
225
|
+
type: "click", button: "left", x: 5, y: contentTop + starts[1] - 1,
|
|
226
|
+
} as any);
|
|
227
|
+
expect((component as any).peekState.selectedIndex).toBe(1);
|
|
228
|
+
|
|
229
|
+
// The blank separator after the second block is not an interactive span.
|
|
230
|
+
const before = (component as any).peekState.selectedIndex;
|
|
231
|
+
component.handleMouse({
|
|
232
|
+
type: "click", button: "left", x: 5, y: contentTop + ends[1] - 1,
|
|
233
|
+
} as any);
|
|
234
|
+
expect((component as any).peekState.selectedIndex).toBe(before);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("handles a chat wheel event even before the first transcript render", () => {
|
|
238
|
+
const component = new BtwOverlayComponent(
|
|
239
|
+
tui,
|
|
240
|
+
theme,
|
|
241
|
+
keybindings,
|
|
242
|
+
() => [{
|
|
243
|
+
id: 1,
|
|
244
|
+
turnId: 1,
|
|
245
|
+
type: "assistant-text",
|
|
246
|
+
text: Array.from({ length: 50 }, (_, index) => `Response ${index}`).join("\n"),
|
|
247
|
+
streaming: false,
|
|
248
|
+
}] as any,
|
|
249
|
+
() => null,
|
|
250
|
+
() => "contextual",
|
|
251
|
+
() => {},
|
|
252
|
+
() => {},
|
|
253
|
+
() => {},
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
component.handleMouse({
|
|
257
|
+
type: "wheel", button: "none", x: 5, y: 4, wheelDelta: -1,
|
|
258
|
+
} as any);
|
|
259
|
+
|
|
260
|
+
expect((component as any).transcriptScrollOffset).toBeGreaterThan(0);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("handles the first wheel event immediately after opening a tool preview", () => {
|
|
264
|
+
const component = new BtwOverlayComponent(
|
|
265
|
+
tui,
|
|
266
|
+
theme,
|
|
267
|
+
keybindings,
|
|
268
|
+
() => [
|
|
269
|
+
{ id: 1, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "read", args: "src/index.ts" },
|
|
270
|
+
{ id: 2, turnId: 1, type: "tool-result", toolCallId: "call-1", toolName: "read", content: Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n"), isError: false, truncated: false, streaming: false },
|
|
271
|
+
] as any,
|
|
272
|
+
() => null,
|
|
273
|
+
() => "contextual",
|
|
274
|
+
() => {},
|
|
275
|
+
() => {},
|
|
276
|
+
() => {},
|
|
277
|
+
);
|
|
278
|
+
|
|
279
|
+
component.handleInput("\x10");
|
|
280
|
+
component.render(80);
|
|
281
|
+
component.handleInput("w");
|
|
282
|
+
component.handleMouse({ action: "wheel", button: 0, x: 5, y: 4, delta: 1 } as any);
|
|
283
|
+
|
|
284
|
+
expect((component as any).peekToolPreviewScrollOffset).toBeGreaterThan(0);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it("updates the single selected target while line scrolling across tool rows", () => {
|
|
288
|
+
const component = new BtwOverlayComponent(
|
|
289
|
+
tui,
|
|
290
|
+
theme,
|
|
291
|
+
keybindings,
|
|
292
|
+
() => [
|
|
293
|
+
{ id: 1, turnId: 1, type: "user-message", text: Array.from({ length: 40 }, (_, index) => `Prompt ${index}`).join("\n") },
|
|
294
|
+
{ id: 2, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "read", args: "src/index.ts" },
|
|
295
|
+
{ id: 3, turnId: 1, type: "tool-result", toolCallId: "call-1", toolName: "read", content: "done", isError: false, truncated: false, streaming: false },
|
|
296
|
+
{ id: 4, turnId: 1, type: "assistant-text", text: Array.from({ length: 40 }, (_, index) => `Response ${index}`).join("\n"), streaming: false },
|
|
297
|
+
] as any,
|
|
298
|
+
() => null,
|
|
299
|
+
() => "contextual",
|
|
300
|
+
() => {},
|
|
301
|
+
() => {},
|
|
302
|
+
() => {},
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
component.handleInput("\x10");
|
|
306
|
+
component.render(80);
|
|
307
|
+
const starts = (component as any).peekBlockStarts as number[];
|
|
308
|
+
for (let i = 0; i < starts[1]; i++) component.handleInput("j");
|
|
309
|
+
expect((component as any).peekState.selectedIndex).toBe(1);
|
|
310
|
+
component.handleInput("J");
|
|
311
|
+
expect((component as any).peekState.selectedIndex).toBe(3);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
it("opens and closes a bounded read-only tool preview without leaving Peek", () => {
|
|
315
|
+
const component = new BtwOverlayComponent(
|
|
316
|
+
tui,
|
|
317
|
+
theme,
|
|
318
|
+
keybindings,
|
|
319
|
+
() => [
|
|
320
|
+
{ id: 1, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "read", args: "src/index.ts" },
|
|
321
|
+
{ id: 2, turnId: 1, type: "tool-result", toolCallId: "call-1", toolName: "read", content: Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n"), isError: false, truncated: false, streaming: false },
|
|
322
|
+
] as any,
|
|
323
|
+
() => null,
|
|
324
|
+
() => "contextual",
|
|
325
|
+
() => {},
|
|
326
|
+
() => {},
|
|
327
|
+
() => {},
|
|
328
|
+
);
|
|
329
|
+
|
|
330
|
+
component.handleInput("\x10");
|
|
331
|
+
expect(component.render(80).join("\n")).toContain("w:preview");
|
|
332
|
+
component.handleInput("\r");
|
|
333
|
+
expect((component as any).expandedToolId).toBe(0);
|
|
334
|
+
component.render(80);
|
|
335
|
+
const starts = (component as any).peekBlockStarts as number[];
|
|
336
|
+
const contentTop = (component as any).peekContentTop as number;
|
|
337
|
+
component.handleMouse({
|
|
338
|
+
action: "click", button: 0, x: 5, y: contentTop + starts[0], clickCount: 2,
|
|
339
|
+
} as any);
|
|
340
|
+
expect((component as any).expandedToolId).toBeNull();
|
|
341
|
+
component.handleInput("w");
|
|
342
|
+
const preview = component.render(80).join("\n");
|
|
343
|
+
expect(preview).toContain("Input:");
|
|
344
|
+
expect(preview).toContain("Output");
|
|
345
|
+
component.handleInput("g");
|
|
346
|
+
const beforeWheel = (component as any).peekToolPreviewScrollOffset as number;
|
|
347
|
+
component.handleMouse({ action: "wheel", button: 0, x: 5, y: 4, delta: 1 } as any);
|
|
348
|
+
expect((component as any).peekToolPreviewScrollOffset).toBeGreaterThan(beforeWheel);
|
|
349
|
+
component.handleInput("G");
|
|
350
|
+
const previewState = (component as any).peekState;
|
|
351
|
+
const previewOffset = (component as any).peekToolPreviewScrollOffset as number;
|
|
352
|
+
expect(previewOffset).toBeLessThanOrEqual(
|
|
353
|
+
Math.max(0, ((component as any).peekToolPreviewLines as string[]).length - previewState.viewportHeight),
|
|
354
|
+
);
|
|
355
|
+
component.handleInput("j");
|
|
356
|
+
expect((component as any).peekToolPreviewScrollOffset).toBe(previewOffset);
|
|
357
|
+
component.handleInput("g");
|
|
358
|
+
expect((component as any).peekToolPreviewScrollOffset).toBe(0);
|
|
359
|
+
component.handleInput("q");
|
|
360
|
+
expect((component as any).peekState.active).toBe(true);
|
|
361
|
+
expect((component as any).peekToolPreviewIndex).toBeNull();
|
|
362
|
+
component.handleInput("q");
|
|
363
|
+
expect((component as any).peekState.active).toBe(false);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
it("keeps the rendered overlay within a short terminal height", () => {
|
|
367
|
+
const shortTui = { ...tui, terminal: { write: () => {}, rows: 10 } } as any;
|
|
368
|
+
const component = new BtwOverlayComponent(
|
|
369
|
+
shortTui,
|
|
370
|
+
theme,
|
|
371
|
+
keybindings,
|
|
372
|
+
() => [{ id: 1, turnId: 1, type: "assistant-text", text: "A\nB\nC", streaming: false }] as any,
|
|
373
|
+
() => null,
|
|
374
|
+
() => "contextual",
|
|
375
|
+
() => {},
|
|
376
|
+
() => {},
|
|
377
|
+
() => {},
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
expect(component.render(80)).toHaveLength(10);
|
|
381
|
+
component.handleInput("\x10");
|
|
382
|
+
expect(component.render(80)).toHaveLength(10);
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
it("keeps Enter and Escape composer behavior outside Peek", () => {
|
|
386
|
+
let submitted = "";
|
|
387
|
+
let dismissed = 0;
|
|
388
|
+
const composerKeybindings = {
|
|
389
|
+
matches: (data: string, action: string) => action === "app.interrupt" && data === "\x1b",
|
|
390
|
+
} as any;
|
|
391
|
+
const component = new BtwOverlayComponent(
|
|
392
|
+
tui,
|
|
393
|
+
theme,
|
|
394
|
+
composerKeybindings,
|
|
395
|
+
() => [],
|
|
396
|
+
() => null,
|
|
397
|
+
() => "contextual",
|
|
398
|
+
(value) => { submitted = value; },
|
|
399
|
+
() => { dismissed++; },
|
|
400
|
+
() => {},
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
component.focused = true;
|
|
404
|
+
component.setDraft("submit me");
|
|
405
|
+
component.handleInput("\r");
|
|
406
|
+
expect(submitted).toBe("submit me");
|
|
407
|
+
component.handleInput("\x1b");
|
|
408
|
+
expect(dismissed).toBe(1);
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
it("configures fd-backed completion for @ path suggestions", () => {
|
|
412
|
+
const component = new BtwOverlayComponent(
|
|
413
|
+
tui,
|
|
414
|
+
theme,
|
|
415
|
+
keybindings,
|
|
416
|
+
() => [],
|
|
417
|
+
() => null,
|
|
418
|
+
() => "contextual",
|
|
419
|
+
() => {},
|
|
420
|
+
() => {},
|
|
421
|
+
() => {},
|
|
422
|
+
);
|
|
423
|
+
|
|
424
|
+
expect((component as any).input.autocompleteProvider.fdPath).toBeTruthy();
|
|
425
|
+
});
|
|
168
426
|
});
|