@kingsoftcloud/agentkit-harness-ui 0.0.18 → 0.0.19
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/package.json +2 -2
- package/src/components.mjs +1 -1
- package/src/engine-view/adapter.mjs +80 -10
- package/src/engine-view/app.mjs +2 -2
- package/src/host/session-task-events.mjs +60 -7
- package/src/host/state/native-runtime-route.mjs +3 -2
- package/src/host/state/native-status-panel.mjs +6 -0
- package/src/host/task-timeline.mjs +23 -12
- package/src/index.mjs +1 -1
- package/src/project.mjs +2 -2
- package/src/protocol.mjs +6 -1
- package/src/react-binding.mjs +116 -1
- package/src/reducer.mjs +29 -1
- package/src/renderers.mjs +6 -7
- package/src/styles.mjs +40 -3
- package/src/tool-error.mjs +19 -4
- package/src/view.mjs +22 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-ui",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.19",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Reusable React task-process UI for AgentKit Native: an explicitly versioned event protocol, a pure state reducer, and an accessible timeline. No Studio/DSH/Python imports; React is a peer dependency.",
|
|
@@ -98,6 +98,6 @@
|
|
|
98
98
|
"registry": "https://registry.npmjs.org"
|
|
99
99
|
},
|
|
100
100
|
"dependencies": {
|
|
101
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
101
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.19"
|
|
102
102
|
}
|
|
103
103
|
}
|
package/src/components.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
import { createHarnessComponents } from "./react-binding.mjs";
|
|
3
|
-
export const { HarnessTimeline } = createHarnessComponents(React);
|
|
3
|
+
export const { HarnessTimeline, HarnessTurn } = createHarnessComponents(React);
|
|
4
4
|
export { buildViewModel, styles } from "./react-binding.mjs";
|
|
5
5
|
|
|
6
6
|
import * as ReactDOM from "react-dom";
|
|
@@ -4,30 +4,62 @@
|
|
|
4
4
|
// adapter turns them into the timeline's own event stream. It is deterministic
|
|
5
5
|
// and keyed by engine sequence numbers, so replaying any prefix is a no-op.
|
|
6
6
|
import { PROTOCOL_VERSION } from "../protocol.mjs";
|
|
7
|
+
import { toolIdentity } from "../tool-identity.mjs";
|
|
7
8
|
|
|
8
9
|
export const ENGINE_EVENT_SCHEMA = "agentkit.engine-event/v1";
|
|
9
10
|
export const ENGINE_VIEW_CONTRACT = "agentkit.engine-view/v1";
|
|
11
|
+
export const FINAL_SUBMISSION_TOOL = "submit_final_output";
|
|
10
12
|
|
|
11
13
|
const OUTCOMES = new Set(["completed", "unverified", "blocked", "failed", "cancelled"]);
|
|
12
14
|
const text = value => typeof value === "string" && value.trim().length > 0;
|
|
13
15
|
const input = value => value === undefined || value === null ? {} : typeof value === "object" ? value : { value };
|
|
14
16
|
|
|
17
|
+
function completedEditDisplay(event) {
|
|
18
|
+
const kind = toolIdentity(event.title)?.family;
|
|
19
|
+
const { ok, path, diff_additions: added, diff_deletions: removed } = event.result ?? {};
|
|
20
|
+
if (!["edit", "write"].includes(kind) || ok !== true || !text(path)
|
|
21
|
+
|| ![added, removed].every(count => Number.isSafeInteger(count) && count >= 0)) return undefined;
|
|
22
|
+
return { kind: "file_edit", files: [{ path, changeStat: { added, removed }, operationKind: kind === "write" ? "write" : "edit" }] };
|
|
23
|
+
}
|
|
24
|
+
|
|
15
25
|
function outcomeOf(event) {
|
|
16
26
|
if (event.title === "failed" || event.status === "failed") return "failed";
|
|
17
|
-
if (event.title
|
|
27
|
+
if (["canceled", "cancelled"].includes(event.title) || ["canceled", "cancelled"].includes(event.status)) return "cancelled";
|
|
28
|
+
if (event.status === "verified") return "completed";
|
|
18
29
|
if (OUTCOMES.has(event.status)) return event.status;
|
|
19
30
|
return event.title === "completed" ? "completed" : "unverified";
|
|
20
31
|
}
|
|
21
32
|
|
|
33
|
+
function toolFailure(result, name) {
|
|
34
|
+
const code = result?.error_type ?? result?.code ?? result?.error_code;
|
|
35
|
+
const message = result?.error_message ?? result?.message;
|
|
36
|
+
if (!text(code)) return { message: text(message) ? message : `工具 ${name ?? ""} 未成功`.trim() };
|
|
37
|
+
return { code, ...(text(message) ? { message } : {}),
|
|
38
|
+
...(Number.isSafeInteger(result.failed_edit_index) && result.failed_edit_index >= 0
|
|
39
|
+
? { failed_edit_index: result.failed_edit_index } : {}) };
|
|
40
|
+
}
|
|
41
|
+
|
|
22
42
|
/** Convert one engine event; returns zero or more harness-ui events. */
|
|
23
|
-
export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
43
|
+
export function engineEventToTimeline(event, { runId = "run", time, startedAt = time } = {}) {
|
|
24
44
|
if (!event || event.schema !== ENGINE_EVENT_SCHEMA || !Number.isSafeInteger(event.seq)) return [];
|
|
25
45
|
const v = PROTOCOL_VERSION, id = suffix => `${runId}:${event.seq}:${suffix}`;
|
|
46
|
+
const thoughtId = typeof event.requestId === "string" && /^[a-f0-9]{64}$/.test(event.requestId)
|
|
47
|
+
? `${runId}:thought:${event.requestId}` : id("thought");
|
|
26
48
|
switch (event.kind) {
|
|
27
49
|
case "run.started":
|
|
28
|
-
return [{ v, id: id("start"), type: "task.started", taskId: runId, runId }];
|
|
50
|
+
return [{ v, id: id("start"), type: "task.started", taskId: runId, runId, startedAt }];
|
|
51
|
+
case "todo.initialized":
|
|
52
|
+
case "todo.updated":
|
|
53
|
+
return Object.hasOwn(event, "plan") ? [{ v, id: id("todo"), type: "plan.updated",
|
|
54
|
+
items: event.plan?.items ?? [], completedCount: event.plan?.completedCount, totalCount: event.plan?.totalCount }] : [];
|
|
55
|
+
case "effect.prepared":
|
|
56
|
+
case "effect.settled":
|
|
57
|
+
return event.category === "model" && event.title === "request"
|
|
58
|
+
? [{ v, id: id("model-request"), type: "model.request", active: event.kind === "effect.prepared", itemId: thoughtId }]
|
|
59
|
+
: [];
|
|
29
60
|
case "model.completed": {
|
|
30
61
|
const out = [];
|
|
62
|
+
if (text(event.thinking)) out.push({ v, id: id("thought-done"), type: "thinking.done", itemId: thoughtId, text: event.thinking });
|
|
31
63
|
// Commentary that accompanies tool calls is progress, not the answer.
|
|
32
64
|
if (text(event.detail) && (event.title === "initial_plan" || Array.isArray(event.calls) && event.calls.length)) {
|
|
33
65
|
const itemId = `${runId}:note:${event.seq}`;
|
|
@@ -35,29 +67,41 @@ export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
|
35
67
|
{ v, id: id("note-done"), type: "text.done", itemId });
|
|
36
68
|
}
|
|
37
69
|
for (const call of Array.isArray(event.calls) ? event.calls : []) {
|
|
38
|
-
if (!text(call?.callId) || !text(call?.name)) continue;
|
|
70
|
+
if (!text(call?.callId) || !text(call?.name) || call.name === FINAL_SUBMISSION_TOOL) continue;
|
|
39
71
|
out.push({ v, id: id(`call:${call.callId}`), type: "tool.scheduled", callId: call.callId, name: call.name, input: input(call.arguments) },
|
|
40
72
|
{ v, id: id(`run:${call.callId}`), type: "tool.started", callId: call.callId });
|
|
41
73
|
}
|
|
42
74
|
return out;
|
|
43
75
|
}
|
|
76
|
+
case "model.stream_interrupted":
|
|
77
|
+
return text(event.thinking)
|
|
78
|
+
? [{ v, id: id("thought-done"), type: "thinking.done", itemId: thoughtId, text: event.thinking }]
|
|
79
|
+
: [];
|
|
44
80
|
case "tool.completed": {
|
|
45
81
|
if (!text(event.callId)) return [];
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
82
|
+
// Older engines stored the committed TodoWrite receipt but omitted the
|
|
83
|
+
// separate checklist projection. Never infer progress from tool inputs.
|
|
84
|
+
const display = event.status === "ok" ? completedEditDisplay(event) : undefined;
|
|
85
|
+
if (event.status !== "ok") return [{ v, id: id("error"), type: "tool.error", callId: event.callId,
|
|
86
|
+
error: toolFailure(event.result, event.title) }];
|
|
87
|
+
const out = [{ v, id: id("result"), type: "tool.result", callId: event.callId, result: event.result ?? null,
|
|
88
|
+
...(display ? { display } : {}) }];
|
|
89
|
+
if (event.title === "TodoWrite" && Array.isArray(event.result?.todos))
|
|
90
|
+
out.push({ v, id: id("todo-receipt"), type: "plan.updated",
|
|
91
|
+
items: event.result.todos.map((item, index) => ({ ...item, id: `todo:${index}` })) });
|
|
92
|
+
return out;
|
|
50
93
|
}
|
|
51
94
|
case "model.failure_observed":
|
|
52
95
|
return [{ v, id: id("retry"), type: "task.state", state: "running", reason: "model_retry", message: `模型请求失败(${event.detail ?? "unknown"}),正在重试。` }];
|
|
53
96
|
case "run.terminal": {
|
|
54
97
|
const out = [];
|
|
98
|
+
const itemId = `${runId}:final`;
|
|
55
99
|
if (text(event.detail)) {
|
|
56
|
-
const itemId = `${runId}:final`;
|
|
57
100
|
out.push({ v, id: id("final"), type: "text.delta", itemId, delta: event.detail }, { v, id: id("final-done"), type: "text.done", itemId });
|
|
58
101
|
}
|
|
59
102
|
if (event.title === "paused") return [...out, { v, id: id("paused"), type: "task.state", state: "paused", reason: event.reason ?? null }];
|
|
60
|
-
return [...out, { v, id: id("finished"), type: "task.finished", outcome: outcomeOf(event),
|
|
103
|
+
return [...out, { v, id: id("finished"), type: "task.finished", outcome: outcomeOf(event), endedAt: time,
|
|
104
|
+
...(out.length ? { finalAnswerId: itemId } : {}), ...(event.reason ? { reason: event.reason } : {}) }];
|
|
61
105
|
}
|
|
62
106
|
default:
|
|
63
107
|
return [];
|
|
@@ -67,3 +111,29 @@ export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
|
67
111
|
export function engineEventsToTimeline(events, options) {
|
|
68
112
|
return (Array.isArray(events) ? events : []).flatMap(event => engineEventToTimeline(event, options));
|
|
69
113
|
}
|
|
114
|
+
|
|
115
|
+
export function relativeDeliveryPath(path) {
|
|
116
|
+
return typeof path === "string" && path.length <= 2048 && !/[\\:\u0000-\u001f\u007f?#]/u.test(path)
|
|
117
|
+
&& path.split("/").every(part => part && part !== "." && part !== "..");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Web cards come from the Run's manifest. Older Runs can name an HTML file
|
|
121
|
+
* explicitly in the final answer; the host still has to confirm it exists. */
|
|
122
|
+
export function engineWebDeliveries(event) {
|
|
123
|
+
if (event?.schema !== ENGINE_EVENT_SCHEMA || event.kind !== "run.terminal" || event.title !== "completed"
|
|
124
|
+
|| !text(event.detail)) return [];
|
|
125
|
+
const declared = Array.isArray(event.deliverables) ? event.deliverables : [];
|
|
126
|
+
const web = declared.find(item => item?.kind === "web" && relativeDeliveryPath(item.path)
|
|
127
|
+
&& /\.html?$/i.test(item.path) && (item.root === "." || relativeDeliveryPath(item.root)
|
|
128
|
+
&& item.path.startsWith(item.root + "/")));
|
|
129
|
+
if (web) return [{ path: web.path, root: web.root }];
|
|
130
|
+
if (declared.length) return [];
|
|
131
|
+
|
|
132
|
+
const paths = new Set();
|
|
133
|
+
for (const match of event.detail.matchAll(/`([^`\r\n]+)`|\]\(([^\s()]+)\)/g)) {
|
|
134
|
+
const path = (match[1] ?? match[2]).replace(/^\.\//, "");
|
|
135
|
+
if (relativeDeliveryPath(path) && !/[%<>]/.test(path) && /\.html?$/i.test(path)) paths.add(path);
|
|
136
|
+
if (paths.size >= 8) break;
|
|
137
|
+
}
|
|
138
|
+
return [...paths].map(path => ({ path }));
|
|
139
|
+
}
|
package/src/engine-view/app.mjs
CHANGED
|
@@ -18,7 +18,7 @@ import { initialState, reduceAll } from "../reducer.mjs";
|
|
|
18
18
|
import { engineEventsToTimeline, ENGINE_VIEW_CONTRACT } from "./adapter.mjs";
|
|
19
19
|
|
|
20
20
|
const VERSION = globalThis.__ENGINE_VIEW_VERSION__ ?? "dev";
|
|
21
|
-
const {
|
|
21
|
+
const { HarnessTurn } = createHarnessComponents(React);
|
|
22
22
|
const post = message => { try { window.parent.postMessage({ contract: ENGINE_VIEW_CONTRACT, ...message }, "*"); } catch { /* detached */ } };
|
|
23
23
|
|
|
24
24
|
function App() {
|
|
@@ -48,7 +48,7 @@ function App() {
|
|
|
48
48
|
observer.observe(root);
|
|
49
49
|
return () => { window.removeEventListener("message", onMessage); observer.disconnect(); };
|
|
50
50
|
}, []);
|
|
51
|
-
return React.createElement(
|
|
51
|
+
return React.createElement(HarnessTurn, { state: view.state, theme: view.theme, autoFollow: false, styleSheet: null });
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
createRoot(document.getElementById("root")).render(React.createElement(App));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { initialState, reduce } from '@kingsoftcloud/agentkit-harness-ui/reducer';
|
|
2
2
|
import { previewToolInput } from '@kingsoftcloud/agentkit-harness-ui/input-preview';
|
|
3
3
|
import { nativeRunIsInactive } from './state/native-outcome.mjs';
|
|
4
|
+
import { ENGINE_EVENT_SCHEMA, FINAL_SUBMISSION_TOOL, engineEventToTimeline, engineWebDeliveries } from '../engine-view/adapter.mjs';
|
|
4
5
|
|
|
5
6
|
const textOf = content => (Array.isArray(content) ? content : []).filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
6
7
|
const nativeInterruptionMessages = Object.freeze({
|
|
@@ -55,7 +56,8 @@ function admittedContextMarker(event, sessionId) {
|
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
export function createSessionTaskProjector({ sessionId } = {}) {
|
|
58
|
-
let revision = -1, previousWindow = null, tasks = new Map(), result = [], activeTurn = null, settledSteps = new Set(), previews = new Map(), finalAnswers = new Map(), dispositions = new Map();
|
|
59
|
+
let revision = -1, previousWindow = null, tasks = new Map(), result = [], activeTurn = null, settledSteps = new Set(), previews = new Map(), finalAnswers = new Map(), dispositions = new Map(), engineTurns = new Map(), replies = new Map();
|
|
60
|
+
let settledEngineThoughts = new Set();
|
|
59
61
|
const apply = entry => {
|
|
60
62
|
const event = entry.event, data = event?.data;
|
|
61
63
|
if (!event || !data) return;
|
|
@@ -84,6 +86,7 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
84
86
|
if (!task) task = reduce(initialState(), { v: 1, type: 'task.started', id: `turn:${turn}`, taskId: String(turn),
|
|
85
87
|
...(event.type === 'turn/start' ? { startedAt: event.time } : {}) });
|
|
86
88
|
const prefix = `${turn}:${data.step ?? 0}`, source = `${entry.type}:${event.seq}`;
|
|
89
|
+
const engineBlock = index => `${turn}:engine-thought:${index}`;
|
|
87
90
|
const responseId = typeof sessionId === 'string' && sessionId && Number.isSafeInteger(data.step) && data.step > 0
|
|
88
91
|
? JSON.stringify([sessionId, turn, data.step]) : null;
|
|
89
92
|
// The host retains successful attempt frames until step/end so its own
|
|
@@ -94,6 +97,22 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
94
97
|
let index = 0;
|
|
95
98
|
const emit = (type, value) => { task = reduce(task, { v: 1, type, id: `${source}:${index++}`, ts: event.time, ...value }); };
|
|
96
99
|
if (event.type === 'turn/start' && task.taskStartedAt === null) emit('task.started', { taskId: String(turn), startedAt: event.time });
|
|
100
|
+
if (event.type === 'agentkit/native-engine-event' && event.ignorable === true
|
|
101
|
+
&& typeof data.runId === 'string' && data.runId && data.event?.schema === ENGINE_EVENT_SCHEMA
|
|
102
|
+
&& Number.isSafeInteger(data.event.seq)) {
|
|
103
|
+
const previous = engineTurns.get(turn);
|
|
104
|
+
if (previous && (previous.runId !== data.runId || previous.seq >= data.event.seq)) return;
|
|
105
|
+
const terminal = data.event.kind === 'run.terminal';
|
|
106
|
+
engineTurns.set(turn, { runId: data.runId, seq: data.event.seq, terminal,
|
|
107
|
+
...(terminal ? { deliveries: engineWebDeliveries(data.event).map(item => ({ ...item, seq: event.seq })),
|
|
108
|
+
...(data.event.title === 'completed' ? { deliverySeq: event.seq } : {}) } : {}) });
|
|
109
|
+
if (Number.isSafeInteger(data.settledThinkingBlock) && data.settledThinkingBlock >= 0)
|
|
110
|
+
settledEngineThoughts.add(engineBlock(data.settledThinkingBlock));
|
|
111
|
+
for (const frame of engineEventToTimeline(data.event, { runId: data.runId, time: event.time, startedAt: task.taskStartedAt ?? event.time }))
|
|
112
|
+
task = reduce(task, frame);
|
|
113
|
+
tasks.set(turn, task);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
97
116
|
const block = (value, position, done = true, sourceMessageId) => {
|
|
98
117
|
const itemId = `${prefix}:block:${position}`;
|
|
99
118
|
if (value.type === 'text') emit(done ? 'text.done' : 'text.delta', { itemId, ...(responseId ? { responseId } : {}), ...(sourceMessageId ? { sourceMessageId } : {}), ...(done ? { text: value.text } : { delta: value.text }) });
|
|
@@ -101,11 +120,37 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
101
120
|
};
|
|
102
121
|
if (event.type === 'user/message' && ['user', 'user-rpc'].includes(data.source?.kind))
|
|
103
122
|
emit('text.done', { itemId: `user:${data.id ?? event.seq}`, text: textOf(data.content), role: 'user' });
|
|
123
|
+
const engine = engineTurns.get(turn);
|
|
124
|
+
if (event.type === 'agentkit/native-engine-tool-draft') {
|
|
125
|
+
if (event.ignorable !== true || engine?.runId !== data.runId || !task.modelThinkingId
|
|
126
|
+
|| !/^[a-f0-9]{64}$/.test(data.requestId) || task.modelThinkingId !== `${data.runId}:thought:${data.requestId}`
|
|
127
|
+
|| !Array.isArray(data.tools) || data.tools.length > 16) return;
|
|
128
|
+
for (const tool of data.tools) {
|
|
129
|
+
if (!Number.isSafeInteger(tool?.index) || tool.index < 0 || typeof tool.name !== 'string'
|
|
130
|
+
|| !/^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/.test(tool.name) || tool.name === FINAL_SUBMISSION_TOOL) continue;
|
|
131
|
+
emit('tool.preview', { previewId: `${task.modelThinkingId}:draft:${tool.index}`, name: tool.name, responseId: task.modelThinkingId });
|
|
132
|
+
}
|
|
133
|
+
tasks.set(turn, task);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (event.type === 'assistant/live-chunk' && engine) {
|
|
137
|
+
const chunk = data.chunk;
|
|
138
|
+
if (task.modelThinkingId && chunk?.type === 'reasoning-delta' && Number.isSafeInteger(chunk.index)
|
|
139
|
+
&& !settledEngineThoughts.has(engineBlock(chunk.index))
|
|
140
|
+
&& !task.items.some(item => item.kind === 'tool-preview' && item.responseId === task.modelThinkingId)) {
|
|
141
|
+
emit('thinking.delta', { itemId: task.modelThinkingId, responseId: task.modelThinkingId, delta: chunk.text });
|
|
142
|
+
tasks.set(turn, task);
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
104
146
|
if (event.type === 'assistant/message') {
|
|
105
147
|
const content = data.message?.content ?? [];
|
|
106
148
|
const textIndex = content.findLastIndex(part => part.type === 'text' && part.text?.trim());
|
|
107
|
-
|
|
108
|
-
|
|
149
|
+
const final = data.interrupted !== true && textIndex >= 0 && !content.some(part => part.type === 'tool-call');
|
|
150
|
+
finalAnswers.set(turn, final ? `${prefix}:block:${textIndex}` : null);
|
|
151
|
+
if (final) replies.set(turn, { messageId: data.message.id });
|
|
152
|
+
else replies.delete(turn);
|
|
153
|
+
if (engine && (task.finalAnswerId || !final)) return;
|
|
109
154
|
content.forEach((part, i) => {
|
|
110
155
|
block(part, i, true, data.message.id);
|
|
111
156
|
// A host may publish the live dispatch before the committed assistant
|
|
@@ -117,7 +162,7 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
117
162
|
}
|
|
118
163
|
});
|
|
119
164
|
}
|
|
120
|
-
if (event.type === 'assistant/live-chunk') {
|
|
165
|
+
if (event.type === 'assistant/live-chunk' && !engine) {
|
|
121
166
|
const chunk = data.chunk;
|
|
122
167
|
if (chunk?.type === 'text-delta') block({ type: 'text', text: chunk.text }, chunk.index, false);
|
|
123
168
|
if (chunk?.type === 'reasoning-delta') block({ type: 'reasoning', text: chunk.text }, chunk.index, false);
|
|
@@ -133,11 +178,11 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
133
178
|
...(responseId ? { responseId } : {}) });
|
|
134
179
|
}
|
|
135
180
|
}
|
|
136
|
-
if (event.type === 'tool/call') {
|
|
181
|
+
if (event.type === 'tool/call' && !engine) {
|
|
137
182
|
let input = {}; try { input = typeof data.arguments === 'string' ? JSON.parse(data.arguments) : data.arguments; } catch { /* incomplete arguments */ }
|
|
138
183
|
emit('tool.scheduled', { callId: data.callId, name: data.name, input, ...(responseId ? { responseId } : {}) });
|
|
139
184
|
}
|
|
140
|
-
if (event.type === 'tool/result') {
|
|
185
|
+
if (event.type === 'tool/result' && !engine) {
|
|
141
186
|
const message = data.message;
|
|
142
187
|
const text = textOf(message?.content); let value;
|
|
143
188
|
try { value = JSON.parse(text); } catch { /* plain tool result */ }
|
|
@@ -151,6 +196,9 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
151
196
|
}
|
|
152
197
|
if (event.type === 'turn/end') {
|
|
153
198
|
const reason = data.reason;
|
|
199
|
+
if (replies.has(turn)) replies.set(turn, { ...replies.get(turn), time: event.time, seq: event.seq,
|
|
200
|
+
branchable: reason?.kind === 'completed' });
|
|
201
|
+
if (engine?.terminal && (task.finalAnswerId || !finalAnswers.get(turn) || reason?.kind !== 'completed')) return;
|
|
154
202
|
const interruption = reason?.kind === 'error' && typeof reason.error?.code === 'string'
|
|
155
203
|
&& Object.hasOwn(nativeInterruptionMessages, reason.error.code) ? nativeInterruptionMessages[reason.error.code] : null;
|
|
156
204
|
const outcome = interruption ? 'unverified' : reason?.kind === 'completed' ? 'unverified' : reason?.kind === 'blocked' ? 'blocked'
|
|
@@ -179,12 +227,17 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
179
227
|
const append = suffix !== null && !suffix.some(entry => entry.event?.type === 'assistant/message');
|
|
180
228
|
if (!append) {
|
|
181
229
|
tasks = new Map(); activeTurn = null; previews = new Map(); finalAnswers = new Map(); dispositions = new Map();
|
|
230
|
+
engineTurns = new Map(); replies = new Map(); settledEngineThoughts = new Set();
|
|
182
231
|
settledSteps = new Set((window.entries ?? []).filter(entry => entry.event?.type === 'assistant/message')
|
|
183
232
|
.map(entry => `${entry.event.data.turn}:${entry.event.data.step ?? 0}`));
|
|
184
233
|
}
|
|
185
234
|
for (const entry of append ? suffix : window.entries ?? []) apply(entry);
|
|
186
235
|
revision = window.revision;previousWindow = window;
|
|
187
|
-
result = [...tasks].sort(([a], [b]) => a - b).map(([turn, state]) => ({
|
|
236
|
+
result = [...tasks].sort(([a], [b]) => a - b).map(([turn, state]) => ({
|
|
237
|
+
turn, state, ...(replies.has(turn) ? { reply: replies.get(turn) } : {}),
|
|
238
|
+
...(state.finalAnswerId && engineTurns.get(turn)?.deliverySeq !== undefined
|
|
239
|
+
? { deliveries: engineTurns.get(turn).deliveries, deliverySeq: engineTurns.get(turn).deliverySeq } : {}),
|
|
240
|
+
}));
|
|
188
241
|
return result;
|
|
189
242
|
},
|
|
190
243
|
};
|
|
@@ -7,7 +7,7 @@ export function nativeRuntimeRouteInput(_session, openState, projection, boundPr
|
|
|
7
7
|
return { presetId: boundPresetId, ready: openState === 'open' && projection?.state === 'ready' };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, signal }) {
|
|
10
|
+
export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, isIndependentPreset, signal }) {
|
|
11
11
|
const first = await hostRemote.agents({ source: 'local', pageSize: 100 });
|
|
12
12
|
signal.throwIfAborted();
|
|
13
13
|
if (!Array.isArray(first?.items)) throw Error('智能体目录响应无效');
|
|
@@ -22,5 +22,6 @@ export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveA
|
|
|
22
22
|
if (!agentId) return { kind: 'other', agentId: null };
|
|
23
23
|
const agent = items.find(item => (item.metadata?.id ?? item.id) === agentId);
|
|
24
24
|
if (!agent) throw Error('当前会话的智能体配置暂不可用');
|
|
25
|
-
|
|
25
|
+
if (agent.spec?.runtime?.type !== 'harness') return { kind: 'other', agentId };
|
|
26
|
+
return { kind: isIndependentPreset?.(presetId) ? 'engine' : 'native', agentId };
|
|
26
27
|
}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
export function engineStatusPanelModel(tasks, running) {
|
|
2
|
+
const latest = tasks.findLast(task => task.state.planSummary);
|
|
3
|
+
const plan = latest?.state.plan ? { items: latest.state.plan, ...latest.state.planSummary } : null;
|
|
4
|
+
return { git: null, plan, terminals: [], agents: [], isRunning: Boolean(running) };
|
|
5
|
+
}
|
|
6
|
+
|
|
1
7
|
/** Host facts adapted to the independent status presentation. No execution capability. */
|
|
2
8
|
export function nativeStatusPanelModel(status, children = [], commandObservations = []) {
|
|
3
9
|
const activity = status?.activity;
|
|
@@ -3,7 +3,7 @@ import { installNativeCommandPane } from './native-command-pane.mjs';
|
|
|
3
3
|
import { createHarnessComponents } from '@kingsoftcloud/agentkit-harness-ui/react-binding';
|
|
4
4
|
import { createMarkdownComponents, markdownStyles } from '@kingsoftcloud/agentkit-harness-ui/markdown';
|
|
5
5
|
import { createStatusPanelComponents, statusPanelStyles } from '@kingsoftcloud/agentkit-harness-ui/status-panel';
|
|
6
|
-
import { nativeStatusPanelModel } from './state/native-status-panel.mjs';
|
|
6
|
+
import { engineStatusPanelModel, nativeStatusPanelModel } from './state/native-status-panel.mjs';
|
|
7
7
|
import { nativeTaskWorkspaceRoot, taskWorkspaceFileTarget } from './state/task-links.mjs';
|
|
8
8
|
import { resolveNativeRuntimeRoute, nativeRuntimeRouteInput } from './state/native-runtime-route.mjs';
|
|
9
9
|
import { createNativeTaskReadModel } from './state/native-task-read-model.mjs';
|
|
@@ -27,11 +27,11 @@ const labels = { result: '执行结果', thought: '思考', running: '执行中'
|
|
|
27
27
|
toolPreparing: '正在生成工具参数', previewStopped: '工具参数生成已中断' };
|
|
28
28
|
|
|
29
29
|
/** Only the transport adapter and runtime controls belong to Studio. */
|
|
30
|
-
export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPreset }) {
|
|
30
|
+
export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPreset, isIndependentPreset, resolveWebDelivery, loadDeliveryEvidence }) {
|
|
31
31
|
if (typeof resolveAgentFromPreset !== 'function') throw TypeError('The host preset-to-Agent resolver is required');
|
|
32
32
|
const { React, ReactDOM } = ui;
|
|
33
33
|
const { createElement: h, useMemo, useEffect, useLayoutEffect, useState, useRef } = React;
|
|
34
|
-
const {
|
|
34
|
+
const { HarnessTurn } = createHarnessComponents(React);
|
|
35
35
|
const { ConversationStatusPanel } = createStatusPanelComponents(React, ReactDOM);
|
|
36
36
|
const { MarkdownResponse } = createMarkdownComponents(React, ReactDOM);
|
|
37
37
|
const commandPane = installNativeCommandPane(ctx, { React, hostRemote });
|
|
@@ -40,7 +40,8 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
40
40
|
onOpenExternalUrl: url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); },
|
|
41
41
|
onOpenFileLink: onOpenFile && (({ href }) => { const target = taskWorkspaceFileTarget(href, cwd); if (target) onOpenFile(target); }) }, text) });
|
|
42
42
|
const markdownLabels = { copyCode: '复制代码', copied: '已复制', wrapLines: '自动换行', languageLabel: '代码' };
|
|
43
|
-
function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile,
|
|
43
|
+
function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile, openExternalLink,
|
|
44
|
+
branchAt, renderAssistantActions, turnAnchors, fallback, statusPanel }) {
|
|
44
45
|
const [variant, setVariant] = useState(() => {
|
|
45
46
|
try { const saved = localStorage.getItem('native.status-panel.variant'); return ['auto', 'mini', 'panel'].includes(saved) ? saved : 'auto'; }
|
|
46
47
|
catch { return 'auto'; }
|
|
@@ -71,6 +72,10 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
71
72
|
const error = localError ?? readSnapshot?.error;
|
|
72
73
|
const projector = useMemo(() => createSessionTaskProjector({ sessionId }), [sessionId]);
|
|
73
74
|
const tasks = useMemo(() => projector.project(eventWindow), [projector, eventWindow]);
|
|
75
|
+
const resolveDelivery = useMemo(() => resolveWebDelivery
|
|
76
|
+
? (delivery, signal) => resolveWebDelivery(sessionId, delivery, signal) : undefined, [sessionId]);
|
|
77
|
+
const loadEvidence = useMemo(() => loadDeliveryEvidence
|
|
78
|
+
? (seq, signal) => loadDeliveryEvidence(sessionId, seq, signal) : undefined, [sessionId]);
|
|
74
79
|
useEffect(() => {
|
|
75
80
|
let active = true;
|
|
76
81
|
setProjectionError(null);
|
|
@@ -84,7 +89,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
84
89
|
const controller = new AbortController();
|
|
85
90
|
const generation = ++routeGeneration.current;
|
|
86
91
|
setRoute({ key: routeKey, kind: 'loading', agentId: null, generation }); setError(null);
|
|
87
|
-
if (routeReady) void resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, signal: controller.signal })
|
|
92
|
+
if (routeReady) void resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, isIndependentPreset, signal: controller.signal })
|
|
88
93
|
.then(next => { if (!controller.signal.aborted) setRoute({ ...next, key: routeKey, generation }); })
|
|
89
94
|
.catch(failure => { if (!controller.signal.aborted) setRoute({ key: routeKey, kind: 'error', agentId: null, generation,
|
|
90
95
|
error: failure.message || '无法读取当前会话的运行时' }); });
|
|
@@ -110,7 +115,9 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
110
115
|
setCommandObservations([]);
|
|
111
116
|
if (nativeAgent) return commandPane.subscribe({ agentId: nativeAgent, sessionId }, setCommandObservations);
|
|
112
117
|
}, [nativeAgent, sessionId]);
|
|
113
|
-
const
|
|
118
|
+
const engineRoute = route.key === routeKey && route.kind === 'engine';
|
|
119
|
+
const panelModel = useMemo(() => engineRoute ? engineStatusPanelModel(tasks, running)
|
|
120
|
+
: nativeStatusPanelModel(status, childTasks, commandObservations), [engineRoute, tasks, running, status, childTasks, commandObservations]);
|
|
114
121
|
useEffect(() => {
|
|
115
122
|
if (nativeAgent) for (const terminal of panelModel.terminals)
|
|
116
123
|
commandPane.register({ ...terminal, agentId: nativeAgent, sessionId });
|
|
@@ -121,7 +128,8 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
121
128
|
if (!target) { setError('文件链接不在执行工作区或位置无效'); return; }
|
|
122
129
|
void Promise.resolve(openFile(target.path)).catch(failure => setError(failure.message || '无法打开文件'));
|
|
123
130
|
};
|
|
124
|
-
const panelVisible = nativeAgent && (panelModel.git || panelModel.plan
|
|
131
|
+
const panelVisible = (nativeAgent || engineRoute) && Boolean(panelModel.git || panelModel.plan
|
|
132
|
+
|| panelModel.agents.length || panelModel.terminals.length || panelModel.isRunning);
|
|
125
133
|
useLayoutEffect(() => {
|
|
126
134
|
// The presentation owns the summary seat while routing/loading too.
|
|
127
135
|
// Lack of polled data is not permission to paint the resident Todo dock.
|
|
@@ -147,7 +155,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
147
155
|
if (route.kind === 'error') return h('div', { role: 'alert', 'data-testid': 'task-runtime-error' },
|
|
148
156
|
h('p', null, route.error), h('button', { type: 'button', onClick: () => setRouteAttempt(value => value + 1) }, '重试加载'));
|
|
149
157
|
if (route.kind === 'other') return fallback;
|
|
150
|
-
if (!observation) return readSnapshot?.phase === 'error'
|
|
158
|
+
if (route.kind === 'native' && !observation) return readSnapshot?.phase === 'error'
|
|
151
159
|
? h('div', { role: 'alert', 'data-testid': 'task-observation-error' }, h('p', null, readSnapshot.error),
|
|
152
160
|
h('button', { type: 'button', onClick: () => void readerRef.current?.refresh() }, '重试加载任务过程'))
|
|
153
161
|
: h('div', { role: 'status', 'data-testid': 'task-observation-loading' }, '正在同步任务过程…');
|
|
@@ -160,16 +168,19 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
160
168
|
onOpenSubagent: openSubagent,
|
|
161
169
|
onOpenTerminal: terminal => commandPane.open({ ...terminal, agentId: nativeAgent, sessionId }),
|
|
162
170
|
onOpenSubagentDirectory: () => childPane.openDirectory({ agentId: nativeAgent, parentSessionId: sessionId }) })), statusPanel.target) : null,
|
|
163
|
-
...presented.map(({ turn, state }) => h(
|
|
164
|
-
state,
|
|
171
|
+
...presented.map(({ turn, state, reply, deliveries, deliverySeq }) => h(HarnessTurn, { key: turn,
|
|
172
|
+
state, reply, onBranch: branchAt, assistantActions: reply?.messageId ? renderAssistantActions?.(reply.messageId) : null,
|
|
173
|
+
deliveries, resolveWebDelivery: resolveDelivery, deliverySeq, loadDeliveryEvidence: loadEvidence,
|
|
174
|
+
containerProps: { 'data-chat-anchor-key': turnAnchors?.get(turn), 'data-chat-paging-anchor': true },
|
|
175
|
+
labels, locale: 'zh-CN', showPlanDock: !statusPanel, theme: theme.active.colorScheme,
|
|
165
176
|
workspaceRoot: executionRoot,
|
|
166
177
|
onOpenFile: ({ path }) => openWorkspaceFile(path),
|
|
167
178
|
onOpenSubagent: openSubagent,
|
|
168
|
-
onCopy: text =>
|
|
179
|
+
onCopy: text => navigator.clipboard.writeText(text),
|
|
169
180
|
renderText: (text, { streaming }) => h(MarkdownResponse, { streaming, theme: theme.active.colorScheme, scopeKey: sessionId + ':' + executionRoot,
|
|
170
181
|
labels: markdownLabels,
|
|
171
182
|
onCopyCode: text => navigator.clipboard.writeText(text),
|
|
172
|
-
onOpenExternalUrl: url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); },
|
|
183
|
+
onOpenExternalUrl: openExternalLink ?? (url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); }),
|
|
173
184
|
onOpenFileLink: ({ href }) => openWorkspaceFile(href) }, text) })),
|
|
174
185
|
...(pending ?? []).filter(item => item.placement === 'transcript').map(item => h('p', { key: item.requestId, 'aria-label': '待发送输入' }, item.text)),
|
|
175
186
|
error ? h('p', { role: 'alert' }, error) : null,
|
package/src/index.mjs
CHANGED
|
@@ -49,4 +49,4 @@ export { toolIdentity, toolConversationVisible, localizedToolTitle } from './too
|
|
|
49
49
|
|
|
50
50
|
// React binding. Imported lazily-safe only because this barrel re-exports it;
|
|
51
51
|
// hosts that do not need React should import the subpaths directly.
|
|
52
|
-
export { HarnessTimeline } from "./components.mjs";
|
|
52
|
+
export { HarnessTimeline, HarnessTurn } from "./components.mjs";
|
package/src/project.mjs
CHANGED
|
@@ -69,8 +69,8 @@ export function isTerminal(state) {
|
|
|
69
69
|
export function planProgress(state) {
|
|
70
70
|
const plan = state?.plan;
|
|
71
71
|
if (!Array.isArray(plan) || !plan.length) return null;
|
|
72
|
-
const total = plan.length;
|
|
73
|
-
const completed = plan.filter(item => item.status === "completed").length;
|
|
72
|
+
const total = state.planSummary?.totalCount ?? plan.length;
|
|
73
|
+
const completed = state.planSummary?.completedCount ?? plan.filter(item => item.status === "completed").length;
|
|
74
74
|
const inProgress = plan.find(item => item.status === "in_progress");
|
|
75
75
|
return {
|
|
76
76
|
total,
|
package/src/protocol.mjs
CHANGED
|
@@ -21,6 +21,7 @@ export const EventType = Object.freeze({
|
|
|
21
21
|
TaskStarted: "task.started",
|
|
22
22
|
TaskState: "task.state",
|
|
23
23
|
TaskFinished: "task.finished",
|
|
24
|
+
ModelRequest: "model.request",
|
|
24
25
|
TextDelta: "text.delta",
|
|
25
26
|
TextDone: "text.done",
|
|
26
27
|
ThinkingStart: "thinking.start",
|
|
@@ -162,6 +163,9 @@ function normalizePayload(type, event) {
|
|
|
162
163
|
...(hostTime(event.startedAt) !== null ? { startedAt: event.startedAt } : {}) };
|
|
163
164
|
case EventType.TaskState:
|
|
164
165
|
return { state: requiredChoice(event.state, TASK_STATES, "task state"), reason: str(event.reason) || null, message: str(event.message) || null };
|
|
166
|
+
case EventType.ModelRequest:
|
|
167
|
+
if (typeof event.active !== "boolean") throw new TypeError("model request requires an active flag");
|
|
168
|
+
return { active: event.active, itemId: str(event.itemId) };
|
|
165
169
|
case EventType.TaskFinished: {
|
|
166
170
|
const outcome = requiredChoice(event.outcome, TASK_OUTCOMES, "task outcome");
|
|
167
171
|
if (event.executionState !== undefined && (event.executionState !== TaskState.Interrupted || outcome !== TaskOutcome.Unverified))
|
|
@@ -223,7 +227,8 @@ function normalizePayload(type, event) {
|
|
|
223
227
|
after: { kind: marker.after.kind, ...(marker.after.id ? { id: marker.after.id } : {}) } } };
|
|
224
228
|
}
|
|
225
229
|
case EventType.PlanUpdated:
|
|
226
|
-
return { items: Array.isArray(event.items) ? event.items.map(normalizePlanItem).filter(Boolean) : []
|
|
230
|
+
return { items: Array.isArray(event.items) ? event.items.map(normalizePlanItem).filter(Boolean) : [],
|
|
231
|
+
completedCount: event.completedCount, totalCount: event.totalCount };
|
|
227
232
|
default:
|
|
228
233
|
return {};
|
|
229
234
|
}
|
package/src/react-binding.mjs
CHANGED
|
@@ -483,13 +483,128 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
483
483
|
}
|
|
484
484
|
|
|
485
485
|
|
|
486
|
+
function WebDelivery({ path, seq, resolve, zh }) {
|
|
487
|
+
const [preview, setPreview] = useState(null);
|
|
488
|
+
const [pending, setPending] = useState(false);
|
|
489
|
+
const [failed, setFailed] = useState(false);
|
|
490
|
+
const lifetime = useRef(null);
|
|
491
|
+
useEffect(() => {
|
|
492
|
+
const controller = new AbortController();
|
|
493
|
+
lifetime.current = controller;
|
|
494
|
+
void resolve({ path, seq }, controller.signal).then(delivery => {
|
|
495
|
+
if (!controller.signal.aborted) setPreview(delivery);
|
|
496
|
+
}).catch(() => {});
|
|
497
|
+
return () => controller.abort();
|
|
498
|
+
}, [path, seq, resolve]);
|
|
499
|
+
if (!preview?.href) return null;
|
|
500
|
+
const filename = path.split('/').at(-1);
|
|
501
|
+
const openLabel = zh ? `打开 ${filename}` : `Open ${filename}`;
|
|
502
|
+
const openSidebar = async () => {
|
|
503
|
+
const signal = lifetime.current.signal;
|
|
504
|
+
setFailed(false);
|
|
505
|
+
setPending(true);
|
|
506
|
+
try { await preview.openInSidebar(signal); }
|
|
507
|
+
catch { if (!signal.aborted) setFailed(true); }
|
|
508
|
+
finally { if (!signal.aborted) setPending(false); }
|
|
509
|
+
};
|
|
510
|
+
const newTab = (label, ariaLabel) => createElement('a', { href: preview.href, target: '_blank', rel: 'noopener noreferrer',
|
|
511
|
+
'aria-label': ariaLabel }, label);
|
|
512
|
+
return createElement('div', { className: 'harness-delivery', 'data-testid': 'web-delivery' },
|
|
513
|
+
createElement('span', { className: 'harness-delivery-icon' },
|
|
514
|
+
createElement('svg', { viewBox: '0 0 24 24', width: 20, height: 20, fill: 'none', stroke: 'currentColor',
|
|
515
|
+
strokeWidth: 1.5, 'aria-hidden': true },
|
|
516
|
+
createElement('circle', { cx: 12, cy: 12, r: 9 }), createElement('ellipse', { cx: 12, cy: 12, rx: 4, ry: 9 }),
|
|
517
|
+
createElement('path', { d: 'M3 12h18' }))),
|
|
518
|
+
createElement('span', { className: 'harness-delivery-name' },
|
|
519
|
+
createElement('strong', { title: path }, filename),
|
|
520
|
+
createElement('small', null, zh ? '网站 · HTML' : 'Website · HTML')),
|
|
521
|
+
preview.openInSidebar ? createElement('div', { className: 'harness-delivery-actions' },
|
|
522
|
+
createElement('button', { type: 'button', disabled: pending, onClick: openSidebar, 'aria-label': openLabel },
|
|
523
|
+
pending ? (zh ? '正在打开…' : 'Opening…') : (zh ? '打开' : 'Open')),
|
|
524
|
+
createElement('details', { className: 'harness-delivery-menu' },
|
|
525
|
+
createElement('summary', { 'aria-label': zh ? '更多打开方式' : 'More ways to open' },
|
|
526
|
+
createElement('svg', { width: 14, height: 14, viewBox: '0 0 24 24', 'aria-hidden': true, fill: 'none', stroke: 'currentColor' },
|
|
527
|
+
createElement('path', { d: 'm6 9 6 6 6-6', strokeWidth: 2 }))),
|
|
528
|
+
newTab(zh ? '在新标签页打开' : 'Open in a new tab')),
|
|
529
|
+
failed ? createElement('span', { role: 'status' }, zh ? '无法打开侧栏预览' : 'Could not open the sidebar preview') : null)
|
|
530
|
+
: newTab(zh ? '打开' : 'Open', openLabel));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function DeliveryEvidence({ seq, load, openFile, zh }) {
|
|
534
|
+
const [evidence, setEvidence] = useState(null);
|
|
535
|
+
useEffect(() => {
|
|
536
|
+
const controller = new AbortController();
|
|
537
|
+
void load(seq, controller.signal).then(value => {
|
|
538
|
+
if (!controller.signal.aborted) setEvidence(value);
|
|
539
|
+
}).catch(() => {});
|
|
540
|
+
return () => controller.abort();
|
|
541
|
+
}, [seq, load]);
|
|
542
|
+
if (!evidence) return null;
|
|
543
|
+
const { files, screenshots, truncated } = evidence;
|
|
544
|
+
const counts = file => Number.isSafeInteger(file.added) && file.added >= 0
|
|
545
|
+
&& Number.isSafeInteger(file.removed) && file.removed >= 0;
|
|
546
|
+
const delta = (added, removed) => createElement('span', { className: 'harness-delivery-delta' },
|
|
547
|
+
createElement('span', null, `+${added}`), createElement('span', null, `−${removed}`));
|
|
548
|
+
const total = files.length && !truncated && files.every(counts)
|
|
549
|
+
? delta(files.reduce((sum, file) => sum + file.added, 0), files.reduce((sum, file) => sum + file.removed, 0)) : null;
|
|
550
|
+
const label = zh ? `${files.length}${truncated ? '+' : ''} 个文件已更改`
|
|
551
|
+
: `${files.length}${truncated ? '+' : ''} ${files.length === 1 ? 'file' : 'files'} changed`;
|
|
552
|
+
return createElement(React.Fragment, null,
|
|
553
|
+
files.length ? createElement('details', { className: 'harness-delivery-changes', 'data-testid': 'delivery-changes' },
|
|
554
|
+
createElement('summary', null, label, total),
|
|
555
|
+
createElement('ul', null, ...files.map(file => createElement('li', { key: file.path },
|
|
556
|
+
file.deleted || !openFile ? createElement('span', null, file.path)
|
|
557
|
+
: createElement('button', { type: 'button', onClick: () => openFile({ path: file.path, kind: 'file' }) }, file.path),
|
|
558
|
+
counts(file) ? delta(file.added, file.removed) : null)))) : null,
|
|
559
|
+
...screenshots.map(({ path, href }) => createElement('a', { key: path, className: 'harness-delivery-image',
|
|
560
|
+
'data-testid': 'delivery-screenshot', href, target: '_blank', rel: 'noopener noreferrer' },
|
|
561
|
+
createElement('img', { src: href, alt: path.split('/').at(-1), loading: 'lazy' }))));
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function HarnessTurn({ state, reply, onCopy, onBranch, assistantActions, containerProps, deliveries, resolveWebDelivery,
|
|
565
|
+
deliverySeq, loadDeliveryEvidence, locale = 'zh-CN', ...timeline }) {
|
|
566
|
+
const [copyState, setCopyState] = useState(null);
|
|
567
|
+
const answer = state.items.find(item => item.id === state.finalAnswerId);
|
|
568
|
+
const copy = async () => {
|
|
569
|
+
try {
|
|
570
|
+
const text = answer.sourceMessageId ? state.items.filter(item => item.kind === 'text'
|
|
571
|
+
&& item.sourceMessageId === answer.sourceMessageId).map(item => item.text).join('\n\n') : answer.text;
|
|
572
|
+
await (onCopy ? onCopy(text) : navigator.clipboard.writeText(text));
|
|
573
|
+
setCopyState('copied');
|
|
574
|
+
} catch { setCopyState('failed'); }
|
|
575
|
+
};
|
|
576
|
+
const zh = locale.startsWith('zh');
|
|
577
|
+
const copyLabel = copyState === 'copied' ? (zh ? '已复制' : 'Copied') : (zh ? '复制回复' : 'Copy reply');
|
|
578
|
+
const branchLabel = zh ? '从这里新建分支' : 'Branch from here';
|
|
579
|
+
const button = (label, onClick, path) => createElement('button', { type: 'button', title: label, 'aria-label': label, onClick },
|
|
580
|
+
createElement('svg', { viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
|
|
581
|
+
strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, createElement('path', { d: path })));
|
|
582
|
+
const clock = reply?.time ?? state.taskEndedAt;
|
|
583
|
+
return createElement('article', { ...containerProps, className: 'harness-turn', 'data-testid': 'harness-turn' },
|
|
584
|
+
createElement(HarnessTimeline, { state, onCopy, locale, ...timeline }),
|
|
585
|
+
state.taskState === 'failed' && state.taskError
|
|
586
|
+
? createElement('p', { className: 'harness-turn-error', role: 'alert' }, state.taskError) : null,
|
|
587
|
+
...(answer?.kind === 'text' && !answer.streaming && resolveWebDelivery ? (deliveries ?? []).map(delivery =>
|
|
588
|
+
createElement(WebDelivery, { key: JSON.stringify([delivery.seq, delivery.path]), ...delivery, resolve: resolveWebDelivery, zh })) : []),
|
|
589
|
+
answer?.kind === 'text' && !answer.streaming && deliverySeq !== undefined && loadDeliveryEvidence
|
|
590
|
+
? createElement(DeliveryEvidence, { key: deliverySeq, seq: deliverySeq, load: loadDeliveryEvidence, openFile: timeline.onOpenFile, zh }) : null,
|
|
591
|
+
answer?.kind === 'text' && !answer.streaming ? createElement('div', { className: 'harness-reply-actions',
|
|
592
|
+
role: 'group', 'aria-label': zh ? '回复操作' : 'Reply actions' },
|
|
593
|
+
button(copyLabel, copy, copyState === 'copied' ? 'm5 12 4 4L19 6' : 'M8 8h11v12H8zM5 16H4V4h11v1'),
|
|
594
|
+
assistantActions,
|
|
595
|
+
reply?.branchable && onBranch ? button(branchLabel, () => onBranch(reply.seq), 'M5 19 19 5m-6 0h6v6M5 10v9h9') : null,
|
|
596
|
+
typeof clock === 'number' && Number.isFinite(clock) ? createElement('time', { dateTime: new Date(clock).toISOString() },
|
|
597
|
+
new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit', hour12: false }).format(clock)) : null,
|
|
598
|
+
copyState === 'failed' ? createElement('span', { role: 'status' }, zh ? '无法复制' : 'Unable to copy') : null) : null);
|
|
599
|
+
}
|
|
600
|
+
|
|
486
601
|
function SubagentPane({ state, loading, error, omittedRows = 0, omittedChars = 0, labels = {}, ...timeline }) {
|
|
487
602
|
return React.createElement('section', { className: 'harness-subagent-pane', 'data-testid': 'subagent-pane', 'aria-readonly': true },
|
|
488
603
|
error ? React.createElement('p', { role: 'alert' }, error) : loading ? React.createElement('p', { role: 'status' }, labels.childSyncing || 'Syncing') : null,
|
|
489
604
|
omittedRows || omittedChars ? React.createElement('p', { className: 'harness-subagent-window-notice' }, labels.childOmitted || 'Earlier rows or long fields are omitted in this observation window.') : null,
|
|
490
605
|
state ? React.createElement(HarnessTimeline, { state, labels, ...timeline }) : null);
|
|
491
606
|
}
|
|
492
|
-
return { HarnessTimeline, SubagentPane };
|
|
607
|
+
return { HarnessTimeline, HarnessTurn, SubagentPane };
|
|
493
608
|
}
|
|
494
609
|
|
|
495
610
|
export { buildViewModel, styles };
|
package/src/reducer.mjs
CHANGED
|
@@ -33,12 +33,15 @@ export function initialState() {
|
|
|
33
33
|
taskError: null,
|
|
34
34
|
taskStartedAt: null, taskEndedAt: null, finalAnswerId: null,
|
|
35
35
|
verificationRequired: null,
|
|
36
|
+
modelRequestActive: false,
|
|
37
|
+
modelThinkingId: null,
|
|
36
38
|
contextMarkers: [],
|
|
37
39
|
subagents: new Map(),
|
|
38
40
|
items: [], // ordered TimelineItem[]
|
|
39
41
|
seen: new Set(), // event ids already applied (dedup/replay)
|
|
40
42
|
pendingThinking: new Set(), // itemIds that had thinking.start but no delta yet
|
|
41
43
|
plan: null, // PlanItem[] | null
|
|
44
|
+
planSummary: null, // null until the session has observed a checklist update
|
|
42
45
|
lastSeq: null,
|
|
43
46
|
};
|
|
44
47
|
}
|
|
@@ -84,6 +87,11 @@ function apply(state, e) {
|
|
|
84
87
|
case EventType.TaskStarted: return applyTaskStarted(state, e);
|
|
85
88
|
case EventType.TaskState: return applyTaskState(state, e);
|
|
86
89
|
case EventType.TaskFinished: return applyTaskFinished(state, e);
|
|
90
|
+
case EventType.ModelRequest:
|
|
91
|
+
if (!e.active || state.modelThinkingId !== e.itemId) settleModelPresentation(state);
|
|
92
|
+
state.modelRequestActive = e.active;
|
|
93
|
+
state.modelThinkingId = e.active ? e.itemId : null;
|
|
94
|
+
return;
|
|
87
95
|
case EventType.TextDelta: return applyTextDelta(state, e);
|
|
88
96
|
case EventType.TextDone: return applyTextDone(state, e);
|
|
89
97
|
case EventType.ThinkingStart: return applyThinkingStart(state, e);
|
|
@@ -141,9 +149,20 @@ function applyTaskStarted(state, e) {
|
|
|
141
149
|
state.taskEndedAt = null; state.finalAnswerId = null;
|
|
142
150
|
}
|
|
143
151
|
|
|
152
|
+
function settleModelPresentation(state) {
|
|
153
|
+
if (!state.modelThinkingId) return;
|
|
154
|
+
applyThinkingDone(state, { itemId: state.modelThinkingId });
|
|
155
|
+
state.items = state.items.filter(item => item.kind !== 'tool-preview' || item.responseId !== state.modelThinkingId);
|
|
156
|
+
}
|
|
157
|
+
|
|
144
158
|
function applyTaskState(state, e) {
|
|
145
159
|
if (!canTransition(state.taskState, e.state)) return; // ignore invalid transitions
|
|
146
160
|
state.taskState = e.state;
|
|
161
|
+
if (e.state !== TaskState.Running) {
|
|
162
|
+
settleModelPresentation(state);
|
|
163
|
+
state.modelRequestActive = false;
|
|
164
|
+
state.modelThinkingId = null;
|
|
165
|
+
}
|
|
147
166
|
state.taskReason = e.reason;
|
|
148
167
|
state.taskMessage = e.message;
|
|
149
168
|
if (e.state === TaskState.Running || e.state === TaskState.Recovered) {
|
|
@@ -153,6 +172,9 @@ function applyTaskState(state, e) {
|
|
|
153
172
|
}
|
|
154
173
|
|
|
155
174
|
function applyTaskFinished(state, e) {
|
|
175
|
+
settleModelPresentation(state);
|
|
176
|
+
state.modelRequestActive = false;
|
|
177
|
+
state.modelThinkingId = null;
|
|
156
178
|
state.verificationRequired = e.verificationRequired;
|
|
157
179
|
state.taskOutcome = e.outcome;
|
|
158
180
|
state.taskSummary = e.summary; // host-supplied; may be null — never invented
|
|
@@ -317,7 +339,13 @@ function settlePriorReasoning(state, event) {
|
|
|
317
339
|
}
|
|
318
340
|
|
|
319
341
|
function applyPlan(state, e) {
|
|
320
|
-
state.plan =
|
|
342
|
+
state.plan = e.items.length ? e.items : null;
|
|
343
|
+
const visibleCompleted = e.items.filter(item => item.status === "completed").length;
|
|
344
|
+
const totalCount = Number.isSafeInteger(e.totalCount) && e.totalCount >= e.items.length ? e.totalCount : e.items.length;
|
|
345
|
+
const omittedItems = totalCount - e.items.length;
|
|
346
|
+
const completedCount = Number.isSafeInteger(e.completedCount) && e.completedCount >= visibleCompleted
|
|
347
|
+
&& e.completedCount <= visibleCompleted + omittedItems ? e.completedCount : visibleCompleted;
|
|
348
|
+
state.planSummary = { totalCount, completedCount, omittedItems };
|
|
321
349
|
}
|
|
322
350
|
|
|
323
351
|
function findItemIndex(state, id) {
|
package/src/renderers.mjs
CHANGED
|
@@ -122,9 +122,9 @@ function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultO
|
|
|
122
122
|
if (canToggle) summaryKids.push(chevronIcon("harness-tool-chevron"));
|
|
123
123
|
const visibleBody = open && canToggle ? (typeof body === 'function' ? body() : body) : [];
|
|
124
124
|
const bodyKids = Array.isArray(visibleBody) ? visibleBody : [visibleBody];
|
|
125
|
-
if (error && open && canToggle) bodyKids.
|
|
125
|
+
if (error && open && canToggle) bodyKids.unshift(h("div", {
|
|
126
126
|
className: "harness-tool-error", role: "alert", "data-testid": "tool-error",
|
|
127
|
-
}, error));
|
|
127
|
+
}, errorSummary === error ? error : [errorSummary, h("div", {}, error)]));
|
|
128
128
|
const detailsProps = canToggle ? {
|
|
129
129
|
open, className: "harness-tool-details", "data-testid": "tool-details",
|
|
130
130
|
"data-call-id": item.callId, "aria-expanded": open,
|
|
@@ -322,9 +322,7 @@ function readFileRenderer(item, opts) {
|
|
|
322
322
|
? (opts.labels && opts.labels.readReading || "Reading")
|
|
323
323
|
: (opts.labels && opts.labels.readKind || "Read");
|
|
324
324
|
const canOpen = Boolean(opts.onOpenFile) && meta.entryType === "file";
|
|
325
|
-
//
|
|
326
|
-
// path is NOT duplicated in the title — only the leaf shows in the chip and
|
|
327
|
-
// the workspace-relative path shows once as the secondary.
|
|
325
|
+
// Show the file chip once. Keep relative context for nested files.
|
|
328
326
|
const summary = [
|
|
329
327
|
h("span", {
|
|
330
328
|
className: running
|
|
@@ -335,11 +333,12 @@ function readFileRenderer(item, opts) {
|
|
|
335
333
|
fileChip(path, fileName, canOpen, opts, "read-chip", "read-file-name",
|
|
336
334
|
{ kind: meta.entryType === "directory" ? "directory" : "file", callId: item.callId, path }),
|
|
337
335
|
];
|
|
338
|
-
|
|
336
|
+
const relativePath = path ? workspaceRelative(path, opts.workspaceRoot) : "";
|
|
337
|
+
if (relativePath && relativePath !== fileName) summary.push(h("span", {
|
|
339
338
|
className: "harness-tool-secondary harness-read-path",
|
|
340
339
|
"data-testid": "read-file-path",
|
|
341
340
|
title: path,
|
|
342
|
-
},
|
|
341
|
+
}, relativePath));
|
|
343
342
|
// Read is a one-line chip; it does not toggle. A failed read surfaces its
|
|
344
343
|
// error inline via the shell, and an optional inspect action lets the host
|
|
345
344
|
// open the result/details (the public result-inspection action).
|
package/src/styles.mjs
CHANGED
|
@@ -86,6 +86,7 @@ export const styles = `
|
|
|
86
86
|
user-select: none;
|
|
87
87
|
}
|
|
88
88
|
.harness-thought-summary::-webkit-details-marker, .harness-tool-summary::-webkit-details-marker { display: none; }
|
|
89
|
+
.harness-model-activity { cursor: default; }
|
|
89
90
|
/* Inline SVG icons (Lucide, ISC — see NOTICE) are sized by font-size so they
|
|
90
91
|
sit on the text baseline; stroke is currentColor so they inherit the line
|
|
91
92
|
color and dim with the muted/failure tokens. */
|
|
@@ -134,7 +135,6 @@ export const styles = `
|
|
|
134
135
|
.harness-tool-secondary { font-size: 0.8rem; color: var(--harness-fg-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 40ch; }
|
|
135
136
|
.harness-tool-status { font-size: 0.8rem; color: var(--harness-fg-muted); text-transform: lowercase; }
|
|
136
137
|
.harness-tool-status-running { color: var(--harness-running); }
|
|
137
|
-
.harness-tool-status-failed { color: var(--harness-error); }
|
|
138
138
|
.harness-tool-status-completed { display: none; }
|
|
139
139
|
.harness-tool-details-static > summary { cursor: default; list-style: none; }
|
|
140
140
|
.harness-tool-details-static > summary::-webkit-details-marker { display: none; }
|
|
@@ -150,8 +150,7 @@ export const styles = `
|
|
|
150
150
|
.harness-tool-detail-line dt { color: var(--harness-fg-muted); min-width: 8ch; }
|
|
151
151
|
.harness-tool-detail-line dd { margin: 0; word-break: break-all; }
|
|
152
152
|
.harness-tool-progress { color: var(--harness-running); font-size: 0.85rem; }
|
|
153
|
-
.harness-tool-error { color: var(--harness-
|
|
154
|
-
.harness-tool-error-inline { font-weight: 600; }
|
|
153
|
+
.harness-tool-error { color: var(--harness-fg-muted); font-size: 0.85rem; }
|
|
155
154
|
.harness-tool-result { margin-top: 6px; }
|
|
156
155
|
.harness-tool-result > summary { cursor: pointer; color: var(--harness-fg-muted); font-size: 0.8rem; }
|
|
157
156
|
|
|
@@ -263,6 +262,44 @@ button.harness-tool-summary { border: 0; background: none; color: inherit; font:
|
|
|
263
262
|
.harness-subagent-window-notice { font-size: 12px; color: var(--harness-fg-muted, #888); }
|
|
264
263
|
.harness-work-items { display: flex; flex-direction: column; gap: var(--harness-work-gap, 16px); }
|
|
265
264
|
.harness-work-history { margin: 0; }
|
|
265
|
+
.harness-turn { width: 100%; min-width: 0; }
|
|
266
|
+
.harness-turn + .harness-turn { margin-top: 24px; }
|
|
267
|
+
.harness-turn-error { color: #cf222e; color: light-dark(#cf222e, #ff7b72); margin: 8px 0 0; }
|
|
268
|
+
.harness-delivery { display: flex; align-items: center; gap: 12px; padding: 10px 12px; margin-top: 12px; border-radius: 10px;
|
|
269
|
+
border: 1px solid color-mix(in srgb, currentColor 16%, transparent); background: color-mix(in srgb, currentColor 6%, transparent);
|
|
270
|
+
font-size: var(--ui-font-size, 14px); }
|
|
271
|
+
.harness-delivery-icon { display: grid; place-items: center; flex: 0 0 34px; height: 34px; border-radius: 7px;
|
|
272
|
+
background: color-mix(in srgb, currentColor 8%, transparent); }
|
|
273
|
+
.harness-delivery-name { display: grid; gap: 2px; flex: 1; min-width: 0; }
|
|
274
|
+
.harness-delivery-name strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
|
|
275
|
+
.harness-delivery-name small { color: var(--dsh-fg-muted, GrayText); }
|
|
276
|
+
.harness-delivery :is(a, button, summary) { flex: none; padding: 4px 10px; border: 1px solid color-mix(in srgb, currentColor 20%, transparent);
|
|
277
|
+
border-radius: 6px; color: inherit; text-decoration: none; }
|
|
278
|
+
.harness-delivery :is(a, button, summary):is(:hover, :focus-visible) { background: color-mix(in srgb, currentColor 9%, transparent); }
|
|
279
|
+
.harness-delivery-actions { display: flex; align-items: center; gap: 4px; }
|
|
280
|
+
.harness-delivery button { background: transparent; font: inherit; cursor: pointer; }
|
|
281
|
+
.harness-delivery-menu { position: relative; }
|
|
282
|
+
.harness-delivery-menu summary { display: flex; align-items: center; height: 28px; box-sizing: border-box; cursor: pointer; list-style: none; }
|
|
283
|
+
.harness-delivery-menu summary::-webkit-details-marker { display: none; }
|
|
284
|
+
.harness-delivery-menu a { position: absolute; z-index: 1; inset-inline-end: 0; margin-top: 4px; width: max-content;
|
|
285
|
+
background: var(--color-popover, Canvas); }
|
|
286
|
+
.harness-delivery-changes { margin-top: 12px; border: 1px solid color-mix(in srgb, currentColor 16%, transparent);
|
|
287
|
+
border-radius: 10px; background: color-mix(in srgb, currentColor 6%, transparent); font-size: var(--ui-font-size, 14px); }
|
|
288
|
+
.harness-delivery-changes summary { padding: 10px 12px; cursor: pointer; }
|
|
289
|
+
.harness-delivery-delta { display: inline-flex; gap: 6px; margin-inline-start: 8px; }
|
|
290
|
+
.harness-delivery-delta span:first-child { color: light-dark(#1a7f37, #4ac26b); }
|
|
291
|
+
.harness-delivery-delta span:last-child { color: light-dark(#cf222e, #ff7b72); }
|
|
292
|
+
.harness-delivery-changes ul { list-style: none; margin: 0; padding: 0 12px 8px; }
|
|
293
|
+
.harness-delivery-changes li { display: flex; align-items: center; justify-content: space-between; min-width: 0; }
|
|
294
|
+
.harness-delivery-changes li :is(button, span) { overflow-wrap: anywhere; }
|
|
295
|
+
.harness-delivery-changes li button { padding: 4px 0; text-align: start; background: transparent; color: inherit;
|
|
296
|
+
border: 0; font: inherit; cursor: pointer; }
|
|
297
|
+
.harness-delivery-changes li button:hover { text-decoration: underline; }
|
|
298
|
+
.harness-delivery-image { display: block; width: fit-content; max-width: 100%; margin-top: 12px; }
|
|
299
|
+
.harness-delivery-image img { display: block; max-width: min(100%, 480px); height: auto; border-radius: 10px; }
|
|
300
|
+
.harness-reply-actions { display: flex; align-items: center; gap: 10px; margin-top: 10px; color: var(--dsh-fg-muted, GrayText); font-size: 12px; }
|
|
301
|
+
.harness-reply-actions button { display: inline-grid; place-items: center; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 5px; color: inherit; background: transparent; cursor: pointer; }
|
|
302
|
+
.harness-reply-actions button:hover, .harness-reply-actions button:focus-visible { background: color-mix(in srgb, currentColor 12%, transparent); }
|
|
266
303
|
.harness-work-history-summary { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; border-bottom: 1px solid var(--harness-border); color: var(--harness-fg-muted); cursor: pointer; list-style: none; }
|
|
267
304
|
.harness-work-history-summary::-webkit-details-marker { display: none; }
|
|
268
305
|
.harness-work-history-chevron { opacity: .7; }
|
package/src/tool-error.mjs
CHANGED
|
@@ -7,6 +7,8 @@ const summaries = {
|
|
|
7
7
|
capture_limit_exceeded: '工作区变更清单超出观测上限,命令未执行',
|
|
8
8
|
command_policy_blocked: '命令不符合当前执行规则,尚未执行',
|
|
9
9
|
policy_denied: '当前权限规则未允许这次操作',
|
|
10
|
+
snippet_not_found: '找不到要替换的原文片段',
|
|
11
|
+
ambiguous_edit: '原文匹配次数与预期不符',
|
|
10
12
|
command_evidence_incomplete: '命令回执尚不完整,需要核对执行结果',
|
|
11
13
|
studio_native_browser_unavailable: '本地浏览器不可用,尚未完成网页验证',
|
|
12
14
|
child_capability_unavailable: '该子智能体缺少任务所需工具,尚未启动',
|
|
@@ -20,13 +22,26 @@ const summaries = {
|
|
|
20
22
|
selector_resolution_failed: '无法解析或读取指定目标',
|
|
21
23
|
};
|
|
22
24
|
|
|
25
|
+
function errorValue(error) {
|
|
26
|
+
try { return typeof error === 'string' ? JSON.parse(error) : error; } catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const errorCode = value => value?.error_type ?? value?.code ?? value?.error_code ?? value?.error?.code;
|
|
30
|
+
|
|
31
|
+
export function isRetryableEditFailure(error) {
|
|
32
|
+
return ['snippet_not_found', 'ambiguous_edit'].includes(errorCode(errorValue(error)));
|
|
33
|
+
}
|
|
34
|
+
|
|
23
35
|
/** Detailed evidence remains expandable; compact rows do not dump wire JSON. */
|
|
24
36
|
export function toolErrorSummary(error, { locale } = {}) {
|
|
25
|
-
|
|
26
|
-
try { value = typeof error === 'string' ? JSON.parse(error) : error; } catch { /* plain error */ }
|
|
37
|
+
const value = errorValue(error);
|
|
27
38
|
if (value && typeof value === 'object') {
|
|
28
|
-
const code = value
|
|
29
|
-
if (String(locale ?? '').startsWith('zh'))
|
|
39
|
+
const code = errorCode(value);
|
|
40
|
+
if (String(locale ?? '').startsWith('zh')) {
|
|
41
|
+
if (code === 'snippet_not_found' && Number.isSafeInteger(value.failed_edit_index) && value.failed_edit_index >= 0)
|
|
42
|
+
return `第 ${value.failed_edit_index + 1} 项找不到原文,本批修改未写入`;
|
|
43
|
+
return summaries[code] ?? '工具调用失败,点击查看具体原因';
|
|
44
|
+
}
|
|
30
45
|
return 'Tool call failed; expand for details';
|
|
31
46
|
}
|
|
32
47
|
return redactError(error);
|
package/src/view.mjs
CHANGED
|
@@ -19,6 +19,8 @@ import { latestSummaryLine } from './summary-playback.mjs';
|
|
|
19
19
|
import { visibleItems, isWaitingForFirstToken, planProgress, DEFAULT_LABELS } from "./project.mjs";
|
|
20
20
|
import { latestNonEmptyLine, truncateText } from "./summary.mjs";
|
|
21
21
|
import { renderTool } from "./renderers.mjs";
|
|
22
|
+
import { isRetryableEditFailure } from "./tool-error.mjs";
|
|
23
|
+
import { toolIdentity } from "./tool-identity.mjs";
|
|
22
24
|
import { activityGroups, activityGroupSummary } from './activity-groups.mjs';
|
|
23
25
|
import { conversationWorkSegments, completedWorkLabel } from './work-segments.mjs';
|
|
24
26
|
|
|
@@ -167,17 +169,23 @@ export function buildViewModel(state, options = {}) {
|
|
|
167
169
|
"data-testid": "harness-timeline",
|
|
168
170
|
"data-has-user-input": String(items.some(item => item.kind === 'text' && item.role === 'user')),
|
|
169
171
|
role: "log",
|
|
170
|
-
"aria-label": opts.ariaLabel,
|
|
171
|
-
"aria-busy": isWaitingForFirstToken(state) ? "true" : "false",
|
|
172
|
+
"aria-label": options.ariaLabel ?? (String(opts.locale ?? '').startsWith('zh') ? '任务过程' : opts.ariaLabel),
|
|
173
|
+
"aria-busy": (isWaitingForFirstToken(state) || state.taskState === "running" && state.modelRequestActive) ? "true" : "false",
|
|
172
174
|
...(opts.rootProps || {}),
|
|
173
175
|
}, ...rootChildren);
|
|
174
176
|
}
|
|
175
177
|
|
|
176
178
|
function timelineList(state, items, opts) {
|
|
177
179
|
const kids = [];
|
|
178
|
-
|
|
179
|
-
|
|
180
|
+
const modelActive = state.taskState === "running" && state.modelRequestActive;
|
|
181
|
+
if (!modelActive && isWaitingForFirstToken(state)) kids.push(waitingPlaceholder(opts));
|
|
182
|
+
const transcript = state.taskState === 'running' ? items.filter(item =>
|
|
183
|
+
!(item.kind === 'tool' && item.status === 'failed' && toolIdentity(item.name).family === 'edit'
|
|
184
|
+
&& isRetryableEditFailure(item.error))) : items;
|
|
185
|
+
const segments = conversationWorkSegments(state, transcript);
|
|
180
186
|
for (const [index, segment] of segments.entries()) {
|
|
187
|
+
const showModelActivity = modelActive && index === segments.length - 1
|
|
188
|
+
&& !segment.process.some(item => item.streaming && ["thought", "tool-preview"].includes(item.kind));
|
|
181
189
|
kids.push(...renderTimelineItems(segment.inputs, opts));
|
|
182
190
|
if (segment.collapsible) {
|
|
183
191
|
const open = Boolean(opts.historyOpen?.get(segment.id));
|
|
@@ -186,11 +194,13 @@ function timelineList(state, items, opts) {
|
|
|
186
194
|
h('span', {}, completedWorkLabel(state, opts.locale)), chevronIcon('harness-work-history-chevron')),
|
|
187
195
|
open ? h('div', { className: 'harness-work-items harness-work-history-content', 'data-testid': 'work-history-content' },
|
|
188
196
|
...renderTimelineItems(segment.process, opts)) : null));
|
|
189
|
-
} else if (segment.process.length) kids.push(h('div', { className: 'harness-work-items', 'data-testid': 'work-process' },
|
|
197
|
+
} else if (segment.process.length || showModelActivity) kids.push(h('div', { className: 'harness-work-items', 'data-testid': 'work-process' },
|
|
190
198
|
...renderTimelineItems(segment.process, opts, state.taskState === 'running'
|
|
191
|
-
&& index === segments.length - 1 && segment.following.length === 0)
|
|
199
|
+
&& index === segments.length - 1 && segment.following.length === 0),
|
|
200
|
+
showModelActivity ? modelActivity(opts) : null));
|
|
192
201
|
kids.push(...renderTimelineItems(segment.following, opts));
|
|
193
202
|
}
|
|
203
|
+
if (modelActive && !segments.length) kids.push(modelActivity(opts));
|
|
194
204
|
if (!kids.length && opts.emptyState) kids.push(opts.emptyState);
|
|
195
205
|
if (opts.following === false) kids.push(jumpToLatest(opts));
|
|
196
206
|
return h("div", { className: "harness-timeline", "data-testid": "harness-timeline-list" }, ...kids);
|
|
@@ -260,6 +270,12 @@ function textBlock(item, opts) {
|
|
|
260
270
|
}, h("span", { className: "harness-text-content" }, text));
|
|
261
271
|
}
|
|
262
272
|
|
|
273
|
+
function modelActivity(opts) {
|
|
274
|
+
return h("div", { className: "harness-thought-summary harness-model-activity", role: "status", "data-testid": "model-thinking" },
|
|
275
|
+
brainIcon("harness-thought-icon"),
|
|
276
|
+
h("span", { className: "harness-thought-label harness-thought-label-streaming" }, opts.labels.thinking));
|
|
277
|
+
}
|
|
278
|
+
|
|
263
279
|
function thoughtBlock(item, opts) {
|
|
264
280
|
const streaming = Boolean(item.streaming);
|
|
265
281
|
const userOpen = opts.thoughtOpen ? Boolean(opts.thoughtOpen.get(item.id)) : null;
|