@zhin.js/adapter-sandbox 1.1.20 → 1.1.22
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 +64 -0
- package/README.md +55 -7
- package/adapters/sandbox/index.js +3 -12
- package/adapters/sandbox/index.ts +2 -12
- package/lib/adapter.d.ts +17 -0
- package/lib/adapter.js +17 -0
- package/lib/client.d.ts +7 -14
- package/lib/client.js +12 -11
- package/lib/endpoint.d.ts +16 -13
- package/lib/endpoint.js +171 -138
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/protocol.d.ts +22 -1
- package/lib/protocol.js +34 -4
- package/package.json +17 -17
- package/pages/index/ConversationRecoveryPanel.js +131 -0
- package/pages/index/ConversationRecoveryPanel.tsx +134 -0
- package/pages/index/SandboxChat.js +319 -111
- package/pages/index/SandboxChat.tsx +356 -126
- package/pages/index/agentTrace.js +21 -10
- package/pages/index/agentTrace.ts +24 -10
- package/pages/index/conversationRecovery.js +40 -0
- package/pages/index/conversationRecovery.ts +68 -0
- package/pages/index/index.js +5 -5
- package/pages/index/index.tsx +5 -5
- package/pages/index/messages.js +24 -6
- package/pages/index/messages.ts +24 -6
- package/pages/index/playgroundState.js +51 -1
- package/pages/index/playgroundState.ts +61 -1
- package/pages/index/sandboxTransport.js +25 -0
- package/pages/index/sandboxTransport.ts +35 -0
- package/pages/index/useSandboxHistory.js +161 -0
- package/pages/index/useSandboxHistory.ts +164 -0
- package/pages/index/workspaceDirectory.js +49 -0
- package/pages/index/workspaceDirectory.ts +74 -0
- package/pages/index/workspaceDirectoryState.js +120 -0
- package/pages/index/workspaceDirectoryState.ts +124 -0
- package/src/adapter.ts +22 -0
- package/src/client.ts +16 -18
- package/src/endpoint.ts +179 -140
- package/src/index.ts +1 -1
- package/src/protocol.ts +59 -13
|
@@ -9,9 +9,9 @@ const traceCachePrefix = 'zhin.sandbox.agent-trace.v1:';
|
|
|
9
9
|
export function buildSandboxSessionKey(endpointId, scope, sceneId) {
|
|
10
10
|
return `sandbox:${endpointId || 'sandbox-bot'}:${scope}:${sceneId}`;
|
|
11
11
|
}
|
|
12
|
-
export function
|
|
12
|
+
export function agentSessionsPath(sessionKey) {
|
|
13
13
|
const params = new URLSearchParams({ sessionKey });
|
|
14
|
-
return `/agent/
|
|
14
|
+
return `/agent/sessions?${params}`;
|
|
15
15
|
}
|
|
16
16
|
export function mergeTraceSnapshot(previous, incoming) {
|
|
17
17
|
if (!previous || previous.sessionKey !== incoming.sessionKey)
|
|
@@ -58,7 +58,7 @@ export function saveCachedAgentTrace(snapshot, storage = browserTraceStorage())
|
|
|
58
58
|
try {
|
|
59
59
|
storage.setItem(`${traceCachePrefix}${snapshot.sessionKey}`, JSON.stringify({
|
|
60
60
|
...snapshot,
|
|
61
|
-
events: snapshot.events.slice(-300),
|
|
61
|
+
events: snapshot.events.slice(-300).map(event => ({ ...event, data: cacheTraceData(event.data) })),
|
|
62
62
|
activeTurnIds: snapshot.activeTurnIds.slice(-20),
|
|
63
63
|
}));
|
|
64
64
|
return true;
|
|
@@ -154,12 +154,16 @@ export function deriveWorkbenchArtifacts(snapshot, locale = 'zh-CN') {
|
|
|
154
154
|
recordedAt: event.recordedAt,
|
|
155
155
|
};
|
|
156
156
|
if (toolName === 'write_file' || toolName === 'edit_file') {
|
|
157
|
-
const
|
|
157
|
+
const settlement = outcome?.type === 'tool_result' ? outcome.data : undefined;
|
|
158
|
+
const filePath = stringValue(recordValue(settlement?.fileChange).path)
|
|
159
|
+
|| stringValue(args.file_path ?? args.path) || 'unknown file';
|
|
160
|
+
const projectFilePath = stringValue(recordValue(settlement?.projectFile).path);
|
|
158
161
|
return [{
|
|
159
162
|
...common,
|
|
160
163
|
kind: 'file-change',
|
|
161
164
|
title: toolName === 'write_file' ? sandboxText(locale, "写入文件") : sandboxText(locale, "编辑文件"),
|
|
162
165
|
path: filePath,
|
|
166
|
+
...(projectFilePath ? { projectFilePath } : {}),
|
|
163
167
|
detail: artifactOutputDetail(outcome),
|
|
164
168
|
diff: fileDiff(toolName, args, filePath),
|
|
165
169
|
}];
|
|
@@ -280,7 +284,8 @@ export function deriveAgentRunSteps(snapshot, run, locale = 'zh-CN') {
|
|
|
280
284
|
}
|
|
281
285
|
export function buildAgentRunReport(snapshot, context = {}, locale = 'zh-CN') {
|
|
282
286
|
const runs = deriveTaskRuns(snapshot);
|
|
283
|
-
const
|
|
287
|
+
const requestedRun = context.run;
|
|
288
|
+
const run = requestedRun ? runs.find((candidate) => candidate.id === runIdentityKey(requestedRun)) : runs[0];
|
|
284
289
|
const identity = run ?? context.run;
|
|
285
290
|
const turnId = identity?.turnId;
|
|
286
291
|
const steps = deriveAgentRunSteps(snapshot, identity, locale);
|
|
@@ -325,7 +330,7 @@ export function buildAgentRunReport(snapshot, context = {}, locale = 'zh-CN') {
|
|
|
325
330
|
lines.push('', ...markdownBlock('text', artifact.detail));
|
|
326
331
|
lines.push('');
|
|
327
332
|
});
|
|
328
|
-
lines.push('---', sandboxText(locale, "由 Zhin
|
|
333
|
+
lines.push('---', sandboxText(locale, "由 Zhin「会话」于 {0} 导出。", [new Date().toISOString()]));
|
|
329
334
|
return `${lines.join('\n').trim()}\n`;
|
|
330
335
|
}
|
|
331
336
|
export function presentTraceEvent(event, locale = 'zh-CN') {
|
|
@@ -334,7 +339,7 @@ export function presentTraceEvent(event, locale = 'zh-CN') {
|
|
|
334
339
|
switch (event.type) {
|
|
335
340
|
case 'turn_start': return { title: sandboxText(locale, "开始处理"), detail: shortTurn(event.turnId), tone: 'running' };
|
|
336
341
|
case 'capability_resolution': return { title: sandboxText(locale, "能力已解析"), detail: `${arrayLength(data.tools)} tools · ${arrayLength(data.skills)} skills`, tone: 'capability' };
|
|
337
|
-
case 'iteration_start': return { title: sandboxText(locale, "推理迭代 {0}", [String(data.iteration ?? '')]), detail: sandboxText(locale, "上限 {0}", [String(data.maxIterations
|
|
342
|
+
case 'iteration_start': return { title: sandboxText(locale, "推理迭代 {0}", [String(data.iteration ?? '')]), detail: data.maxIterations == null ? '' : sandboxText(locale, "上限 {0}", [String(data.maxIterations)]), tone: 'thinking' };
|
|
338
343
|
case 'thinking': return { title: sandboxText(locale, "模型思考"), detail: preview(data.text), tone: 'thinking' };
|
|
339
344
|
case 'tool_call': return { title: sandboxText(locale, "调用 {0}", [tool]), detail: preview(data.toolUseId), tone: 'tool' };
|
|
340
345
|
case 'tool_result': return { title: sandboxText(locale, "{0} 完成", [tool]), detail: duration(data.durationMs, locale), tone: 'success' };
|
|
@@ -353,14 +358,14 @@ export function presentTraceEvent(event, locale = 'zh-CN') {
|
|
|
353
358
|
default: return { title: event.type.replaceAll('_', ' '), detail: '', tone: 'muted' };
|
|
354
359
|
}
|
|
355
360
|
}
|
|
356
|
-
export async function fetchAgentTrace(sessionKey, afterSequence = 0, locale = 'zh-CN') {
|
|
361
|
+
export async function fetchAgentTrace(sessionKey, afterSequence = 0, locale = 'zh-CN', signal) {
|
|
357
362
|
const base = getSandboxApiBase() || window.location.origin;
|
|
358
363
|
const url = new URL('/api/agent/traces', `${base}/`);
|
|
359
364
|
url.searchParams.set('sessionKey', sessionKey);
|
|
360
365
|
url.searchParams.set('limit', '300');
|
|
361
366
|
if (afterSequence > 0)
|
|
362
367
|
url.searchParams.set('after', String(afterSequence));
|
|
363
|
-
const response = await fetch(url, { headers: getSandboxAuthHeaders() });
|
|
368
|
+
const response = await fetch(url, { headers: getSandboxAuthHeaders(), signal });
|
|
364
369
|
const body = await response.json().catch(() => ({}));
|
|
365
370
|
if (!response.ok || body.success === false || !body.data) {
|
|
366
371
|
throw new Error(response.status === 503
|
|
@@ -548,9 +553,15 @@ function parseCachedTraceEvent(value) {
|
|
|
548
553
|
sessionKey: item.sessionKey,
|
|
549
554
|
turnId: item.turnId,
|
|
550
555
|
type: item.type,
|
|
551
|
-
data: item.data,
|
|
556
|
+
data: cacheTraceData(item.data),
|
|
552
557
|
};
|
|
553
558
|
}
|
|
559
|
+
function cacheTraceData(data) {
|
|
560
|
+
const cached = { ...data };
|
|
561
|
+
// Project-file links are granted by the current Host API, not Hostless cache.
|
|
562
|
+
delete cached.projectFile;
|
|
563
|
+
return cached;
|
|
564
|
+
}
|
|
554
565
|
function nonNegativeNumber(value) {
|
|
555
566
|
const number = Number(value);
|
|
556
567
|
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
|
|
@@ -61,6 +61,8 @@ export interface WorkbenchArtifact {
|
|
|
61
61
|
readonly kind: 'file-change' | 'test' | 'command';
|
|
62
62
|
readonly title: string;
|
|
63
63
|
readonly path?: string;
|
|
64
|
+
/** Current Host projection into its existing project-file authority. */
|
|
65
|
+
readonly projectFilePath?: string;
|
|
64
66
|
readonly status: 'running' | 'completed' | 'failed' | 'denied' | 'cancelled';
|
|
65
67
|
readonly detail?: string;
|
|
66
68
|
readonly diff?: string;
|
|
@@ -99,9 +101,9 @@ export function buildSandboxSessionKey(endpointId: string, scope: SandboxScope,
|
|
|
99
101
|
return `sandbox:${endpointId || 'sandbox-bot'}:${scope}:${sceneId}`;
|
|
100
102
|
}
|
|
101
103
|
|
|
102
|
-
export function
|
|
104
|
+
export function agentSessionsPath(sessionKey: string): string {
|
|
103
105
|
const params = new URLSearchParams({ sessionKey });
|
|
104
|
-
return `/agent/
|
|
106
|
+
return `/agent/sessions?${params}`;
|
|
105
107
|
}
|
|
106
108
|
|
|
107
109
|
export function mergeTraceSnapshot(
|
|
@@ -156,7 +158,7 @@ export function saveCachedAgentTrace(
|
|
|
156
158
|
try {
|
|
157
159
|
storage.setItem(`${traceCachePrefix}${snapshot.sessionKey}`, JSON.stringify({
|
|
158
160
|
...snapshot,
|
|
159
|
-
events: snapshot.events.slice(-300),
|
|
161
|
+
events: snapshot.events.slice(-300).map(event => ({ ...event, data: cacheTraceData(event.data) })),
|
|
160
162
|
activeTurnIds: snapshot.activeTurnIds.slice(-20),
|
|
161
163
|
}));
|
|
162
164
|
return true;
|
|
@@ -248,12 +250,16 @@ export function deriveWorkbenchArtifacts(snapshot: AgentTraceSnapshot | null, lo
|
|
|
248
250
|
recordedAt: event.recordedAt,
|
|
249
251
|
} as const;
|
|
250
252
|
if (toolName === 'write_file' || toolName === 'edit_file') {
|
|
251
|
-
const
|
|
253
|
+
const settlement = outcome?.type === 'tool_result' ? outcome.data : undefined;
|
|
254
|
+
const filePath = stringValue(recordValue(settlement?.fileChange).path)
|
|
255
|
+
|| stringValue(args.file_path ?? args.path) || 'unknown file';
|
|
256
|
+
const projectFilePath = stringValue(recordValue(settlement?.projectFile).path);
|
|
252
257
|
return [{
|
|
253
258
|
...common,
|
|
254
259
|
kind: 'file-change',
|
|
255
260
|
title: toolName === 'write_file' ? sandboxText(locale, "写入文件") : sandboxText(locale, "编辑文件"),
|
|
256
261
|
path: filePath,
|
|
262
|
+
...(projectFilePath ? { projectFilePath } : {}),
|
|
257
263
|
detail: artifactOutputDetail(outcome),
|
|
258
264
|
diff: fileDiff(toolName, args, filePath),
|
|
259
265
|
}];
|
|
@@ -366,7 +372,8 @@ export function deriveAgentRunSteps(snapshot: AgentTraceSnapshot | null, run: Ag
|
|
|
366
372
|
|
|
367
373
|
export function buildAgentRunReport(snapshot: AgentTraceSnapshot | null, context: AgentRunReportContext = {}, locale: SandboxLocale = 'zh-CN'): string {
|
|
368
374
|
const runs = deriveTaskRuns(snapshot);
|
|
369
|
-
const
|
|
375
|
+
const requestedRun = context.run;
|
|
376
|
+
const run = requestedRun ? runs.find((candidate) => candidate.id === runIdentityKey(requestedRun)) : runs[0];
|
|
370
377
|
const identity = run ?? context.run;
|
|
371
378
|
const turnId = identity?.turnId;
|
|
372
379
|
const steps = deriveAgentRunSteps(snapshot, identity, locale);
|
|
@@ -406,7 +413,7 @@ export function buildAgentRunReport(snapshot: AgentTraceSnapshot | null, context
|
|
|
406
413
|
lines.push('');
|
|
407
414
|
});
|
|
408
415
|
|
|
409
|
-
lines.push('---', sandboxText(locale, "由 Zhin
|
|
416
|
+
lines.push('---', sandboxText(locale, "由 Zhin「会话」于 {0} 导出。", [new Date().toISOString()]));
|
|
410
417
|
return `${lines.join('\n').trim()}\n`;
|
|
411
418
|
}
|
|
412
419
|
|
|
@@ -416,7 +423,7 @@ export function presentTraceEvent(event: AgentTraceEvent, locale: SandboxLocale
|
|
|
416
423
|
switch (event.type) {
|
|
417
424
|
case 'turn_start': return { title: sandboxText(locale, "开始处理"), detail: shortTurn(event.turnId), tone: 'running' };
|
|
418
425
|
case 'capability_resolution': return { title: sandboxText(locale, "能力已解析"), detail: `${arrayLength(data.tools)} tools · ${arrayLength(data.skills)} skills`, tone: 'capability' };
|
|
419
|
-
case 'iteration_start': return { title: sandboxText(locale, "推理迭代 {0}", [String(data.iteration ?? '')]), detail: sandboxText(locale, "上限 {0}", [String(data.maxIterations
|
|
426
|
+
case 'iteration_start': return { title: sandboxText(locale, "推理迭代 {0}", [String(data.iteration ?? '')]), detail: data.maxIterations == null ? '' : sandboxText(locale, "上限 {0}", [String(data.maxIterations)]), tone: 'thinking' };
|
|
420
427
|
case 'thinking': return { title: sandboxText(locale, "模型思考"), detail: preview(data.text), tone: 'thinking' };
|
|
421
428
|
case 'tool_call': return { title: sandboxText(locale, "调用 {0}", [tool]), detail: preview(data.toolUseId), tone: 'tool' };
|
|
422
429
|
case 'tool_result': return { title: sandboxText(locale, "{0} 完成", [tool]), detail: duration(data.durationMs, locale), tone: 'success' };
|
|
@@ -436,13 +443,13 @@ export function presentTraceEvent(event: AgentTraceEvent, locale: SandboxLocale
|
|
|
436
443
|
}
|
|
437
444
|
}
|
|
438
445
|
|
|
439
|
-
export async function fetchAgentTrace(sessionKey: string, afterSequence = 0, locale: SandboxLocale = 'zh-CN'): Promise<AgentTraceSnapshot> {
|
|
446
|
+
export async function fetchAgentTrace(sessionKey: string, afterSequence = 0, locale: SandboxLocale = 'zh-CN', signal?: AbortSignal): Promise<AgentTraceSnapshot> {
|
|
440
447
|
const base = getSandboxApiBase() || window.location.origin;
|
|
441
448
|
const url = new URL('/api/agent/traces', `${base}/`);
|
|
442
449
|
url.searchParams.set('sessionKey', sessionKey);
|
|
443
450
|
url.searchParams.set('limit', '300');
|
|
444
451
|
if (afterSequence > 0) url.searchParams.set('after', String(afterSequence));
|
|
445
|
-
const response = await fetch(url, { headers: getSandboxAuthHeaders() });
|
|
452
|
+
const response = await fetch(url, { headers: getSandboxAuthHeaders(), signal });
|
|
446
453
|
const body = await response.json().catch(() => ({})) as { success?: boolean; data?: AgentTraceSnapshot; error?: string };
|
|
447
454
|
if (!response.ok || body.success === false || !body.data) {
|
|
448
455
|
throw new Error(response.status === 503
|
|
@@ -633,10 +640,17 @@ function parseCachedTraceEvent(value: unknown): AgentTraceEvent | undefined {
|
|
|
633
640
|
sessionKey: item.sessionKey,
|
|
634
641
|
turnId: item.turnId,
|
|
635
642
|
type: item.type,
|
|
636
|
-
data: item.data as Record<string, unknown
|
|
643
|
+
data: cacheTraceData(item.data as Record<string, unknown>),
|
|
637
644
|
};
|
|
638
645
|
}
|
|
639
646
|
|
|
647
|
+
function cacheTraceData(data: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
|
648
|
+
const cached = { ...data };
|
|
649
|
+
// Project-file links are granted by the current Host API, not Hostless cache.
|
|
650
|
+
delete cached.projectFile;
|
|
651
|
+
return cached;
|
|
652
|
+
}
|
|
653
|
+
|
|
640
654
|
function nonNegativeNumber(value: unknown): number {
|
|
641
655
|
const number = Number(value);
|
|
642
656
|
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Generated by build-plugin-runtime-entries.mjs. Do not edit.
|
|
2
|
+
import { captureSandboxRequestContext } from './sandboxTransport.js';
|
|
3
|
+
/** Read-only recovery never sends a message, answers a prompt, or retries execution. */
|
|
4
|
+
async function readRecovery(path, connectionId, sessionKey, signal, cursor, context = captureSandboxRequestContext()) {
|
|
5
|
+
const url = new URL(path, `${context.apiBase || window.location.origin}/`);
|
|
6
|
+
url.searchParams.set('connectionId', connectionId);
|
|
7
|
+
url.searchParams.set('sessionKey', sessionKey);
|
|
8
|
+
if (cursor)
|
|
9
|
+
url.searchParams.set('cursor', cursor);
|
|
10
|
+
const response = await fetch(url, { headers: context.headers, cache: 'no-store', signal });
|
|
11
|
+
if (response.status === 404 || response.status === 405)
|
|
12
|
+
return null;
|
|
13
|
+
const body = await response.json();
|
|
14
|
+
if (!response.ok || !body.success || !body.data)
|
|
15
|
+
throw new Error(body.error || `Conversation recovery failed (${response.status})`);
|
|
16
|
+
return body.data;
|
|
17
|
+
}
|
|
18
|
+
export function readPendingInteractions(connectionId, sessionKey, signal, context) {
|
|
19
|
+
return readRecovery('/api/interactions/pending', connectionId, sessionKey, signal, undefined, context);
|
|
20
|
+
}
|
|
21
|
+
export function readConversationResults(connectionId, sessionKey, signal, cursor, context) {
|
|
22
|
+
return readRecovery('/api/conversations/results', connectionId, sessionKey, signal, cursor, context);
|
|
23
|
+
}
|
|
24
|
+
export function resultDeliveryStatus(result) {
|
|
25
|
+
const statuses = result.deliveries.map(delivery => delivery.status);
|
|
26
|
+
if (!statuses.length || statuses.includes('unknown') || result.deliveries.some(delivery => delivery.deliveryUnknown))
|
|
27
|
+
return 'unknown';
|
|
28
|
+
if (statuses.includes('partial') || statuses.includes('sent') && statuses.includes('not_sent'))
|
|
29
|
+
return 'partial';
|
|
30
|
+
return statuses.every(status => status === 'sent') ? 'sent' : 'not_sent';
|
|
31
|
+
}
|
|
32
|
+
export function prependResultPage(previous, earlier) {
|
|
33
|
+
if (previous.sessionKey !== earlier.sessionKey)
|
|
34
|
+
throw new Error('Result page belongs to another conversation');
|
|
35
|
+
const rows = new Map(previous.results.map(result => [result.turnId, result]));
|
|
36
|
+
for (const result of earlier.results)
|
|
37
|
+
if (!rows.has(result.turnId))
|
|
38
|
+
rows.set(result.turnId, result);
|
|
39
|
+
return { ...earlier, results: [...rows.values()].sort((a, b) => a.completedAt - b.completedAt || a.turnId.localeCompare(b.turnId)) };
|
|
40
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { MessageSegment } from '@zhin.js/client';
|
|
2
|
+
import { captureSandboxRequestContext, type SandboxRequestContext } from './sandboxTransport.js';
|
|
3
|
+
|
|
4
|
+
export interface PendingInteraction {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly generation: number;
|
|
7
|
+
readonly subjectId: string;
|
|
8
|
+
readonly expiresAt: number;
|
|
9
|
+
readonly segments: MessageSegment[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RecoveredDelivery {
|
|
13
|
+
readonly status: 'sent' | 'not_sent' | 'unknown' | 'partial';
|
|
14
|
+
readonly deliveryUnknown?: true;
|
|
15
|
+
readonly recordedAt: number;
|
|
16
|
+
readonly messages: readonly (Readonly<{ id: string }> | null)[];
|
|
17
|
+
readonly resources: readonly Readonly<{ type: string; url: string }>[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RecoveredResult {
|
|
21
|
+
readonly turnId: string;
|
|
22
|
+
readonly completedAt: number;
|
|
23
|
+
readonly message: string;
|
|
24
|
+
readonly deliveries: readonly RecoveredDelivery[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RecoveredResultPage {
|
|
28
|
+
readonly sessionKey: string;
|
|
29
|
+
readonly results: readonly RecoveredResult[];
|
|
30
|
+
readonly hasMore: boolean;
|
|
31
|
+
readonly nextCursor: string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Read-only recovery never sends a message, answers a prompt, or retries execution. */
|
|
35
|
+
async function readRecovery<T>(path: string, connectionId: string, sessionKey: string, signal?: AbortSignal, cursor?: string,
|
|
36
|
+
context: SandboxRequestContext = captureSandboxRequestContext()): Promise<T | null> {
|
|
37
|
+
const url = new URL(path, `${context.apiBase || window.location.origin}/`);
|
|
38
|
+
url.searchParams.set('connectionId', connectionId);
|
|
39
|
+
url.searchParams.set('sessionKey', sessionKey);
|
|
40
|
+
if (cursor) url.searchParams.set('cursor', cursor);
|
|
41
|
+
const response = await fetch(url, { headers: context.headers, cache: 'no-store', signal });
|
|
42
|
+
if (response.status === 404 || response.status === 405) return null;
|
|
43
|
+
const body = await response.json() as { success?: boolean; data?: T; error?: string };
|
|
44
|
+
if (!response.ok || !body.success || !body.data) throw new Error(body.error || `Conversation recovery failed (${response.status})`);
|
|
45
|
+
return body.data;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function readPendingInteractions(connectionId: string, sessionKey: string, signal?: AbortSignal, context?: SandboxRequestContext) {
|
|
49
|
+
return readRecovery<{ generation: number; pending: readonly PendingInteraction[] }>('/api/interactions/pending', connectionId, sessionKey, signal, undefined, context);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function readConversationResults(connectionId: string, sessionKey: string, signal?: AbortSignal, cursor?: string, context?: SandboxRequestContext) {
|
|
53
|
+
return readRecovery<RecoveredResultPage>('/api/conversations/results', connectionId, sessionKey, signal, cursor, context);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function resultDeliveryStatus(result: RecoveredResult): RecoveredDelivery['status'] {
|
|
57
|
+
const statuses = result.deliveries.map(delivery => delivery.status);
|
|
58
|
+
if (!statuses.length || statuses.includes('unknown') || result.deliveries.some(delivery => delivery.deliveryUnknown)) return 'unknown';
|
|
59
|
+
if (statuses.includes('partial') || statuses.includes('sent') && statuses.includes('not_sent')) return 'partial';
|
|
60
|
+
return statuses.every(status => status === 'sent') ? 'sent' : 'not_sent';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function prependResultPage(previous: RecoveredResultPage, earlier: RecoveredResultPage): RecoveredResultPage {
|
|
64
|
+
if (previous.sessionKey !== earlier.sessionKey) throw new Error('Result page belongs to another conversation');
|
|
65
|
+
const rows = new Map(previous.results.map(result => [result.turnId, result]));
|
|
66
|
+
for (const result of earlier.results) if (!rows.has(result.turnId)) rows.set(result.turnId, result);
|
|
67
|
+
return { ...earlier, results: [...rows.values()].sort((a, b) => a.completedAt - b.completedAt || a.turnId.localeCompare(b.turnId)) };
|
|
68
|
+
}
|
package/pages/index/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Generated by build-plugin-runtime-entries.mjs. Do not edit.
|
|
2
2
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
3
|
import { definePage } from '@zhin.js/console-contract';
|
|
4
|
-
import SandboxChat from './SandboxChat';
|
|
4
|
+
import SandboxChat, {} from './SandboxChat';
|
|
5
5
|
export const meta = definePage({
|
|
6
|
-
title: '
|
|
7
|
-
titleI18n: { en: '
|
|
6
|
+
title: '会话',
|
|
7
|
+
titleI18n: { en: 'Conversations' },
|
|
8
8
|
icon: 'Box',
|
|
9
9
|
order: 10,
|
|
10
10
|
});
|
|
@@ -14,6 +14,6 @@ export const meta = definePage({
|
|
|
14
14
|
* Agent workbench for testing scoped conversations, rich messages and execution traces.
|
|
15
15
|
* WebSocket targets Host `/sandbox` via zhin_api_base + token (see sandboxTransport.ts).
|
|
16
16
|
*/
|
|
17
|
-
export default function SandboxPage() {
|
|
18
|
-
return _jsx(SandboxChat, {});
|
|
17
|
+
export default function SandboxPage(props) {
|
|
18
|
+
return _jsx(SandboxChat, { ...props });
|
|
19
19
|
}
|
package/pages/index/index.tsx
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { definePage } from '@zhin.js/console-contract';
|
|
2
|
-
import SandboxChat from './SandboxChat';
|
|
2
|
+
import SandboxChat, { type SandboxPageProps } from './SandboxChat';
|
|
3
3
|
|
|
4
4
|
export const meta = definePage({
|
|
5
|
-
title: '
|
|
6
|
-
titleI18n: { en: '
|
|
5
|
+
title: '会话',
|
|
6
|
+
titleI18n: { en: 'Conversations' },
|
|
7
7
|
icon: 'Box',
|
|
8
8
|
order: 10,
|
|
9
9
|
});
|
|
@@ -14,6 +14,6 @@ export const meta = definePage({
|
|
|
14
14
|
* Agent workbench for testing scoped conversations, rich messages and execution traces.
|
|
15
15
|
* WebSocket targets Host `/sandbox` via zhin_api_base + token (see sandboxTransport.ts).
|
|
16
16
|
*/
|
|
17
|
-
export default function SandboxPage() {
|
|
18
|
-
return <SandboxChat />;
|
|
17
|
+
export default function SandboxPage(props: SandboxPageProps) {
|
|
18
|
+
return <SandboxChat {...props} />;
|
|
19
19
|
}
|
package/pages/index/messages.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
// Generated by build-plugin-runtime-entries.mjs. Do not edit.
|
|
2
2
|
/** Authored interface copy only; unknown/user text is returned unchanged. */
|
|
3
3
|
export const sandboxEnglish = {
|
|
4
|
+
"刷新会话目录": "Refresh conversations",
|
|
5
|
+
"正在读取会话目录": "Loading conversations",
|
|
6
|
+
"Host 会话目录": "Host conversations",
|
|
7
|
+
"会话目录": "Conversations",
|
|
8
|
+
"重新读取": "Reload",
|
|
4
9
|
"当前用户": "Current user",
|
|
10
|
+
"Sandbox 连接尚未就绪,会话切换未发送。": "Sandbox is not connected. The conversation switch was not sent.",
|
|
11
|
+
"Sandbox 连接尚未就绪,消息未发送。": "Sandbox is not connected. Your message was not sent.",
|
|
5
12
|
"审阅者": "Reviewer",
|
|
6
13
|
"协作者": "Collaborator",
|
|
7
14
|
"当前 Token 只有演示权限,任务运行已禁用。": "This token has demo access only. Task execution is disabled.",
|
|
@@ -22,6 +29,8 @@ export const sandboxEnglish = {
|
|
|
22
29
|
"[音频无地址]": "[Audio URL missing]",
|
|
23
30
|
"↩ 引用消息 #": "↩ Quoted message #",
|
|
24
31
|
"聊天记录": "Chat history",
|
|
32
|
+
"消息已撤回": "Message recalled",
|
|
33
|
+
"消息正文未保存": "Message body was not stored",
|
|
25
34
|
"…共": "…total",
|
|
26
35
|
"条": "messages",
|
|
27
36
|
"[合并转发]": "[Forwarded messages]",
|
|
@@ -31,7 +40,7 @@ export const sandboxEnglish = {
|
|
|
31
40
|
"单用户": "Single user",
|
|
32
41
|
"群组上下文": "Group context",
|
|
33
42
|
"频道上下文": "Channel context",
|
|
34
|
-
"
|
|
43
|
+
"停止请求已提交。": "Stop request submitted.",
|
|
35
44
|
"当前会话没有运行中的任务。": "No running task in this conversation.",
|
|
36
45
|
"无法停止任务": "Could not stop the task",
|
|
37
46
|
"停止中": "Stopping",
|
|
@@ -49,8 +58,8 @@ export const sandboxEnglish = {
|
|
|
49
58
|
"查看 {0} 个步骤": "View {0} steps",
|
|
50
59
|
"{0} 个变更与产物": "{0} changes and artifacts",
|
|
51
60
|
"打开运行检查器": "Open run inspector",
|
|
52
|
-
"
|
|
53
|
-
"
|
|
61
|
+
"会话列表": "Conversation list",
|
|
62
|
+
"会话": "Conversations",
|
|
54
63
|
"检查器": "Inspector",
|
|
55
64
|
"Sandbox WebSocket 已连接": "Sandbox WebSocket connected",
|
|
56
65
|
"正在重连 Sandbox WebSocket": "Reconnecting Sandbox WebSocket",
|
|
@@ -63,7 +72,7 @@ export const sandboxEnglish = {
|
|
|
63
72
|
"频道": "Channel",
|
|
64
73
|
"取消": "Cancel",
|
|
65
74
|
"创建": "Create",
|
|
66
|
-
"
|
|
75
|
+
"新建会话": "New conversation",
|
|
67
76
|
"会话已持久化": "Conversation saved",
|
|
68
77
|
"会话保存失败": "Could not save conversation",
|
|
69
78
|
"{0} 条消息": "{0} messages",
|
|
@@ -149,7 +158,16 @@ export const sandboxEnglish = {
|
|
|
149
158
|
"暂无输出": "No output yet",
|
|
150
159
|
"等待结果": "Waiting for a result",
|
|
151
160
|
"Agent 修改文件、执行命令或测试后,产物会集中出现在这里": "Artifacts appear here when the Agent modifies files, runs commands or executes tests",
|
|
152
|
-
"
|
|
161
|
+
"对话与轨迹": "Conversation and trace",
|
|
162
|
+
"返回会话": "Back to conversation",
|
|
163
|
+
"打开当前文件": "Open current file",
|
|
164
|
+
"待处理操作": "Pending interaction",
|
|
165
|
+
"加载更早结果": "Load earlier results",
|
|
166
|
+
"加载更早记录": "Load earlier messages",
|
|
167
|
+
"已完成,未投递": "Completed, not delivered",
|
|
168
|
+
"已完成,部分内容未投递": "Completed, partly delivered",
|
|
169
|
+
"已完成,投递结果未知": "Completed, delivery unknown",
|
|
170
|
+
"已撤回": "Recalled",
|
|
153
171
|
"Agent 运行中": "Agent is running",
|
|
154
172
|
"最近任务已完成": "Latest task completed",
|
|
155
173
|
"最近任务失败": "Latest task failed",
|
|
@@ -200,7 +218,7 @@ export const sandboxEnglish = {
|
|
|
200
218
|
"- 状态:{0}": "- Status: {0}",
|
|
201
219
|
"- 路径:{0}": "- Path: {0}",
|
|
202
220
|
"- 耗时:{0} ms": "- Duration: {0} ms",
|
|
203
|
-
"由 Zhin
|
|
221
|
+
"由 Zhin「会话」于 {0} 导出。": "Exported from Zhin Conversations at {0}.",
|
|
204
222
|
"开始处理": "Start processing",
|
|
205
223
|
"能力已解析": "Capabilities resolved",
|
|
206
224
|
"模型思考": "Model reasoning",
|
package/pages/index/messages.ts
CHANGED
|
@@ -2,7 +2,14 @@ export type SandboxLocale = 'zh-CN' | 'en';
|
|
|
2
2
|
|
|
3
3
|
/** Authored interface copy only; unknown/user text is returned unchanged. */
|
|
4
4
|
export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
5
|
+
"刷新会话目录": "Refresh conversations",
|
|
6
|
+
"正在读取会话目录": "Loading conversations",
|
|
7
|
+
"Host 会话目录": "Host conversations",
|
|
8
|
+
"会话目录": "Conversations",
|
|
9
|
+
"重新读取": "Reload",
|
|
5
10
|
"当前用户": "Current user",
|
|
11
|
+
"Sandbox 连接尚未就绪,会话切换未发送。": "Sandbox is not connected. The conversation switch was not sent.",
|
|
12
|
+
"Sandbox 连接尚未就绪,消息未发送。": "Sandbox is not connected. Your message was not sent.",
|
|
6
13
|
"审阅者": "Reviewer",
|
|
7
14
|
"协作者": "Collaborator",
|
|
8
15
|
"当前 Token 只有演示权限,任务运行已禁用。": "This token has demo access only. Task execution is disabled.",
|
|
@@ -23,6 +30,8 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
23
30
|
"[音频无地址]": "[Audio URL missing]",
|
|
24
31
|
"↩ 引用消息 #": "↩ Quoted message #",
|
|
25
32
|
"聊天记录": "Chat history",
|
|
33
|
+
"消息已撤回": "Message recalled",
|
|
34
|
+
"消息正文未保存": "Message body was not stored",
|
|
26
35
|
"…共": "…total",
|
|
27
36
|
"条": "messages",
|
|
28
37
|
"[合并转发]": "[Forwarded messages]",
|
|
@@ -32,7 +41,7 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
32
41
|
"单用户": "Single user",
|
|
33
42
|
"群组上下文": "Group context",
|
|
34
43
|
"频道上下文": "Channel context",
|
|
35
|
-
"
|
|
44
|
+
"停止请求已提交。": "Stop request submitted.",
|
|
36
45
|
"当前会话没有运行中的任务。": "No running task in this conversation.",
|
|
37
46
|
"无法停止任务": "Could not stop the task",
|
|
38
47
|
"停止中": "Stopping",
|
|
@@ -50,8 +59,8 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
50
59
|
"查看 {0} 个步骤": "View {0} steps",
|
|
51
60
|
"{0} 个变更与产物": "{0} changes and artifacts",
|
|
52
61
|
"打开运行检查器": "Open run inspector",
|
|
53
|
-
"
|
|
54
|
-
"
|
|
62
|
+
"会话列表": "Conversation list",
|
|
63
|
+
"会话": "Conversations",
|
|
55
64
|
"检查器": "Inspector",
|
|
56
65
|
"Sandbox WebSocket 已连接": "Sandbox WebSocket connected",
|
|
57
66
|
"正在重连 Sandbox WebSocket": "Reconnecting Sandbox WebSocket",
|
|
@@ -64,7 +73,7 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
64
73
|
"频道": "Channel",
|
|
65
74
|
"取消": "Cancel",
|
|
66
75
|
"创建": "Create",
|
|
67
|
-
"
|
|
76
|
+
"新建会话": "New conversation",
|
|
68
77
|
"会话已持久化": "Conversation saved",
|
|
69
78
|
"会话保存失败": "Could not save conversation",
|
|
70
79
|
"{0} 条消息": "{0} messages",
|
|
@@ -150,7 +159,16 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
150
159
|
"暂无输出": "No output yet",
|
|
151
160
|
"等待结果": "Waiting for a result",
|
|
152
161
|
"Agent 修改文件、执行命令或测试后,产物会集中出现在这里": "Artifacts appear here when the Agent modifies files, runs commands or executes tests",
|
|
153
|
-
"
|
|
162
|
+
"对话与轨迹": "Conversation and trace",
|
|
163
|
+
"返回会话": "Back to conversation",
|
|
164
|
+
"打开当前文件": "Open current file",
|
|
165
|
+
"待处理操作": "Pending interaction",
|
|
166
|
+
"加载更早结果": "Load earlier results",
|
|
167
|
+
"加载更早记录": "Load earlier messages",
|
|
168
|
+
"已完成,未投递": "Completed, not delivered",
|
|
169
|
+
"已完成,部分内容未投递": "Completed, partly delivered",
|
|
170
|
+
"已完成,投递结果未知": "Completed, delivery unknown",
|
|
171
|
+
"已撤回": "Recalled",
|
|
154
172
|
"Agent 运行中": "Agent is running",
|
|
155
173
|
"最近任务已完成": "Latest task completed",
|
|
156
174
|
"最近任务失败": "Latest task failed",
|
|
@@ -201,7 +219,7 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
|
|
|
201
219
|
"- 状态:{0}": "- Status: {0}",
|
|
202
220
|
"- 路径:{0}": "- Path: {0}",
|
|
203
221
|
"- 耗时:{0} ms": "- Duration: {0} ms",
|
|
204
|
-
"由 Zhin
|
|
222
|
+
"由 Zhin「会话」于 {0} 导出。": "Exported from Zhin Conversations at {0}.",
|
|
205
223
|
"开始处理": "Start processing",
|
|
206
224
|
"能力已解析": "Capabilities resolved",
|
|
207
225
|
"模型思考": "Model reasoning",
|
|
@@ -38,7 +38,7 @@ export function loadPlaygroundState(storage = browserStorage()) {
|
|
|
38
38
|
return fallback;
|
|
39
39
|
const sessionKeys = new Set(sessions.map(sessionIdentity));
|
|
40
40
|
const messages = Array.isArray(parsed.messages)
|
|
41
|
-
? parsed.messages.map(parseMessage).filter((item) => (
|
|
41
|
+
? parsed.messages.map(parseMessage).filter((item) => (item !== undefined && sessionKeys.has(sessionIdentity({ id: item.channelId, type: item.channelType }))))
|
|
42
42
|
: [];
|
|
43
43
|
const requestedActive = typeof parsed.activeSessionId === 'string'
|
|
44
44
|
? sessions.find((session) => session.id === parsed.activeSessionId && (parsed.activeSessionType === undefined || session.type === parsed.activeSessionType))
|
|
@@ -116,11 +116,61 @@ function parseMessage(value) {
|
|
|
116
116
|
content: item.content,
|
|
117
117
|
timestamp: Number.isFinite(item.timestamp) ? Number(item.timestamp) : Date.now(),
|
|
118
118
|
...(item.interactionResolved === true ? { interactionResolved: true } : {}),
|
|
119
|
+
...(hasPlaygroundKeyboard(item.content) ? { interactionReadOnly: true } : {}),
|
|
120
|
+
...(Number.isSafeInteger(item.historySequence) && Number(item.historySequence) > 0 ? { historySequence: Number(item.historySequence) } : {}),
|
|
121
|
+
...(item.recalled === true ? { recalled: true } : {}),
|
|
122
|
+
...(typeof item.recalledMessageId === 'string' ? { recalledMessageId: item.recalledMessageId } : {}),
|
|
119
123
|
};
|
|
120
124
|
}
|
|
125
|
+
export function hasPlaygroundKeyboard(content) {
|
|
126
|
+
return content.some(segment => segment?.type === 'keyboard' || (segment?.type === 'forward'
|
|
127
|
+
&& Array.isArray(segment.data?.entries) && segment.data.entries.some((entry) => Array.isArray(entry?.segments) && hasPlaygroundKeyboard(entry.segments))));
|
|
128
|
+
}
|
|
129
|
+
/** Retire only controls previously issued by the current authoritative prompt reader. */
|
|
130
|
+
export function retirePlaygroundInteractions(current, scene, retiredSegments) {
|
|
131
|
+
const retired = new Set(keyboardPayloads(retiredSegments));
|
|
132
|
+
return current.map(message => message.type === 'received' && message.channelType === scene.type && message.channelId === scene.id
|
|
133
|
+
&& message.interactionReadOnly !== true && keyboardPayloads(message.content).some(payload => retired.has(payload))
|
|
134
|
+
? { ...message, interactionReadOnly: true } : message);
|
|
135
|
+
}
|
|
136
|
+
function keyboardPayloads(segments) {
|
|
137
|
+
const payloads = [];
|
|
138
|
+
for (const segment of segments) {
|
|
139
|
+
if (segment?.type === 'keyboard' && Array.isArray(segment.data?.rows)) {
|
|
140
|
+
for (const row of segment.data.rows) {
|
|
141
|
+
if (!Array.isArray(row))
|
|
142
|
+
continue;
|
|
143
|
+
for (const button of row)
|
|
144
|
+
if (typeof button?.payload === 'string')
|
|
145
|
+
payloads.push(button.payload);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
else if (segment?.type === 'forward') {
|
|
149
|
+
if (Array.isArray(segment.data?.entries)) {
|
|
150
|
+
for (const entry of segment.data.entries)
|
|
151
|
+
if (Array.isArray(entry?.segments))
|
|
152
|
+
payloads.push(...keyboardPayloads(entry.segments));
|
|
153
|
+
}
|
|
154
|
+
if (Array.isArray(segment.data?.messages)) {
|
|
155
|
+
for (const batch of segment.data.messages)
|
|
156
|
+
if (Array.isArray(batch))
|
|
157
|
+
payloads.push(...keyboardPayloads(batch));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return payloads;
|
|
162
|
+
}
|
|
121
163
|
function browserStorage() {
|
|
122
164
|
return typeof window === 'undefined' ? undefined : window.localStorage;
|
|
123
165
|
}
|
|
124
166
|
function sessionIdentity(value) {
|
|
125
167
|
return `${value.type}\0${value.id}`;
|
|
126
168
|
}
|
|
169
|
+
/** Socket echoes replace their local optimistic row, without crossing scenes or authors. */
|
|
170
|
+
export function mergePlaygroundMessage(messages, incoming) {
|
|
171
|
+
const index = messages.findIndex(message => message.id === incoming.id
|
|
172
|
+
&& message.channelType === incoming.channelType && message.channelId === incoming.channelId
|
|
173
|
+
&& message.type === incoming.type);
|
|
174
|
+
return index < 0 ? [...messages, incoming]
|
|
175
|
+
: messages.map((message, offset) => offset === index ? { ...message, ...incoming } : message);
|
|
176
|
+
}
|