@kingsoftcloud/agentkit-harness-ui 0.0.19 → 0.0.21
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/engine-view/adapter.mjs +17 -5
- package/src/host/pending-inputs.mjs +22 -0
- package/src/host/session-task-events.mjs +17 -2
- package/src/host/task-timeline.mjs +9 -3
- package/src/protocol.mjs +11 -2
- package/src/react-binding.mjs +18 -13
- package/src/reducer.mjs +27 -1
- package/src/renderers.mjs +88 -47
- package/src/styles.mjs +6 -2
- package/src/tool-error.mjs +14 -1
- package/src/view.mjs +27 -9
- package/src/work-segments.mjs +18 -2
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.21",
|
|
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.21"
|
|
102
102
|
}
|
|
103
103
|
}
|
|
@@ -34,7 +34,8 @@ function toolFailure(result, name) {
|
|
|
34
34
|
const code = result?.error_type ?? result?.code ?? result?.error_code;
|
|
35
35
|
const message = result?.error_message ?? result?.message;
|
|
36
36
|
if (!text(code)) return { message: text(message) ? message : `工具 ${name ?? ""} 未成功`.trim() };
|
|
37
|
-
|
|
37
|
+
const reason = code === 'command_policy_blocked' && result?.executed === false ? result.finding?.detail : undefined;
|
|
38
|
+
return { code, ...(text(reason) ? { message: reason } : text(message) ? { message } : {}),
|
|
38
39
|
...(Number.isSafeInteger(result.failed_edit_index) && result.failed_edit_index >= 0
|
|
39
40
|
? { failed_edit_index: result.failed_edit_index } : {}) };
|
|
40
41
|
}
|
|
@@ -55,7 +56,9 @@ export function engineEventToTimeline(event, { runId = "run", time, startedAt =
|
|
|
55
56
|
case "effect.prepared":
|
|
56
57
|
case "effect.settled":
|
|
57
58
|
return event.category === "model" && event.title === "request"
|
|
58
|
-
? [{ v, id: id("model-request"), type: "model.request", active: event.kind === "effect.prepared",
|
|
59
|
+
? [{ v, id: id("model-request"), type: "model.request", active: event.kind === "effect.prepared",
|
|
60
|
+
retry: event.kind === "effect.prepared" && event.retry === true,
|
|
61
|
+
...(event.purpose === "compaction" ? { purpose: "compaction" } : {}), itemId: thoughtId }]
|
|
59
62
|
: [];
|
|
60
63
|
case "model.completed": {
|
|
61
64
|
const out = [];
|
|
@@ -79,6 +82,8 @@ export function engineEventToTimeline(event, { runId = "run", time, startedAt =
|
|
|
79
82
|
: [];
|
|
80
83
|
case "tool.completed": {
|
|
81
84
|
if (!text(event.callId)) return [];
|
|
85
|
+
if (event.status === "uncertain") return [{ v, id: id("uncertain"), type: "tool.state",
|
|
86
|
+
callId: event.callId, status: "uncertain" }];
|
|
82
87
|
// Older engines stored the committed TodoWrite receipt but omitted the
|
|
83
88
|
// separate checklist projection. Never infer progress from tool inputs.
|
|
84
89
|
const display = event.status === "ok" ? completedEditDisplay(event) : undefined;
|
|
@@ -91,8 +96,12 @@ export function engineEventToTimeline(event, { runId = "run", time, startedAt =
|
|
|
91
96
|
items: event.result.todos.map((item, index) => ({ ...item, id: `todo:${index}` })) });
|
|
92
97
|
return out;
|
|
93
98
|
}
|
|
94
|
-
case "model.
|
|
95
|
-
return
|
|
99
|
+
case "model.retry_scheduled":
|
|
100
|
+
return Number.isSafeInteger(event.retryAt) && event.retryAt > 0
|
|
101
|
+
? [{ v, id: id("model-wait"), type: "model.wait", retryAt: event.retryAt, httpStatus: event.httpStatus }] : [];
|
|
102
|
+
case "model.retry_exhausted":
|
|
103
|
+
return [{ v, id: id("paused"), type: "task.state", state: "paused", reason: "provider_unavailable",
|
|
104
|
+
message: event.modelError }];
|
|
96
105
|
case "run.terminal": {
|
|
97
106
|
const out = [];
|
|
98
107
|
const itemId = `${runId}:final`;
|
|
@@ -100,8 +109,11 @@ export function engineEventToTimeline(event, { runId = "run", time, startedAt =
|
|
|
100
109
|
out.push({ v, id: id("final"), type: "text.delta", itemId, delta: event.detail }, { v, id: id("final-done"), type: "text.done", itemId });
|
|
101
110
|
}
|
|
102
111
|
if (event.title === "paused") return [...out, { v, id: id("paused"), type: "task.state", state: "paused", reason: event.reason ?? null }];
|
|
112
|
+
if (event.title === "interrupted") return [{ v, id: id("finished"), type: "task.finished",
|
|
113
|
+
outcome: "unverified", executionState: "interrupted", endedAt: time, reason: event.reason }];
|
|
103
114
|
return [...out, { v, id: id("finished"), type: "task.finished", outcome: outcomeOf(event), endedAt: time,
|
|
104
|
-
...(out.length ? { finalAnswerId: itemId } : {}), ...(event.reason ? { reason: event.reason } : {})
|
|
115
|
+
...(out.length ? { finalAnswerId: itemId } : {}), ...(event.reason ? { reason: event.reason } : {}),
|
|
116
|
+
...(text(event.modelError) ? { error: event.modelError } : {}) }];
|
|
105
117
|
}
|
|
106
118
|
default:
|
|
107
119
|
return [];
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { initialState } from '../reducer.mjs';
|
|
2
|
+
|
|
3
|
+
/** Only an exact durable request identity replaces its optimistic bubble.
|
|
4
|
+
* Repeating the same text intentionally remains a distinct user message. */
|
|
5
|
+
export function pendingInputStates(inputs, eventWindow) {
|
|
6
|
+
const candidates = (Array.isArray(inputs) ? inputs : []).filter(item => item?.placement === 'transcript');
|
|
7
|
+
if (!candidates.length) return [];
|
|
8
|
+
const committed = new Set((eventWindow?.entries ?? []).flatMap(entry => {
|
|
9
|
+
const event = entry.event;
|
|
10
|
+
return event?.type === 'user/message' && ['user', 'user-rpc'].includes(event.data?.source?.kind)
|
|
11
|
+
&& typeof event.data.source.rpcId === 'string' ? [event.data.source.rpcId] : [];
|
|
12
|
+
}));
|
|
13
|
+
const seen = new Set();
|
|
14
|
+
return candidates.flatMap(item => {
|
|
15
|
+
if (item?.placement !== 'transcript' || typeof item.requestId !== 'string'
|
|
16
|
+
|| committed.has(item.requestId) || seen.has(item.requestId) || typeof item.text !== 'string') return [];
|
|
17
|
+
seen.add(item.requestId);
|
|
18
|
+
return [{ requestId: item.requestId, state: { ...initialState(), items: [
|
|
19
|
+
{ kind: 'text', id: `pending:${item.requestId}`, role: 'user', text: item.text, streaming: false },
|
|
20
|
+
] } }];
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -121,6 +121,18 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
121
121
|
if (event.type === 'user/message' && ['user', 'user-rpc'].includes(data.source?.kind))
|
|
122
122
|
emit('text.done', { itemId: `user:${data.id ?? event.seq}`, text: textOf(data.content), role: 'user' });
|
|
123
123
|
const engine = engineTurns.get(turn);
|
|
124
|
+
if (event.type === 'agentkit/native-engine-text') {
|
|
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
|
+
|| !/^[\da-f-]{36}:\d{1,16}$/.test(data.cursor) || typeof data.delta !== 'string' || data.delta.length > 8192
|
|
128
|
+
|| !Number.isSafeInteger(data.offset) || data.offset < 0) return;
|
|
129
|
+
const itemId = `${task.modelThinkingId}:text`, previous = task.items.find(item => item.id === itemId && item.preview);
|
|
130
|
+
const prefix = previous?.receivedChars === data.offset ? previous.text : '';
|
|
131
|
+
task = reduce(task, { v: 1, type: 'text.preview', id: `${data.runId}:text:${data.requestId}:${data.cursor}`,
|
|
132
|
+
itemId, responseId: task.modelThinkingId, text: prefix + data.delta, receivedChars: data.offset + data.delta.length });
|
|
133
|
+
tasks.set(turn, task);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
124
136
|
if (event.type === 'agentkit/native-engine-tool-draft') {
|
|
125
137
|
if (event.ignorable !== true || engine?.runId !== data.runId || !task.modelThinkingId
|
|
126
138
|
|| !/^[a-f0-9]{64}$/.test(data.requestId) || task.modelThinkingId !== `${data.runId}:thought:${data.requestId}`
|
|
@@ -186,12 +198,14 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
186
198
|
const message = data.message;
|
|
187
199
|
const text = textOf(message?.content); let value;
|
|
188
200
|
try { value = JSON.parse(text); } catch { /* plain tool result */ }
|
|
201
|
+
const name = task.items.find(item => item.callId === message?.toolCallId)?.name;
|
|
189
202
|
const display = data.meta?.contract === 'agentkit.workspace-display/v1' ? data.meta.display
|
|
190
|
-
: commandDisplay(
|
|
203
|
+
: commandDisplay(name, value);
|
|
204
|
+
const workspaceObservation = (name === 'read_workspace_file' || name === 'search_workspace_files') && value?.ok === true;
|
|
191
205
|
if (dispositions.has(`${turn}:${message?.toolCallId}`)) emit('tool.state', { callId: message.toolCallId, status: 'not_dispatched' });
|
|
192
206
|
else if (uncertainFact(data.meta?.nativeOutcome, message?.toolCallId, turn, sessionId) || value?.status === 'uncertain') emit('tool.state', { callId: message?.toolCallId, status: 'uncertain', message: '执行结果未知,需要核对回执' });
|
|
193
207
|
else emit(message?.isError ? 'tool.error' : 'tool.result', { callId: message?.toolCallId,
|
|
194
|
-
...(message?.isError ? { error: text } : { result: text,
|
|
208
|
+
...(message?.isError ? { error: text } : { result: workspaceObservation ? value : text,
|
|
195
209
|
...(display ? { display } : {}) }) });
|
|
196
210
|
}
|
|
197
211
|
if (event.type === 'turn/end') {
|
|
@@ -199,6 +213,7 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
199
213
|
if (replies.has(turn)) replies.set(turn, { ...replies.get(turn), time: event.time, seq: event.seq,
|
|
200
214
|
branchable: reason?.kind === 'completed' });
|
|
201
215
|
if (engine?.terminal && (task.finalAnswerId || !finalAnswers.get(turn) || reason?.kind !== 'completed')) return;
|
|
216
|
+
if (engine && task.taskState === 'paused' && task.taskReason === 'provider_unavailable' && reason?.kind === 'error') return;
|
|
202
217
|
const interruption = reason?.kind === 'error' && typeof reason.error?.code === 'string'
|
|
203
218
|
&& Object.hasOwn(nativeInterruptionMessages, reason.error.code) ? nativeInterruptionMessages[reason.error.code] : null;
|
|
204
219
|
const outcome = interruption ? 'unverified' : reason?.kind === 'completed' ? 'unverified' : reason?.kind === 'blocked' ? 'blocked'
|
|
@@ -8,6 +8,7 @@ import { nativeTaskWorkspaceRoot, taskWorkspaceFileTarget } from './state/task-l
|
|
|
8
8
|
import { resolveNativeRuntimeRoute, nativeRuntimeRouteInput } from './state/native-runtime-route.mjs';
|
|
9
9
|
import { createNativeTaskReadModel } from './state/native-task-read-model.mjs';
|
|
10
10
|
import { createTimelineEventFeed } from './state/timeline-event-feed.mjs';
|
|
11
|
+
import { pendingInputStates } from './pending-inputs.mjs';
|
|
11
12
|
import { createSessionTaskProjector, nativeTaskState, nativeStatusForTurn, bindNativeSubagents, nativeHistoricalToolState } from './session-task-events.mjs';
|
|
12
13
|
|
|
13
14
|
const labels = { result: '执行结果', thought: '思考', running: '执行中', thinking: '思考中…', ended: '本轮已结束', contextRunning: '正在压缩上下文', contextCompleted: '上下文已自动压缩',
|
|
@@ -16,7 +17,9 @@ const labels = { result: '执行结果', thought: '思考', running: '执行中'
|
|
|
16
17
|
waiting: '等待确认或回执', paused: '已暂停', toolScheduled: '排队中', toolRunning: '执行中', toolCompleted: '已返回',
|
|
17
18
|
toolFailed: '执行失败', toolUncertain: '执行结果未知', toolNotDispatched: '未执行', jumpLatest: '回到最新',
|
|
18
19
|
readKind: '读取', readReading: '读取中', listKind: '列出文件', listSearching: '列出文件中', searchKind: '搜索', searchSearching: '搜索中',
|
|
19
|
-
|
|
20
|
+
searchQuery: '搜索词', searchScope: '搜索范围', searchGlob: '文件匹配规则', searchMatches: '返回命中数', searchResultsTruncated: '部分命中位置已省略',
|
|
21
|
+
readPath: '文件路径', readLines: '已读取行', readRequestedLines: '请求读取行', readOffset: '起始偏移', readLimit: '读取上限',
|
|
22
|
+
readFromLine: '从第 {line} 行开始', readThroughLine: '截至第 {line} 行', readNoLines: '未返回文本行',
|
|
20
23
|
copy: '复制', openFile: '打开文件', openTerminal: '查看终端输出', noOutput: '没有输出', inspect: '查看详情',
|
|
21
24
|
expandCommand: '展开命令', collapseCommand: '收起命令',
|
|
22
25
|
toolDetails: '工具详情', close: '关闭', state: '状态', arguments: '调用参数', noSettledResult: '尚无已确认的结果', appliedChanges: '实际文件变更',
|
|
@@ -41,7 +44,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
41
44
|
onOpenFileLink: onOpenFile && (({ href }) => { const target = taskWorkspaceFileTarget(href, cwd); if (target) onOpenFile(target); }) }, text) });
|
|
42
45
|
const markdownLabels = { copyCode: '复制代码', copied: '已复制', wrapLines: '自动换行', languageLabel: '代码' };
|
|
43
46
|
function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile, openExternalLink,
|
|
44
|
-
branchAt, renderAssistantActions, turnAnchors, fallback, statusPanel }) {
|
|
47
|
+
branchAt, renderAssistantActions, turnAnchors, pendingInputs, fallback, statusPanel }) {
|
|
45
48
|
const [variant, setVariant] = useState(() => {
|
|
46
49
|
try { const saved = localStorage.getItem('native.status-panel.variant'); return ['auto', 'mini', 'panel'].includes(saved) ? saved : 'auto'; }
|
|
47
50
|
catch { return 'auto'; }
|
|
@@ -182,7 +185,10 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
182
185
|
onCopyCode: text => navigator.clipboard.writeText(text),
|
|
183
186
|
onOpenExternalUrl: openExternalLink ?? (url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); }),
|
|
184
187
|
onOpenFileLink: ({ href }) => openWorkspaceFile(href) }, text) })),
|
|
185
|
-
...(
|
|
188
|
+
...pendingInputStates(pendingInputs ?? pending, eventWindow).map(({ requestId, state }) => h(HarnessTurn, {
|
|
189
|
+
key: `pending:${requestId}`, state, labels, locale: 'zh-CN', showPlanDock: false, theme: theme.active.colorScheme,
|
|
190
|
+
containerProps: { 'aria-label': '待发送输入', 'data-pending-request-id': requestId },
|
|
191
|
+
})),
|
|
186
192
|
error ? h('p', { role: 'alert' }, error) : null,
|
|
187
193
|
status?.canResume ? h('button', { type: 'button', onClick: () => void resume() }, '恢复原任务') : null);
|
|
188
194
|
|
package/src/protocol.mjs
CHANGED
|
@@ -22,8 +22,10 @@ export const EventType = Object.freeze({
|
|
|
22
22
|
TaskState: "task.state",
|
|
23
23
|
TaskFinished: "task.finished",
|
|
24
24
|
ModelRequest: "model.request",
|
|
25
|
+
ModelWait: "model.wait",
|
|
25
26
|
TextDelta: "text.delta",
|
|
26
27
|
TextDone: "text.done",
|
|
28
|
+
TextPreview: "text.preview",
|
|
27
29
|
ThinkingStart: "thinking.start",
|
|
28
30
|
ThinkingDelta: "thinking.delta",
|
|
29
31
|
ThinkingDone: "thinking.done",
|
|
@@ -150,7 +152,7 @@ export function normalizeEvent(event) {
|
|
|
150
152
|
const base = { v, type, id, ts: typeof event.ts === "number" ? event.ts : null, seq: typeof event.seq === "number" ? event.seq : null };
|
|
151
153
|
// Optional presentation lineage, supplied by the Host's response boundary.
|
|
152
154
|
// It is never a Run identity, tool claim or an execution permission.
|
|
153
|
-
if (['text.delta', 'text.done', 'thinking.delta', 'thinking.done', 'tool.preview', 'tool.scheduled'].includes(type)
|
|
155
|
+
if (['text.preview', 'text.delta', 'text.done', 'thinking.delta', 'thinking.done', 'tool.preview', 'tool.scheduled'].includes(type)
|
|
154
156
|
&& typeof event.responseId === 'string' && event.responseId.length > 0 && event.responseId.length <= 1024)
|
|
155
157
|
base.responseId = event.responseId;
|
|
156
158
|
return Object.assign(base, normalizePayload(type, event));
|
|
@@ -163,9 +165,13 @@ function normalizePayload(type, event) {
|
|
|
163
165
|
...(hostTime(event.startedAt) !== null ? { startedAt: event.startedAt } : {}) };
|
|
164
166
|
case EventType.TaskState:
|
|
165
167
|
return { state: requiredChoice(event.state, TASK_STATES, "task state"), reason: str(event.reason) || null, message: str(event.message) || null };
|
|
168
|
+
case EventType.ModelWait:
|
|
169
|
+
if (!Number.isSafeInteger(event.retryAt) || event.retryAt <= 0) throw new TypeError('model wait requires a committed deadline');
|
|
170
|
+
return { retryAt: event.retryAt, ...(Number.isSafeInteger(event.httpStatus) ? { httpStatus: event.httpStatus } : {}) };
|
|
166
171
|
case EventType.ModelRequest:
|
|
167
172
|
if (typeof event.active !== "boolean") throw new TypeError("model request requires an active flag");
|
|
168
|
-
return { active: event.active, itemId: str(event.itemId) }
|
|
173
|
+
return { active: event.active, itemId: str(event.itemId), ...(event.retry === true ? { retry: true } : {}),
|
|
174
|
+
...(event.purpose === "compaction" ? { purpose: "compaction" } : {}) };
|
|
169
175
|
case EventType.TaskFinished: {
|
|
170
176
|
const outcome = requiredChoice(event.outcome, TASK_OUTCOMES, "task outcome");
|
|
171
177
|
if (event.executionState !== undefined && (event.executionState !== TaskState.Interrupted || outcome !== TaskOutcome.Unverified))
|
|
@@ -176,6 +182,9 @@ function normalizePayload(type, event) {
|
|
|
176
182
|
...(event.executionState === TaskState.Interrupted ? { executionState: TaskState.Interrupted } : {}),
|
|
177
183
|
verificationRequired: typeof event.verificationRequired === 'boolean' ? event.verificationRequired : null };
|
|
178
184
|
}
|
|
185
|
+
case EventType.TextPreview:
|
|
186
|
+
return { itemId: str(event.itemId), text: str(event.text).slice(-128 * 1024),
|
|
187
|
+
...(Number.isSafeInteger(event.receivedChars) && event.receivedChars >= 0 ? { receivedChars: event.receivedChars } : {}) };
|
|
179
188
|
case EventType.TextDelta:
|
|
180
189
|
return { itemId: str(event.itemId), delta: str(event.delta) };
|
|
181
190
|
case EventType.TextDone:
|
package/src/react-binding.mjs
CHANGED
|
@@ -483,7 +483,7 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
483
483
|
}
|
|
484
484
|
|
|
485
485
|
|
|
486
|
-
function WebDelivery({ path, seq, resolve, zh }) {
|
|
486
|
+
function WebDelivery({ path, seq, resolve, zh, application = false }) {
|
|
487
487
|
const [preview, setPreview] = useState(null);
|
|
488
488
|
const [pending, setPending] = useState(false);
|
|
489
489
|
const [failed, setFailed] = useState(false);
|
|
@@ -491,13 +491,13 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
491
491
|
useEffect(() => {
|
|
492
492
|
const controller = new AbortController();
|
|
493
493
|
lifetime.current = controller;
|
|
494
|
-
void resolve({ path, seq }, controller.signal).then(delivery => {
|
|
494
|
+
void resolve({ path, seq, application }, controller.signal).then(delivery => {
|
|
495
495
|
if (!controller.signal.aborted) setPreview(delivery);
|
|
496
496
|
}).catch(() => {});
|
|
497
497
|
return () => controller.abort();
|
|
498
|
-
}, [path, seq, resolve]);
|
|
498
|
+
}, [path, seq, resolve, application]);
|
|
499
499
|
if (!preview?.href) return null;
|
|
500
|
-
const filename = path.split('/').at(-1);
|
|
500
|
+
const filename = application ? (zh ? '运行中的应用' : 'Running application') : path.split('/').at(-1);
|
|
501
501
|
const openLabel = zh ? `打开 ${filename}` : `Open ${filename}`;
|
|
502
502
|
const openSidebar = async () => {
|
|
503
503
|
const signal = lifetime.current.signal;
|
|
@@ -517,7 +517,7 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
517
517
|
createElement('path', { d: 'M3 12h18' }))),
|
|
518
518
|
createElement('span', { className: 'harness-delivery-name' },
|
|
519
519
|
createElement('strong', { title: path }, filename),
|
|
520
|
-
createElement('small', null, zh ? '网站 · HTML' : 'Website · HTML')),
|
|
520
|
+
createElement('small', null, application ? path : zh ? '网站 · HTML' : 'Website · HTML')),
|
|
521
521
|
preview.openInSidebar ? createElement('div', { className: 'harness-delivery-actions' },
|
|
522
522
|
createElement('button', { type: 'button', disabled: pending, onClick: openSidebar, 'aria-label': openLabel },
|
|
523
523
|
pending ? (zh ? '正在打开…' : 'Opening…') : (zh ? '打开' : 'Open')),
|
|
@@ -530,17 +530,17 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
530
530
|
: newTab(zh ? '打开' : 'Open', openLabel));
|
|
531
531
|
}
|
|
532
532
|
|
|
533
|
-
function DeliveryEvidence({ seq, load, openFile, zh }) {
|
|
533
|
+
function DeliveryEvidence({ seq, load, openFile, resolveWebDelivery, deliveries, zh }) {
|
|
534
534
|
const [evidence, setEvidence] = useState(null);
|
|
535
535
|
useEffect(() => {
|
|
536
536
|
const controller = new AbortController();
|
|
537
|
+
if (!load || seq === undefined) return;
|
|
537
538
|
void load(seq, controller.signal).then(value => {
|
|
538
539
|
if (!controller.signal.aborted) setEvidence(value);
|
|
539
540
|
}).catch(() => {});
|
|
540
541
|
return () => controller.abort();
|
|
541
542
|
}, [seq, load]);
|
|
542
|
-
|
|
543
|
-
const { files, screenshots, truncated } = evidence;
|
|
543
|
+
const { files = [], screenshots = [], truncated, application } = evidence ?? {};
|
|
544
544
|
const counts = file => Number.isSafeInteger(file.added) && file.added >= 0
|
|
545
545
|
&& Number.isSafeInteger(file.removed) && file.removed >= 0;
|
|
546
546
|
const delta = (added, removed) => createElement('span', { className: 'harness-delivery-delta' },
|
|
@@ -550,6 +550,10 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
550
550
|
const label = zh ? `${files.length}${truncated ? '+' : ''} 个文件已更改`
|
|
551
551
|
: `${files.length}${truncated ? '+' : ''} ${files.length === 1 ? 'file' : 'files'} changed`;
|
|
552
552
|
return createElement(React.Fragment, null,
|
|
553
|
+
...(resolveWebDelivery ? [
|
|
554
|
+
...(application ? [{ path: application.path, seq, application: true }] : []),
|
|
555
|
+
...(deliveries ?? []).filter(delivery => delivery.path !== application?.path),
|
|
556
|
+
].map(delivery => createElement(WebDelivery, { key: delivery.path, ...delivery, resolve: resolveWebDelivery, zh })) : []),
|
|
553
557
|
files.length ? createElement('details', { className: 'harness-delivery-changes', 'data-testid': 'delivery-changes' },
|
|
554
558
|
createElement('summary', null, label, total),
|
|
555
559
|
createElement('ul', null, ...files.map(file => createElement('li', { key: file.path },
|
|
@@ -583,11 +587,12 @@ function ScrollEnd({ reducedMotion, renderChildren, type, props }) {
|
|
|
583
587
|
return createElement('article', { ...containerProps, className: 'harness-turn', 'data-testid': 'harness-turn' },
|
|
584
588
|
createElement(HarnessTimeline, { state, onCopy, locale, ...timeline }),
|
|
585
589
|
state.taskState === 'failed' && state.taskError
|
|
586
|
-
? createElement('p', { className: 'harness-turn-error', role: 'alert' }, state.taskError)
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
answer?.kind === 'text' && !answer.streaming &&
|
|
590
|
-
? createElement(DeliveryEvidence, { key: deliverySeq, seq: deliverySeq, load: loadDeliveryEvidence,
|
|
590
|
+
? createElement('p', { className: 'harness-turn-error', role: 'alert' }, state.taskError)
|
|
591
|
+
: state.taskState === 'paused' && state.taskReason === 'provider_unavailable' && state.taskMessage
|
|
592
|
+
? createElement('p', { className: 'harness-turn-model-pause', role: 'status' }, state.taskMessage) : null,
|
|
593
|
+
answer?.kind === 'text' && !answer.streaming && (resolveWebDelivery || loadDeliveryEvidence)
|
|
594
|
+
? createElement(DeliveryEvidence, { key: deliverySeq, seq: deliverySeq, load: loadDeliveryEvidence, deliveries,
|
|
595
|
+
openFile: timeline.onOpenFile, resolveWebDelivery, zh }) : null,
|
|
591
596
|
answer?.kind === 'text' && !answer.streaming ? createElement('div', { className: 'harness-reply-actions',
|
|
592
597
|
role: 'group', 'aria-label': zh ? '回复操作' : 'Reply actions' },
|
|
593
598
|
button(copyLabel, copy, copyState === 'copied' ? 'm5 12 4 4L19 6' : 'M8 8h11v12H8zM5 16H4V4h11v1'),
|
package/src/reducer.mjs
CHANGED
|
@@ -34,6 +34,9 @@ export function initialState() {
|
|
|
34
34
|
taskStartedAt: null, taskEndedAt: null, finalAnswerId: null,
|
|
35
35
|
verificationRequired: null,
|
|
36
36
|
modelRequestActive: false,
|
|
37
|
+
modelRequestRetry: false,
|
|
38
|
+
modelRequestPurpose: null,
|
|
39
|
+
modelWait: null,
|
|
37
40
|
modelThinkingId: null,
|
|
38
41
|
contextMarkers: [],
|
|
39
42
|
subagents: new Map(),
|
|
@@ -87,11 +90,28 @@ function apply(state, e) {
|
|
|
87
90
|
case EventType.TaskStarted: return applyTaskStarted(state, e);
|
|
88
91
|
case EventType.TaskState: return applyTaskState(state, e);
|
|
89
92
|
case EventType.TaskFinished: return applyTaskFinished(state, e);
|
|
93
|
+
case EventType.ModelWait:
|
|
94
|
+
if (state.taskState === TaskState.Running) state.modelWait = { retryAt: e.retryAt, httpStatus: e.httpStatus };
|
|
95
|
+
return;
|
|
90
96
|
case EventType.ModelRequest:
|
|
97
|
+
if (e.active) state.modelWait = null;
|
|
98
|
+
if (e.active && state.taskState === TaskState.Paused && state.taskReason === 'provider_unavailable')
|
|
99
|
+
applyTaskState(state, { state: TaskState.Running, reason: null, message: null });
|
|
91
100
|
if (!e.active || state.modelThinkingId !== e.itemId) settleModelPresentation(state);
|
|
92
101
|
state.modelRequestActive = e.active;
|
|
102
|
+
state.modelRequestRetry = e.active && e.retry === true;
|
|
103
|
+
state.modelRequestPurpose = e.active ? e.purpose ?? null : null;
|
|
93
104
|
state.modelThinkingId = e.active ? e.itemId : null;
|
|
94
105
|
return;
|
|
106
|
+
case EventType.TextPreview: {
|
|
107
|
+
if (!state.modelRequestActive || !e.responseId || e.responseId !== state.modelThinkingId || !e.itemId || !e.text) return;
|
|
108
|
+
const index = findItemIndex(state, e.itemId);
|
|
109
|
+
if (index >= 0 && !state.items[index].preview) return;
|
|
110
|
+
settlePriorReasoning(state, e);
|
|
111
|
+
const item = { kind: 'text', id: e.itemId, text: e.text, responseId: e.responseId, streaming: true, preview: true, receivedChars: e.receivedChars };
|
|
112
|
+
if (index >= 0) state.items[index] = item; else state.items.push(item);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
95
115
|
case EventType.TextDelta: return applyTextDelta(state, e);
|
|
96
116
|
case EventType.TextDone: return applyTextDone(state, e);
|
|
97
117
|
case EventType.ThinkingStart: return applyThinkingStart(state, e);
|
|
@@ -152,7 +172,7 @@ function applyTaskStarted(state, e) {
|
|
|
152
172
|
function settleModelPresentation(state) {
|
|
153
173
|
if (!state.modelThinkingId) return;
|
|
154
174
|
applyThinkingDone(state, { itemId: state.modelThinkingId });
|
|
155
|
-
state.items = state.items.filter(item => item.kind
|
|
175
|
+
state.items = state.items.filter(item => !(item.kind === 'tool-preview' || item.preview === true) || item.responseId !== state.modelThinkingId);
|
|
156
176
|
}
|
|
157
177
|
|
|
158
178
|
function applyTaskState(state, e) {
|
|
@@ -160,7 +180,10 @@ function applyTaskState(state, e) {
|
|
|
160
180
|
state.taskState = e.state;
|
|
161
181
|
if (e.state !== TaskState.Running) {
|
|
162
182
|
settleModelPresentation(state);
|
|
183
|
+
state.modelWait = null;
|
|
163
184
|
state.modelRequestActive = false;
|
|
185
|
+
state.modelRequestRetry = false;
|
|
186
|
+
state.modelRequestPurpose = null;
|
|
164
187
|
state.modelThinkingId = null;
|
|
165
188
|
}
|
|
166
189
|
state.taskReason = e.reason;
|
|
@@ -173,7 +196,10 @@ function applyTaskState(state, e) {
|
|
|
173
196
|
|
|
174
197
|
function applyTaskFinished(state, e) {
|
|
175
198
|
settleModelPresentation(state);
|
|
199
|
+
state.modelWait = null;
|
|
176
200
|
state.modelRequestActive = false;
|
|
201
|
+
state.modelRequestRetry = false;
|
|
202
|
+
state.modelRequestPurpose = null;
|
|
177
203
|
state.modelThinkingId = null;
|
|
178
204
|
state.verificationRequired = e.verificationRequired;
|
|
179
205
|
state.taskOutcome = e.outcome;
|
package/src/renderers.mjs
CHANGED
|
@@ -4,8 +4,7 @@
|
|
|
4
4
|
// renderers that mirror the ZCode DESKTOP task conversation:
|
|
5
5
|
// - execute (terminal): `$` prompt + bounded command, live output with
|
|
6
6
|
// stdout/stderr/exit/cwd, safe-ANSI plain text, copy + open-terminal actions
|
|
7
|
-
// - read:
|
|
8
|
-
// not toggleable
|
|
7
|
+
// - read/search: compact summaries with expandable file and search details
|
|
9
8
|
// - edit: file chips, +N/-N change count, inline diff with REAL line numbers
|
|
10
9
|
// from the patch hunk headers, unified + split responsive, bounded preview
|
|
11
10
|
// with a full-retrieval callback; never infers a write succeeded from input
|
|
@@ -18,12 +17,12 @@
|
|
|
18
17
|
|
|
19
18
|
import { h, terminalIcon, fileTextIcon, searchIcon, pencilIcon, wrenchIcon, chevronIcon, skillIcon, globeIcon } from "./view.mjs";
|
|
20
19
|
import { ToolStatus } from "./protocol.mjs";
|
|
21
|
-
import { toolTitle, toolDetailLines, toolInputPreview,
|
|
20
|
+
import { toolTitle, toolDetailLines, toolInputPreview, redactError } from "./tool-detail.mjs";
|
|
22
21
|
import { truncateText, latestNonEmptyLine, redactValue, boundedDetailLines } from "./summary.mjs";
|
|
23
22
|
import { parseDiffHunks, countChangeStat, inferOperationKind } from "./diff.mjs";
|
|
24
23
|
import { extractCommand, extractOutput } from "./terminal.mjs";
|
|
25
24
|
import { toolIdentity, localizedToolTitle } from './tool-identity.mjs';
|
|
26
|
-
import { toolErrorSummary } from './tool-error.mjs';
|
|
25
|
+
import { commandPolicyBlockReason, isCommandPolicyBlock, toolErrorSummary } from './tool-error.mjs';
|
|
27
26
|
|
|
28
27
|
/** Tool-name → renderer classification. Host tool names vary across runtimes. */
|
|
29
28
|
|
|
@@ -84,17 +83,15 @@ const toolIsLive = item => item.kind === 'tool-preview' ? item.streaming === tru
|
|
|
84
83
|
* own title span), the primary/secondary content, the status word, and a
|
|
85
84
|
* chevron that rotates when the body is open.
|
|
86
85
|
*
|
|
87
|
-
*
|
|
88
|
-
* search that cannot expand still surfaces its redacted error inline in the
|
|
89
|
-
* summary (role=alert), so the failure is never hidden behind a missing toggle.
|
|
86
|
+
* Policy-blocked commands put the reason inside the disclosure.
|
|
90
87
|
*/
|
|
91
|
-
function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultOpen, actions = [], summaryAction }) {
|
|
88
|
+
function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultOpen, actions = [], summaryAction, commandBlocked = false }) {
|
|
92
89
|
const status = item.status;
|
|
93
90
|
const provisional = item.kind === 'tool-preview';
|
|
94
91
|
const streaming = toolIsLive(item);
|
|
95
92
|
if (provisional) { canToggle = false; summaryAction = undefined; actions = []; }
|
|
96
93
|
const error = status === ToolStatus.Failed && item.error ? redactError(item.error) : null;
|
|
97
|
-
// Plain static
|
|
94
|
+
// Plain static failures are already fully visible inline. Structured
|
|
98
95
|
// failures retain a disclosure for the original bounded diagnostic evidence.
|
|
99
96
|
if (error && !canToggle && toolErrorSummary(item.error, opts) !== error) { canToggle = true; defaultOpen = false; }
|
|
100
97
|
const open = resolveOpen(item, opts, defaultOpen == null ? streaming : defaultOpen, canToggle);
|
|
@@ -105,7 +102,7 @@ function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultO
|
|
|
105
102
|
const errorSummary = error ? toolErrorSummary(item.error, opts) : null;
|
|
106
103
|
// Non-toggleable tools have no body to expand into, so their error must live
|
|
107
104
|
// in the summary; toggleable tools show it inline only when collapsed.
|
|
108
|
-
const showInlineError = error && (canToggle ? !open : true);
|
|
105
|
+
const showInlineError = error && !commandBlocked && (canToggle ? !open : true);
|
|
109
106
|
if (showInlineError) summaryKids.push(h("span", {
|
|
110
107
|
className: "harness-tool-error harness-tool-error-inline",
|
|
111
108
|
role: "alert",
|
|
@@ -115,16 +112,18 @@ function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultO
|
|
|
115
112
|
className: `harness-tool-status harness-tool-status-${status}`,
|
|
116
113
|
"data-testid": "tool-status",
|
|
117
114
|
"data-status": status,
|
|
118
|
-
}, statusLabel(status, opts)));
|
|
115
|
+
}, commandBlocked ? (String(opts.locale).startsWith("zh") ? "未执行" : "Not executed") : statusLabel(status, opts)));
|
|
119
116
|
for (const action of actions) {
|
|
120
117
|
if (action) summaryKids.push(action);
|
|
121
118
|
}
|
|
122
119
|
if (canToggle) summaryKids.push(chevronIcon("harness-tool-chevron"));
|
|
123
120
|
const visibleBody = open && canToggle ? (typeof body === 'function' ? body() : body) : [];
|
|
124
121
|
const bodyKids = Array.isArray(visibleBody) ? visibleBody : [visibleBody];
|
|
122
|
+
const blockedReason = commandBlocked ? commandPolicyBlockReason(item.error) : null;
|
|
125
123
|
if (error && open && canToggle) bodyKids.unshift(h("div", {
|
|
126
124
|
className: "harness-tool-error", role: "alert", "data-testid": "tool-error",
|
|
127
|
-
},
|
|
125
|
+
}, commandBlocked ? [errorSummary, blockedReason ? h("div", {}, blockedReason) : null]
|
|
126
|
+
: errorSummary === error ? error : [errorSummary, h("div", {}, error)]));
|
|
128
127
|
const detailsProps = canToggle ? {
|
|
129
128
|
open, className: "harness-tool-details", "data-testid": "tool-details",
|
|
130
129
|
"data-call-id": item.callId, "aria-expanded": open,
|
|
@@ -201,6 +200,7 @@ function executeRenderer(item, opts) {
|
|
|
201
200
|
// One extractor handles both normalized event displays (fullText) and
|
|
202
201
|
// Host observation snapshots (stdout/stderr). An empty alias must not hide
|
|
203
202
|
// real streaming bytes supplied through the other supported representation.
|
|
203
|
+
const commandBlocked = item.status === ToolStatus.Failed && isCommandPolicyBlock(item.error);
|
|
204
204
|
const stdout = out.stdout;
|
|
205
205
|
const hasOutput = Boolean(stdout || out.stderr || out.exit != null);
|
|
206
206
|
const title = localizedToolTitle(item.name, toolTitle(item.name, item.input) || item.name, opts.locale);
|
|
@@ -217,7 +217,7 @@ function executeRenderer(item, opts) {
|
|
|
217
217
|
}, truncateText(command, { maxLines: 1, maxChars: 80 })));
|
|
218
218
|
|
|
219
219
|
const body = [commandBlock(item.callId, command, cwd, opts),
|
|
220
|
-
outputBlock(item.callId, { stdout, stderr: out.stderr, exit: out.exit, cwd, running, hasOutput }, opts)];
|
|
220
|
+
commandBlocked ? null : outputBlock(item.callId, { stdout, stderr: out.stderr, exit: out.exit, cwd, running, hasOutput }, opts)];
|
|
221
221
|
// A host progress message (e.g. "running 4 tests") is shown as a live status
|
|
222
222
|
// line under the command, above the output. The reducer never invents it.
|
|
223
223
|
if (item.progress && item.status !== ToolStatus.Completed) {
|
|
@@ -228,7 +228,7 @@ function executeRenderer(item, opts) {
|
|
|
228
228
|
}, item.progress));
|
|
229
229
|
}
|
|
230
230
|
|
|
231
|
-
return toolShell(item, opts, { icon: terminalIcon("harness-tool-kind-icon"), summary, body, canToggle: true, defaultOpen: false });
|
|
231
|
+
return toolShell(item, opts, { icon: terminalIcon("harness-tool-kind-icon"), summary, body, canToggle: true, defaultOpen: false, commandBlocked });
|
|
232
232
|
}
|
|
233
233
|
|
|
234
234
|
function commandBlock(callId, command, cwd, opts) {
|
|
@@ -301,12 +301,6 @@ function copyButton(opts, text, testid) {
|
|
|
301
301
|
|
|
302
302
|
// ── read / search / list ─────────────────────────────────────────────────────
|
|
303
303
|
//
|
|
304
|
-
// The desktop conversation splits "file-read" (ReadToolCallBlock: a file chip)
|
|
305
|
-
// from "search" (SearchToolCallBlock: "Find {query}" / "List {cwd}"). Both are
|
|
306
|
-
// non-toggleable one-line summaries. The path is shown once (leaf in the chip +
|
|
307
|
-
// the workspace-relative path as secondary, full path only in the chip title)
|
|
308
|
-
// rather than repeated across the title, the chip, and a third path line.
|
|
309
|
-
|
|
310
304
|
function readRenderer(item, opts) {
|
|
311
305
|
return readSubKind(item.name, item.input) === "search"
|
|
312
306
|
? searchListRenderer(item, opts)
|
|
@@ -316,13 +310,11 @@ function readRenderer(item, opts) {
|
|
|
316
310
|
function readFileRenderer(item, opts) {
|
|
317
311
|
const meta = readMeta(item);
|
|
318
312
|
const path = meta.path;
|
|
319
|
-
const fileName = leafName(path) ||
|
|
313
|
+
const fileName = leafName(path) || path;
|
|
320
314
|
const running = toolIsLive(item);
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const canOpen = Boolean(opts.onOpenFile) && meta.entryType === "file";
|
|
325
|
-
// Show the file chip once. Keep relative context for nested files.
|
|
315
|
+
const labels = opts.labels || {};
|
|
316
|
+
const kindLabel = running ? labels.readReading || "Reading" : labels.readKind || "Read";
|
|
317
|
+
const canOpen = meta.entryType === "file" && Boolean(opts.onOpenFile);
|
|
326
318
|
const summary = [
|
|
327
319
|
h("span", {
|
|
328
320
|
className: running
|
|
@@ -330,24 +322,48 @@ function readFileRenderer(item, opts) {
|
|
|
330
322
|
: "harness-tool-title",
|
|
331
323
|
"data-testid": "tool-title",
|
|
332
324
|
}, kindLabel),
|
|
333
|
-
|
|
334
|
-
|
|
325
|
+
path ? h("span", { className: "harness-tool-secondary", "aria-hidden": "true" }, "·") : null,
|
|
326
|
+
path ? fileChip(path, fileName, canOpen, opts, "read-chip", "read-file-name",
|
|
327
|
+
{ kind: meta.entryType, callId: item.callId, showIcon: false }) : null,
|
|
328
|
+
];
|
|
329
|
+
const result = item.result;
|
|
330
|
+
const readRange = result?.line_count === 0
|
|
331
|
+
? labels.readNoLines || "No lines returned"
|
|
332
|
+
: formatReadRange(result?.read_range?.start ?? result?.start_line, result?.read_range?.end ?? result?.end_line, labels);
|
|
333
|
+
const requestedRange = formatReadRange(item.input?.start_line, item.input?.end_line, labels);
|
|
334
|
+
const rows = [
|
|
335
|
+
[labels.readPath || "Path", path, "read-file-path"],
|
|
336
|
+
readRange
|
|
337
|
+
? [labels.readLines || "Lines read", readRange, "read-line-range"]
|
|
338
|
+
: [labels.readRequestedLines || "Requested lines", requestedRange, "read-line-range"],
|
|
339
|
+
...(!readRange && !requestedRange ? [
|
|
340
|
+
[labels.readOffset || "Offset", item.input?.offset, "read-offset"],
|
|
341
|
+
[labels.readLimit || "Limit", item.input?.limit, "read-limit"],
|
|
342
|
+
] : []),
|
|
335
343
|
];
|
|
336
|
-
const relativePath = path ? workspaceRelative(path, opts.workspaceRoot) : "";
|
|
337
|
-
if (relativePath && relativePath !== fileName) summary.push(h("span", {
|
|
338
|
-
className: "harness-tool-secondary harness-read-path",
|
|
339
|
-
"data-testid": "read-file-path",
|
|
340
|
-
title: path,
|
|
341
|
-
}, relativePath));
|
|
342
|
-
// Read is a one-line chip; it does not toggle. A failed read surfaces its
|
|
343
|
-
// error inline via the shell, and an optional inspect action lets the host
|
|
344
|
-
// open the result/details (the public result-inspection action).
|
|
345
344
|
return toolShell(item, opts, {
|
|
346
345
|
icon: fileTextIcon("harness-tool-kind-icon"),
|
|
347
|
-
summary, body:
|
|
346
|
+
summary, body: () => observationDetails(rows), defaultOpen: false,
|
|
347
|
+
canToggle: Boolean(path || readRange || requestedRange || item.error || item.input?.offset != null || item.input?.limit != null),
|
|
348
348
|
});
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
+
function formatReadRange(start, end, labels) {
|
|
352
|
+
const hasStart = Number.isSafeInteger(start) && start > 0;
|
|
353
|
+
const hasEnd = Number.isSafeInteger(end) && end > 0;
|
|
354
|
+
if (hasStart && hasEnd) return start === end ? String(start) : `${start}–${end}`;
|
|
355
|
+
if (hasStart) return (labels.readFromLine || "From line {line}").replace("{line}", start);
|
|
356
|
+
if (hasEnd) return (labels.readThroughLine || "Through line {line}").replace("{line}", end);
|
|
357
|
+
return "";
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function observationDetails(rows) {
|
|
361
|
+
return h("dl", { className: "harness-tool-detail" }, rows
|
|
362
|
+
.filter(([, value]) => typeof value === "string" ? value.length > 0 : Number.isSafeInteger(value))
|
|
363
|
+
.map(([label, value, id]) => h("div", { className: "harness-tool-detail-line", key: id },
|
|
364
|
+
h("dt", {}, label), h("dd", { "data-testid": id }, String(value)))));
|
|
365
|
+
}
|
|
366
|
+
|
|
351
367
|
function searchListRenderer(item, opts) {
|
|
352
368
|
const running = toolIsLive(item);
|
|
353
369
|
const isList = isListInput(item.name, item.input);
|
|
@@ -357,10 +373,7 @@ function searchListRenderer(item, opts) {
|
|
|
357
373
|
const kindLabel = running
|
|
358
374
|
? (isList ? (labels.listSearching || "Listing") : (labels.searchSearching || "Searching"))
|
|
359
375
|
: (isList ? (labels.listKind || "List") : (labels.searchKind || "Search"));
|
|
360
|
-
const primary = isList
|
|
361
|
-
? (cwd ? truncateText(cwd, { maxLines: 1, maxChars: 60 }) : '')
|
|
362
|
-
: (query ? (labels.searchFindQuery || "Find {query}").replace("{query}", truncateText(query, { maxLines: 1, maxChars: 80 }))
|
|
363
|
-
: (labels.searchFind || "Find"));
|
|
376
|
+
const primary = truncateText(isList ? cwd : query, { maxLines: 1, maxChars: isList ? 60 : 80 });
|
|
364
377
|
const summary = [
|
|
365
378
|
h("span", {
|
|
366
379
|
className: running
|
|
@@ -368,17 +381,44 @@ function searchListRenderer(item, opts) {
|
|
|
368
381
|
: "harness-tool-title",
|
|
369
382
|
"data-testid": "tool-title",
|
|
370
383
|
}, kindLabel),
|
|
371
|
-
...(
|
|
384
|
+
...(!isList && primary ? [h("span", { className: "harness-tool-secondary", "aria-hidden": "true" }, "·")] : []),
|
|
385
|
+
...(primary ? [h("span", {
|
|
372
386
|
className: "harness-tool-primary harness-search-primary",
|
|
373
387
|
"data-testid": "search-primary",
|
|
374
388
|
}, primary)] : []),
|
|
375
389
|
];
|
|
376
390
|
return toolShell(item, opts, {
|
|
377
391
|
icon: searchIcon("harness-tool-kind-icon"),
|
|
378
|
-
summary, body:
|
|
392
|
+
summary, body: () => searchDetails(item, query, cwd, labels), defaultOpen: false,
|
|
393
|
+
canToggle: !isList && Boolean(query || cwd || item.result != null || item.error),
|
|
379
394
|
});
|
|
380
395
|
}
|
|
381
396
|
|
|
397
|
+
function searchDetails(item, query, cwd, labels) {
|
|
398
|
+
const result = item.result;
|
|
399
|
+
const nativeSearch = item.name === "search_workspace_files";
|
|
400
|
+
const scope = result?.searched_path || cwd || (nativeSearch ? "." : "");
|
|
401
|
+
const locations = Array.isArray(result?.results) ? result.results
|
|
402
|
+
.filter(hit => typeof hit?.path === "string" && hit.path && Number.isSafeInteger(hit.line) && hit.line > 0) : [];
|
|
403
|
+
const count = Number.isSafeInteger(result?.match_count) ? result.match_count : null;
|
|
404
|
+
const shown = locations.slice(0, 12);
|
|
405
|
+
const legacyResult = typeof result === "string" ? redactError(result, { maxChars: 600 }) : "";
|
|
406
|
+
return [
|
|
407
|
+
observationDetails([
|
|
408
|
+
[labels.searchQuery || "Query", truncateText(query, { maxLines: 3, maxChars: 512 }), "search-query"],
|
|
409
|
+
[labels.searchScope || "Scope", scope, "search-scope"],
|
|
410
|
+
[labels.searchGlob || "File pattern", item.input?.glob, "search-glob"],
|
|
411
|
+
[labels.searchMatches || "Matches returned", count, "search-match-count"],
|
|
412
|
+
]),
|
|
413
|
+
shown.length ? h("ul", { className: "harness-search-matches", "data-testid": "search-matches" },
|
|
414
|
+
shown.map(({ path, line }, index) => h("li", { key: index }, `${path}:${line}`))) : null,
|
|
415
|
+
(result?.locations_truncated ?? result?.truncated) === true || (count ?? locations.length) > shown.length
|
|
416
|
+
? h("div", { className: "harness-tool-secondary", "data-testid": "search-results-truncated" },
|
|
417
|
+
labels.searchResultsTruncated || "Some match locations are omitted") : null,
|
|
418
|
+
legacyResult ? h("pre", { className: "harness-search-legacy-result", "data-testid": "search-legacy-result" }, legacyResult) : null,
|
|
419
|
+
];
|
|
420
|
+
}
|
|
421
|
+
|
|
382
422
|
/** A directory listing (list_workspace_files / parsed list_files) vs a search. */
|
|
383
423
|
function isListInput(name, input) {
|
|
384
424
|
const n = String(name || "");
|
|
@@ -427,8 +467,9 @@ function searchCwd(input) {
|
|
|
427
467
|
|
|
428
468
|
function readMeta(item) {
|
|
429
469
|
const disp = item.display || {};
|
|
430
|
-
|
|
431
|
-
return { path:
|
|
470
|
+
const path = readInputPath(item.input) || (typeof item.result?.path === "string" ? item.result.path : "");
|
|
471
|
+
if (disp.kind === "file_read") return { path: disp.path || path, entryType: disp.entryType || "file" };
|
|
472
|
+
return { path, entryType: "file" };
|
|
432
473
|
}
|
|
433
474
|
|
|
434
475
|
function readInputPath(input) {
|
|
@@ -575,7 +616,7 @@ function fileChip(path, label, clickable, opts, chipTestid, nameTestid, action)
|
|
|
575
616
|
const isDir = action && action.kind === "directory" || String(path || "").endsWith("/");
|
|
576
617
|
const glyph = isDir ? searchIcon("harness-file-icon") : fileTextIcon("harness-file-icon");
|
|
577
618
|
const inner = [
|
|
578
|
-
glyph,
|
|
619
|
+
action?.showIcon === false ? null : glyph,
|
|
579
620
|
h("span", { className: "harness-file-name", "data-testid": nameTestid }, label),
|
|
580
621
|
];
|
|
581
622
|
if (clickable && opts.onOpenFile) {
|
package/src/styles.mjs
CHANGED
|
@@ -99,6 +99,8 @@ export const styles = `
|
|
|
99
99
|
}
|
|
100
100
|
.harness-tool-summary:hover .harness-tool-chevron,
|
|
101
101
|
.harness-thought-summary:hover .harness-thought-chevron { opacity: 1; }
|
|
102
|
+
.harness-tool-read .harness-tool-chevron { opacity: 0.65; }
|
|
103
|
+
.harness-tool-read .harness-tool-summary:is(:hover, :focus-visible) .harness-tool-chevron { opacity: 1; }
|
|
102
104
|
.harness-tool-details[open] .harness-tool-chevron,
|
|
103
105
|
.harness-thought-details[open] .harness-thought-chevron { transform: rotate(90deg); opacity: 1; }
|
|
104
106
|
@media (prefers-reduced-motion: reduce) {
|
|
@@ -133,7 +135,7 @@ export const styles = `
|
|
|
133
135
|
max-width: 50ch;
|
|
134
136
|
}
|
|
135
137
|
.harness-tool-secondary { font-size: 0.8rem; color: var(--harness-fg-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 40ch; }
|
|
136
|
-
.harness-tool-status { font-size: 0.8rem; color: var(--harness-fg-muted); text-transform: lowercase; }
|
|
138
|
+
.harness-tool-status { flex-shrink: 0; white-space: nowrap; font-size: 0.8rem; color: var(--harness-fg-muted); text-transform: lowercase; }
|
|
137
139
|
.harness-tool-status-running { color: var(--harness-running); }
|
|
138
140
|
.harness-tool-status-completed { display: none; }
|
|
139
141
|
.harness-tool-details-static > summary { cursor: default; list-style: none; }
|
|
@@ -149,8 +151,11 @@ export const styles = `
|
|
|
149
151
|
.harness-tool-detail-line { display: flex; gap: 6px; }
|
|
150
152
|
.harness-tool-detail-line dt { color: var(--harness-fg-muted); min-width: 8ch; }
|
|
151
153
|
.harness-tool-detail-line dd { margin: 0; word-break: break-all; }
|
|
154
|
+
.harness-search-matches { margin: 6px 0; padding-inline-start: 1.5em; font-size: 0.85rem; overflow-wrap: anywhere; }
|
|
155
|
+
.harness-search-legacy-result { margin: 6px 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 0.85rem; }
|
|
152
156
|
.harness-tool-progress { color: var(--harness-running); font-size: 0.85rem; }
|
|
153
157
|
.harness-tool-error { color: var(--harness-fg-muted); font-size: 0.85rem; }
|
|
158
|
+
.harness-tool-error-inline { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
154
159
|
.harness-tool-result { margin-top: 6px; }
|
|
155
160
|
.harness-tool-result > summary { cursor: pointer; color: var(--harness-fg-muted); font-size: 0.8rem; }
|
|
156
161
|
|
|
@@ -195,7 +200,6 @@ export const styles = `
|
|
|
195
200
|
.harness-file-chip-static:hover { color: var(--harness-fg-muted); text-decoration: none; }
|
|
196
201
|
.harness-file-icon { font-size: 0.85rem; }
|
|
197
202
|
.harness-file-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
198
|
-
.harness-read-path { font-size: 0.78rem; }
|
|
199
203
|
|
|
200
204
|
/* ── diff count + inline diff (edit) ─────────────────────────────────── */
|
|
201
205
|
.harness-diff-count { display: inline-flex; gap: 4px; align-items: center; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.78rem; }
|
package/src/tool-error.mjs
CHANGED
|
@@ -7,6 +7,11 @@ const summaries = {
|
|
|
7
7
|
capture_limit_exceeded: '工作区变更清单超出观测上限,命令未执行',
|
|
8
8
|
command_policy_blocked: '命令不符合当前执行规则,尚未执行',
|
|
9
9
|
policy_denied: '当前权限规则未允许这次操作',
|
|
10
|
+
approval_prompts_disabled: '这项操作需要单次授权,当前会话未开启审批',
|
|
11
|
+
approval_rejected: '用户未授权这次操作',
|
|
12
|
+
approval_unavailable: '当前没有可用的审批入口',
|
|
13
|
+
approval_cancelled: '这次审批已取消,操作未执行',
|
|
14
|
+
invalid_arguments: '工具参数校验未通过,操作未执行',
|
|
10
15
|
snippet_not_found: '找不到要替换的原文片段',
|
|
11
16
|
ambiguous_edit: '原文匹配次数与预期不符',
|
|
12
17
|
command_evidence_incomplete: '命令回执尚不完整,需要核对执行结果',
|
|
@@ -29,7 +34,15 @@ function errorValue(error) {
|
|
|
29
34
|
const errorCode = value => value?.error_type ?? value?.code ?? value?.error_code ?? value?.error?.code;
|
|
30
35
|
|
|
31
36
|
export function isRetryableEditFailure(error) {
|
|
32
|
-
return ['snippet_not_found', 'ambiguous_edit'].includes(errorCode(errorValue(error)));
|
|
37
|
+
return ['invalid_arguments', 'snippet_not_found', 'ambiguous_edit'].includes(errorCode(errorValue(error)));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const isCommandPolicyBlock = error => errorCode(errorValue(error)) === 'command_policy_blocked';
|
|
41
|
+
|
|
42
|
+
export function commandPolicyBlockReason(error) {
|
|
43
|
+
const value = errorValue(error);
|
|
44
|
+
const reason = value?.finding?.detail ?? value?.message ?? value?.error_message;
|
|
45
|
+
return typeof reason === 'string' ? redactError(reason) : null;
|
|
33
46
|
}
|
|
34
47
|
|
|
35
48
|
/** Detailed evidence remains expandable; compact rows do not dump wire JSON. */
|
package/src/view.mjs
CHANGED
|
@@ -22,7 +22,7 @@ import { renderTool } from "./renderers.mjs";
|
|
|
22
22
|
import { isRetryableEditFailure } from "./tool-error.mjs";
|
|
23
23
|
import { toolIdentity } from "./tool-identity.mjs";
|
|
24
24
|
import { activityGroups, activityGroupSummary } from './activity-groups.mjs';
|
|
25
|
-
import { conversationWorkSegments, completedWorkLabel } from './work-segments.mjs';
|
|
25
|
+
import { conversationWorkSegments, completedWorkLabel, interruptedWorkLabel } from './work-segments.mjs';
|
|
26
26
|
|
|
27
27
|
export const ELEMENT = Symbol.for("agentkit.harness-ui.element");
|
|
28
28
|
|
|
@@ -177,30 +177,34 @@ export function buildViewModel(state, options = {}) {
|
|
|
177
177
|
|
|
178
178
|
function timelineList(state, items, opts) {
|
|
179
179
|
const kids = [];
|
|
180
|
-
const modelActive = state.taskState === "running" && state.modelRequestActive;
|
|
180
|
+
const modelActive = state.taskState === "running" && (state.modelRequestActive || state.modelWait);
|
|
181
181
|
if (!modelActive && isWaitingForFirstToken(state)) kids.push(waitingPlaceholder(opts));
|
|
182
182
|
const transcript = state.taskState === 'running' ? items.filter(item =>
|
|
183
183
|
!(item.kind === 'tool' && item.status === 'failed' && toolIdentity(item.name).family === 'edit'
|
|
184
184
|
&& isRetryableEditFailure(item.error))) : items;
|
|
185
185
|
const segments = conversationWorkSegments(state, transcript);
|
|
186
|
+
const lastHistory = segments.findLastIndex(segment => segment.collapsible);
|
|
187
|
+
const interrupted = interruptedWorkLabel(state, opts.locale);
|
|
186
188
|
for (const [index, segment] of segments.entries()) {
|
|
187
189
|
const showModelActivity = modelActive && index === segments.length - 1
|
|
188
|
-
&& !segment.process.some(item => item.streaming && ["thought", "tool-preview"].includes(item.kind));
|
|
190
|
+
&& !segment.process.some(item => item.streaming && ["text", "thought", "tool-preview"].includes(item.kind));
|
|
189
191
|
kids.push(...renderTimelineItems(segment.inputs, opts));
|
|
190
192
|
if (segment.collapsible) {
|
|
191
193
|
const open = Boolean(opts.historyOpen?.get(segment.id));
|
|
192
194
|
kids.push(h('details', { open, className: 'harness-work-history', 'data-testid': 'work-history', 'data-item-id': segment.id },
|
|
193
195
|
h('summary', { className: 'harness-work-history-summary', 'data-testid': 'work-history-toggle' },
|
|
194
|
-
h('span', {}, completedWorkLabel(state, opts.locale)),
|
|
196
|
+
h('span', {}, completedWorkLabel(state, opts.locale)),
|
|
197
|
+
index === lastHistory && interrupted ? h('span', { 'data-testid': 'work-history-interruption' }, `· ${interrupted}`) : null,
|
|
198
|
+
chevronIcon('harness-work-history-chevron')),
|
|
195
199
|
open ? h('div', { className: 'harness-work-items harness-work-history-content', 'data-testid': 'work-history-content' },
|
|
196
200
|
...renderTimelineItems(segment.process, opts)) : null));
|
|
197
201
|
} else if (segment.process.length || showModelActivity) kids.push(h('div', { className: 'harness-work-items', 'data-testid': 'work-process' },
|
|
198
202
|
...renderTimelineItems(segment.process, opts, state.taskState === 'running'
|
|
199
203
|
&& index === segments.length - 1 && segment.following.length === 0),
|
|
200
|
-
showModelActivity ? modelActivity(opts) : null));
|
|
204
|
+
showModelActivity ? modelActivity(opts, state) : null));
|
|
201
205
|
kids.push(...renderTimelineItems(segment.following, opts));
|
|
202
206
|
}
|
|
203
|
-
if (modelActive && !segments.length) kids.push(modelActivity(opts));
|
|
207
|
+
if (modelActive && !segments.length) kids.push(modelActivity(opts, state));
|
|
204
208
|
if (!kids.length && opts.emptyState) kids.push(opts.emptyState);
|
|
205
209
|
if (opts.following === false) kids.push(jumpToLatest(opts));
|
|
206
210
|
return h("div", { className: "harness-timeline", "data-testid": "harness-timeline-list" }, ...kids);
|
|
@@ -270,10 +274,24 @@ function textBlock(item, opts) {
|
|
|
270
274
|
}, h("span", { className: "harness-text-content" }, text));
|
|
271
275
|
}
|
|
272
276
|
|
|
273
|
-
function modelActivity(opts) {
|
|
274
|
-
|
|
277
|
+
function modelActivity(opts, state) {
|
|
278
|
+
if (state.modelWait) {
|
|
279
|
+
const zh = String(opts.locale ?? '').startsWith('zh'), status = state.modelWait.httpStatus;
|
|
280
|
+
const label = status === 429 ? (zh ? '网关限流,等待重试' : 'Gateway rate limited; waiting to retry')
|
|
281
|
+
: zh ? '模型请求暂未成功,等待重试' : 'Model request delayed; waiting to retry';
|
|
282
|
+
return h('div', { className: 'harness-thought-summary harness-model-activity', role: 'status',
|
|
283
|
+
'data-testid': 'model-backoff', 'data-retry-at': state.modelWait.retryAt },
|
|
284
|
+
brainIcon('harness-thought-icon'), h('span', {}, label));
|
|
285
|
+
}
|
|
286
|
+
const zh = String(opts.locale ?? '').startsWith('zh');
|
|
287
|
+
const compacting = state.modelRequestPurpose === 'compaction', retry = state.modelRequestRetry;
|
|
288
|
+
const label = compacting ? (retry ? (zh ? '正在重试上下文压缩…' : 'Retrying context compaction…')
|
|
289
|
+
: (zh ? '正在压缩上下文…' : 'Compacting context…'))
|
|
290
|
+
: retry ? (zh ? '模型正在重试…' : 'Retrying model request…') : opts.labels.thinking;
|
|
291
|
+
return h("div", { className: "harness-thought-summary harness-model-activity", role: "status",
|
|
292
|
+
"data-testid": compacting ? "model-compaction" : retry ? "model-retry" : "model-thinking" },
|
|
275
293
|
brainIcon("harness-thought-icon"),
|
|
276
|
-
h("span", { className: "harness-thought-label harness-thought-label-streaming" },
|
|
294
|
+
h("span", { className: "harness-thought-label harness-thought-label-streaming" }, label));
|
|
277
295
|
}
|
|
278
296
|
|
|
279
297
|
function thoughtBlock(item, opts) {
|
package/src/work-segments.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { toolIdentity } from './tool-identity.mjs';
|
|
2
|
+
|
|
1
3
|
/** Completion is declared by the Host; a text row alone never closes a task.
|
|
2
4
|
* This is a view over immutable transcript rows, not a second task lifecycle. */
|
|
3
5
|
export function conversationWorkSegments(state, items) {
|
|
@@ -11,6 +13,7 @@ export function conversationWorkSegments(state, items) {
|
|
|
11
13
|
}
|
|
12
14
|
if (segment.inputs.length || segment.work.length) segments.push(segment);
|
|
13
15
|
const closed = ['completed', 'unverified'].includes(state.taskState) && !state.taskError;
|
|
16
|
+
const ended = closed || ['failed', 'cancelled', 'interrupted'].includes(state.taskState);
|
|
14
17
|
return segments.map((segment, index) => {
|
|
15
18
|
const rows = segment.work;
|
|
16
19
|
const candidate = rows.find(item => item.id === state.finalAnswerId)
|
|
@@ -19,9 +22,8 @@ export function conversationWorkSegments(state, items) {
|
|
|
19
22
|
const answerIndex = final ? rows.findIndex(item => item.kind === 'text' && (item.id === final.id
|
|
20
23
|
|| final.sourceMessageId && item.sourceMessageId === final.sourceMessageId)) : -1;
|
|
21
24
|
const process = answerIndex >= 0 ? rows.slice(0, answerIndex) : rows;
|
|
22
|
-
const unresolved = rows.some(item => item.kind === 'tool' && ['scheduled', 'running', 'waiting', 'uncertain', 'interrupted'].includes(item.status));
|
|
23
25
|
return { ...segment, process, following: answerIndex >= 0 ? rows.slice(answerIndex) : [],
|
|
24
|
-
collapsible:
|
|
26
|
+
collapsible: ended && process.length > 0 };
|
|
25
27
|
});
|
|
26
28
|
}
|
|
27
29
|
|
|
@@ -39,3 +41,17 @@ export function completedWorkLabel(state, locale) {
|
|
|
39
41
|
}
|
|
40
42
|
return `${zh ? '已工作' : 'Worked'} ${parts.slice(0, 2).join(' ')}`;
|
|
41
43
|
}
|
|
44
|
+
|
|
45
|
+
export function interruptedWorkLabel(state, locale) {
|
|
46
|
+
if (state.taskState !== 'interrupted') return null;
|
|
47
|
+
const zh = String(locale ?? '').startsWith('zh');
|
|
48
|
+
if (state.taskReason === 'effect_outcome_unknown') {
|
|
49
|
+
const lastUncertain = state.items.findLast(item => item.kind === 'tool' && item.status === 'uncertain');
|
|
50
|
+
const browser = lastUncertain && toolIdentity(lastUncertain.name).family === 'browser';
|
|
51
|
+
return zh ? (browser ? '已中断:浏览器验收结果未确认' : '已中断:工具执行结果未确认')
|
|
52
|
+
: (browser ? 'Interrupted: browser verification result unconfirmed' : 'Interrupted: tool result unconfirmed');
|
|
53
|
+
}
|
|
54
|
+
if (state.taskReason === 'browser_session_unavailable')
|
|
55
|
+
return zh ? '已中断:浏览器会话不可用' : 'Interrupted: browser session unavailable';
|
|
56
|
+
return zh ? '任务已中断' : 'Task interrupted';
|
|
57
|
+
}
|