@kingsoftcloud/agentkit-harness-ui 0.0.13 → 0.0.15

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/README.md CHANGED
@@ -22,6 +22,12 @@ callbacks; the component never resolves execution roots or performs I/O. These
22
22
  are current workspace observations, separate from immutable tool receipts and
23
23
  task acceptance. Failed or canceled reads must not fall back to a parent file.
24
24
 
25
+ `./host/native-approval-actions` adds a Host-owned Session grant action to an
26
+ existing one-call approval card. Lost replies may retry the same offer; an
27
+ explicit stale-offer refusal disables that offer and directs the user to the
28
+ original one-call approval. A later Host offer remains independently usable.
29
+ The component never renews an offer or approves a call without its exact receipt.
30
+
25
31
  ## Design
26
32
 
27
33
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-ui",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
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.",
@@ -38,6 +38,7 @@
38
38
  "./host/native-child-pane": "./src/host/native-child-pane.mjs",
39
39
  "./host/native-child-file-pane": "./src/host/native-child-file-pane.mjs",
40
40
  "./host/native-run-panel": "./src/host/native-run-panel.mjs",
41
+ "./host/native-approval-actions": "./src/host/native-approval-actions.mjs",
41
42
  "./host/native-a2a": "./src/host/native-a2a.mjs",
42
43
  "./host/state/native-a2a": "./src/host/state/native-a2a.mjs",
43
44
  "./host/state/native-task-read-model": "./src/host/state/native-task-read-model.mjs"
@@ -96,6 +97,6 @@
96
97
  "registry": "https://registry.npmjs.org"
97
98
  },
98
99
  "dependencies": {
99
- "@kingsoftcloud/agentkit-harness-core": "0.0.13"
100
+ "@kingsoftcloud/agentkit-harness-core": "0.0.15"
100
101
  }
101
102
  }
@@ -34,7 +34,7 @@ function awaitingCommand(item) {
34
34
  * its parent active between model calls. Child outcomes remain independent.
35
35
  * Narrative, visible reasoning, context markers and child tasks are boundaries.
36
36
  */
37
- export function activityGroups(items, { stageTailIsRunning = false, enableChangesGrouping = false, enableBrowserGrouping = true } = {}) {
37
+ export function activityGroups(items, { stageTailIsRunning = false, enableChangesGrouping = true, enableBrowserGrouping = true } = {}) {
38
38
  // A Shell input draft without a command is transparent to stage boundaries.
39
39
  // Filter before counting/tail detection; keep the original event state intact.
40
40
  items = items.filter(item => !awaitingCommand(item));
@@ -49,7 +49,19 @@ export function activityGroups(items, { stageTailIsRunning = false, enableChange
49
49
  const kind = group === 'explore' ? explorationBucket(item) : toolIdentity(item.name).family;
50
50
  counts[kind] = (counts[kind] ?? 0) + 1;
51
51
  }
52
+ const paths = new Set();
53
+ let unknownFileOperations = 0;
54
+ if (group === 'changes') for (const item of children) {
55
+ const display = item.display ?? {}, input = item.input ?? {};
56
+ const candidates = display.kind === 'file_edit' && Array.isArray(display.files) ? display.files.map(file => file.path)
57
+ : display.path ? [display.path] : Array.isArray(input.files) ? input.files.map(file => file.path)
58
+ : [input.path ?? input.file_path ?? input.filePath ?? input.filename];
59
+ const known = candidates.filter(path => typeof path === 'string' && path.trim());
60
+ if (!known.length) unknownFileOperations++;
61
+ for (const path of known) paths.add(path.trim());
62
+ }
52
63
  result.push({ kind: 'activity-group', id: `activity:${group}:${first.callId ?? first.id}`, family: group, children, counts,
64
+ ...(group === 'changes' ? { fileCount: paths.size, unknownFileOperations } : {}),
53
65
  active: stageTailIsRunning && index === items.length,
54
66
  failed: children.filter(item => item.status === 'failed').length,
55
67
  uncertain: children.filter(item => ['uncertain', 'interrupted', 'waiting'].includes(item.status)).length });
@@ -66,6 +78,10 @@ export function activityGroupSummary(group, locale) {
66
78
  const parts = group.family === 'explore'
67
79
  ? Object.entries(units).filter(([key]) => group.counts[key])
68
80
  .map(([key, unit]) => `${group.counts[key]} ${unit}${!zh && group.counts[key] !== 1 ? key === 'search' || key === 'web-fetch' ? 'es' : 's' : ''}`)
81
+ : group.family === 'changes'
82
+ ? [group.fileCount ? `${group.fileCount} ${zh ? '个文件' : group.fileCount === 1 ? 'file' : 'files'}` : '',
83
+ `${group.children.length} ${zh ? '次操作' : 'operations'}`,
84
+ group.unknownFileOperations ? `${group.unknownFileOperations} ${zh ? '次路径待确认' : 'paths unconfirmed'}` : ''].filter(Boolean)
69
85
  : [`${group.children.length} ${group.family === 'terminal' ? zh ? '个命令' : 'commands'
70
86
  : group.family === 'browser' ? zh ? '次调用' : 'calls' : zh ? '次文件操作' : 'file operations'}`];
71
87
  if (group.failed) parts.push(`${group.failed} ${zh ? '失败' : 'failed'}`);
@@ -0,0 +1,39 @@
1
+ const contract = 'agentkit.native-session-tool-approval/v1';
2
+ const validId = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 256;
3
+
4
+ /** Optional addition to the Host's existing one-call approval card. */
5
+ export function createNativeApprovalActions({ React: { createElement: h, useState, useRef, useEffect }, hostRemote, Button = 'button' }) {
6
+ return function NativeApprovalActions({ pending }) {
7
+ const [waiting, setWaiting] = useState(false), [failure, setFailure] = useState(null);
8
+ const busy = useRef(false), alive = useRef(true), staleOffer = useRef(null);
9
+ useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
10
+ const offer = pending?.sessionGrant;
11
+ if (offer?.contract !== contract || typeof hostRemote?.grantNativeSessionTool !== 'function'
12
+ || !['offerId', 'requestId', 'agentId', 'sessionId', 'runId', 'toolName', 'targetSessionId'].every(key => validId(offer[key]))
13
+ || pending.sessionId !== offer.sessionId || pending.toolName !== offer.toolName
14
+ || typeof pending.answer !== 'function') return null;
15
+ const stale = staleOffer.current === offer.offerId;
16
+ const error = failure?.offerId === offer.offerId ? failure.message : '';
17
+ const allow = async () => {
18
+ if (busy.current || staleOffer.current === offer.offerId || !pending.answerable) return;
19
+ busy.current = true; setWaiting(true); setFailure(null);
20
+ try {
21
+ const request = Object.fromEntries(['agentId', 'sessionId', 'runId', 'offerId', 'requestId'].map(key => [key, offer[key]]));
22
+ const receipt = await hostRemote.grantNativeSessionTool(request);
23
+ if (!['accepted', 'duplicate'].includes(receipt?.status) || receipt.offerId !== offer.offerId || receipt.requestId !== offer.requestId)
24
+ throw Error('unconfirmed Session grant');
25
+ if (alive.current && pending.answerable) await pending.answer('allowed-once');
26
+ } catch (cause) {
27
+ const invalid = ['session_tool_approval_offer_stale', 'studio_native_session_approval_stale'].includes(cause?.code);
28
+ if (invalid) staleOffer.current = offer.offerId;
29
+ if (alive.current) setFailure({ offerId: offer.offerId, message: invalid
30
+ ? '这次会话授权已失效,请选择“允许一次”继续当前操作。'
31
+ : '会话授权尚未确认,请重试或选择仅允许一次。' });
32
+ } finally { busy.current = false; if (alive.current) setWaiting(false); }
33
+ };
34
+ return h('span', null, h(Button, { type: 'button', variant: 'outline', disabled: waiting || stale || !pending.answerable,
35
+ title: `仅记住 ${offer.toolName} 在当前构建及会话运行期间的 Agent 额外审批;Host 和沙箱限制仍然有效。重启或权限变更后需要重新确认。`,
36
+ onClick: allow }, waiting ? '确认授权中…' : stale ? '会话授权已失效' : offer.targetSessionId === offer.sessionId ? '本会话允许此工具' : '本子任务会话允许此工具'),
37
+ error ? h('span', { role: 'alert' }, error) : null);
38
+ };
39
+ }
@@ -67,6 +67,7 @@ export function createNativeChildPanel({ ui: { React: { createElement: h, useEff
67
67
  stopState.visible && stopState.error ? h('span', { role: 'alert' }, stopState.error) : null,
68
68
  h('button', { type: 'button', style: buttonStyle(), onClick: () => setOpen(true) }, '运行与子任务'),
69
69
  open ? h(ResourceDialog, { title: '本会话的运行与子任务', detail: '查看运行用量、恢复状态及各轮子任务。子任务结果仍需父任务验收。', wide: true, onClose: () => setOpen(false) },
70
+ presentation?.detail ? h('p', { 'aria-label': '运行原因与后续操作' }, presentation.detail) : null,
70
71
  h('button', { type: 'button', style: buttonStyle(), disabled: !controller || state.loading, onClick: () => { void controller?.refresh(); void recovery?.refresh(); } }, state.loading ? '读取中…' : '刷新'),
71
72
  recoveryState.error ? h('p', { role: 'alert' }, recoveryState.error) : null,
72
73
  recoveryState.status?.error ? h('p', { role: 'alert' }, recoveryState.status.error.message) : null,
@@ -164,6 +165,7 @@ export function createNativeChildPanel({ ui: { React: { createElement: h, useEff
164
165
  h('button', { type: 'button', disabled: state.reading, style: buttonStyle(), onClick: () => void controller.read(task) }, task.resultAvailable ? '查看结果' : '查看状态'),
165
166
  task.canPromote ? h('button', { type: 'button', disabled: Boolean(state.pending), style: buttonStyle(), onClick: () => void controller.promote(task) }, '转为后台') : null,
166
167
  task.canCancel ? h('button', { type: 'button', disabled: Boolean(state.pending), style: buttonStyle(), onClick: () => void controller.cancel(task) }, '停止子任务') : null,
168
+ task.canResume === true ? h('button', { type: 'button', disabled: Boolean(state.pending), style: buttonStyle(), onClick: () => void controller.resume(task) }, '恢复原子任务') : null,
167
169
  task.canSendInput ? h('div', null,
168
170
  h('textarea', { 'aria-label': `给 ${task.role} 补充指导`, maxLength: 32768, rows: 2, value: drafts[task.childRunId] ?? '',
169
171
  disabled: Boolean(state.pending), onChange: event => setDrafts({ ...drafts, [task.childRunId]: event.target.value }) }),
@@ -220,7 +220,7 @@ export function nativeTaskState(state, status, running) {
220
220
  && !['completed', 'failed'].includes(item.status) && previews.has(item.callId)
221
221
  ? { ...item, status: 'running', display: previews.get(item.callId).display,
222
222
  progress: previews.get(item.callId).truncated ? '运行中的输出预览已截断' : null } : item.kind === 'tool' && toolStates.has(item.callId)
223
- ? { ...item, status: toolStates.get(item.callId) } : item.kind === 'tool-preview' && taskState !== 'running'
223
+ ? item.status === toolStates.get(item.callId) ? item : { ...item, status: toolStates.get(item.callId) } : item.kind === 'tool-preview' && taskState !== 'running'
224
224
  ? { ...item, streaming: false } : item.kind === 'tool' && ['scheduled', 'running'].includes(item.status)
225
225
  && ['interrupted', 'waiting', 'paused', 'cancelled', 'failed', 'unverified', 'completed'].includes(taskState)
226
226
  ? { ...item, status: taskState === 'waiting' ? 'waiting' : 'interrupted' } : item),
@@ -11,6 +11,9 @@ export function createNativeChildrenState({ hostRemote, agentId, sessionId, comm
11
11
  const validTask = task => task && ['childRunId', 'sessionId', 'parentRunId', 'role', 'phase', 'goalPreview']
12
12
  .every(key => typeof task[key] === 'string') && typeof task.resultAvailable === 'boolean'
13
13
  && task.usage && Number.isSafeInteger(task.usage.modelCalls) && Number.isSafeInteger(task.usage.toolCalls)
14
+ && (task.canResume === undefined || typeof task.canResume === 'boolean'
15
+ && (!task.canResume || task.phase === 'paused'
16
+ && !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(task.reason)))
14
17
  && (task.a2aTasks === undefined || Array.isArray(task.a2aTasks) && task.a2aTasks.length <= 10000
15
18
  && task.a2aTasks.every(item => item?.runId === task.parentRunId && item.childRunId === task.childRunId
16
19
  && item.childSessionId === task.sessionId && ['childAgentId', 'operationKey', 'callId']
@@ -25,7 +28,7 @@ export function createNativeChildrenState({ hostRemote, agentId, sessionId, comm
25
28
  if (disposed) return;
26
29
  valid(page);
27
30
  check(Array.isArray(page.tasks) && page.tasks.every(task => validTask(task)
28
- && (!(task.canPromote || task.canCancel || task.canSendInput) || task.parentRunId === page.runId)
31
+ && (!(task.canPromote || task.canCancel || task.canSendInput || task.canResume) || task.parentRunId === page.runId)
29
32
  && (!task.canSendInput || Number.isSafeInteger(task.goalRevision) && task.goalRevision >= 0))
30
33
  && new Set(page.tasks.map(task => task.childRunId)).size === page.tasks.length
31
34
  && Number.isSafeInteger(page.offset) && page.offset >= 0 && page.nextOffset === page.offset + page.tasks.length
@@ -64,7 +67,7 @@ export function createNativeChildrenState({ hostRemote, agentId, sessionId, comm
64
67
  const pending = state.pending;
65
68
  set({ sending: true, error: '' });
66
69
  try {
67
- const method = { promote: 'promoteNativeChild', send: 'sendNativeChildInput', cancel: 'cancelNativeChild' }[state.pendingAction];
70
+ const method = { promote: 'promoteNativeChild', send: 'sendNativeChildInput', cancel: 'cancelNativeChild', resume: 'resumeNativeChild' }[state.pendingAction];
68
71
  const receipt = await hostRemote[method](pending, lifetime.signal);
69
72
  check(receipt?.commandId === pending.commandId && ['accepted', 'duplicate'].includes(receipt.status), '子任务操作回执未确认。');
70
73
  if (disposed) return;
@@ -73,7 +76,7 @@ export function createNativeChildrenState({ hostRemote, agentId, sessionId, comm
73
76
  finally { set({ sending: false }); }
74
77
  }
75
78
  function control(action, task, extra = {}) {
76
- const allowed = { promote: task.canPromote, send: task.canSendInput, cancel: task.canCancel }[action];
79
+ const allowed = { promote: task.canPromote, send: task.canSendInput, cancel: task.canCancel, resume: task.canResume === true }[action];
77
80
  if (disposed || state.pending || !allowed || task.parentRunId !== state.page?.runId) return;
78
81
  if (action === 'send' && (typeof extra.text !== 'string' || !extra.text.trim() || extra.text.length > 32768
79
82
  || !Number.isSafeInteger(task.goalRevision) || task.goalRevision < 0)) return;
@@ -86,6 +89,7 @@ export function createNativeChildrenState({ hostRemote, agentId, sessionId, comm
86
89
  subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
87
90
  refresh: () => load(), next: () => load(true), read,
88
91
  promote: task => control('promote', task), cancel: task => control('cancel', task),
92
+ resume: task => control('resume', task),
89
93
  sendInput: (task, text) => control('send', task, { text, expectedGoalRevision: task.goalRevision }),
90
94
  retryControl: sendControl, retryPromotion: sendControl,
91
95
  dispose() { if (disposed) return; disposed = true; lifetime.abort(); reading++; listeners.clear(); },
@@ -2,6 +2,27 @@ const phases = { created: '已准备', preparing_context: '整理上下文', req
2
2
  compacting: '压缩上下文', verifying: '验证结果', executing_tools: '执行工具', awaiting_interaction: '等待审批或输入', paused: '已暂停',
3
3
  awaiting_reconciliation: '等待核对执行结果', reconciling_tool: '正在核对执行结果', interrupted: '执行中断,需要核对', finalizing: '收尾中' };
4
4
 
5
+ // Stable ledger reasons, never raw provider/tool exception text. These are
6
+ // explanations only; canResume still comes from the current Host authority.
7
+ const pauseReasons = {
8
+ child_paused: ['子任务已暂停,等待处理', '原子任务及已提交结果已保留。请在“运行与子任务”中核对暂停原因,明确恢复或取消原子任务。'],
9
+ approval_rejected: ['审批被拒绝,已暂停', '这次操作没有获得批准,尚未执行。已停止继续申请和生成,等待补充指导或明确恢复。'],
10
+ approval_cancelled: ['审批已取消,已暂停', '这次审批被取消,操作尚未执行。原任务已保留,不会自动重新申请。'],
11
+ approval_unavailable: ['审批通道不可用,已暂停', '尚未取得审批结果,操作没有获得批准。请先恢复审批通道再核对原任务。'],
12
+ output_budget_exhausted: ['输出恢复额度已耗尽,已暂停', '同一响应多次达到输出上限,已保留已提交的工具结果和回复片段。'],
13
+ provider_unavailable: ['模型服务暂不可用,已暂停', '模型请求的本轮重试已耗尽,原运行和已提交结果已保留。'],
14
+ context_summary_unavailable: ['上下文整理暂不可用,已暂停', '上下文摘要暂未生成,原运行已保留,没有丢弃必需上下文。'],
15
+ context_source_unavailable: ['上下文读取暂不可用,已暂停', '必需的上下文读取尚未成功,原运行和已提交结果已保留。'],
16
+ };
17
+ const failureReasons = {
18
+ continuation_budget_exhausted: ['输出续写额度已耗尽', '本轮输出续写与重启额度已耗尽,任务没有完成。请核对模型输出上限和运行记录。'],
19
+ model_budget_exhausted: ['模型调用预算已耗尽', '本轮已达到模型调用总预算,不能通过恢复补回已经消耗的预算。'],
20
+ execution_budget_exhausted: ['执行时间预算已耗尽', '本轮已达到执行时间预算,任务没有完成。'],
21
+ provider_retryable_error_retry_exhausted: ['模型请求重试已耗尽', '模型服务持续未能完成请求,任务没有完成。'],
22
+ context_compaction_limit: ['上下文压缩次数已耗尽', '本轮已达到上下文压缩次数上限,任务尚未完成。'],
23
+ context_mandatory_state_over_budget: ['必需上下文超过预算', '任务必需的上下文超过可用预算,无法安全省略后继续。'],
24
+ };
25
+
5
26
  /** The committed phase survives a crash; only the owner control state says work is still being driven. */
6
27
  export function nativeRunIsInactive(status, transportRunning = true) {
7
28
  return status?.state ? status.state !== 'recovering' : !transportRunning;
@@ -15,6 +36,17 @@ export function nativeRunPresentation(status) {
15
36
  && status.backgroundInterruptionReview.confirmedStopped === true && status.state === 'closed')
16
37
  return { label: '已结束等待,原结果未知', detail: '已核对原操作停止并关闭本轮;未知结果与原回执保持不变,没有重跑原命令。' };
17
38
  if (status.phase === 'canceled') return { label: '已取消', detail: '本轮执行已停止;已经发生的文件或外部修改不会因此自动撤销。' };
39
+ if (status.phase === 'paused' && Object.hasOwn(pauseReasons, status.reason)) {
40
+ const [label, detail] = pauseReasons[status.reason];
41
+ if (status.reason === 'child_paused') return { label, detail };
42
+ return { label, detail: detail + (status.canResume === true
43
+ ? '请在运行与子任务中核对后恢复原运行;不会重新执行已提交的操作。'
44
+ : '请在运行与子任务中核对原因及当前可用操作。') };
45
+ }
46
+ if (status.phase === 'failed' && Object.hasOwn(failureReasons, status.reason)) {
47
+ const [label, detail] = failureReasons[status.reason];
48
+ return { label, detail: status.error?.message || detail };
49
+ }
18
50
  if (status.outcome === 'blocked') return { label: '任务受阻', detail: status.error?.message || '本轮未能完成任务。请查看回复中的缺项,检查 Agent 的「绑定能力」及审批要求。' };
19
51
  if (status.phase === 'failed') return { label: '执行失败', detail: status.error?.message || '本轮执行未成功,请查看错误并核对结果后重试。' };
20
52
  if (status.phase === 'interrupted' && status.reason === 'effect_outcome_unknown')
@@ -23,6 +55,10 @@ export function nativeRunPresentation(status) {
23
55
  return status.canResume === true
24
56
  ? { label: '执行中断,等待恢复', detail: '原运行已没有活动执行者;恢复原任务后才会继续。已提交的回执保持不变。' }
25
57
  : { label: '任务已中断', detail: status.error?.message || '原运行已停止。请查看运行记录和当前可用操作。' };
58
+ if (['preparing_context', 'compacting'].includes(status.phase)
59
+ && status.modelRetryWait?.contract === 'agentkit.native-model-retry-wait/v1'
60
+ && Number.isFinite(status.modelRetryWait.notBefore) && status.modelRetryWait.notBefore > 0)
61
+ return { label: '等待模型重试', detail: '模型请求正在按重试策略等待;任务尚未停止。' };
26
62
  if (status.phase !== 'completed') return { label: phases[status.phase] || '处理中', detail: '' };
27
63
  if (status.outcome === 'failed' || status.outcome === 'budget_exhausted') return { label: '任务未完成', detail: '本轮已结束,任务未完成。请查看错误、预算和结果记录。' };
28
64
  if (status.outcome === 'verified') return { label: '任务已验证', detail: '任务已通过本次配置的验证检查;验证范围以结果证据为准。' };
@@ -16,6 +16,11 @@ export function validateNativeRecoveryStatus(value, { agentId, sessionId, runId
16
16
  '运行错误记录无法识别,请刷新核对。');
17
17
  if (value.outcome != null) check(['verified', 'unverified', 'partial', 'blocked', 'failed', 'budget_exhausted'].includes(value.outcome), '任务结果状态无法识别,请刷新核对。');
18
18
  if (value.verificationRequired !== undefined) check(typeof value.verificationRequired === 'boolean', '任务验证要求无法识别,请刷新核对。');
19
+ if (value.modelRetryWait !== undefined) check(value.modelRetryWait?.contract === 'agentkit.native-model-retry-wait/v1'
20
+ && Object.keys(value.modelRetryWait).sort().join(',') === 'contract,notBefore'
21
+ && Number.isFinite(value.modelRetryWait.notBefore) && value.modelRetryWait.notBefore > 0
22
+ && value.state === 'recovering' && ['preparing_context', 'compacting'].includes(value.phase),
23
+ '模型重试等待状态与原运行不一致,请刷新核对。');
19
24
  if (value.canRetireResources !== undefined) check(typeof value.canRetireResources === 'boolean'
20
25
  && (!value.canRetireResources || !value.managed && value.phase === 'interrupted'
21
26
  && Number.isSafeInteger(value.resourceRetirementEventSeq) && value.resourceRetirementEventSeq >= 0),
@@ -0,0 +1,36 @@
1
+ /** Presentation scheduling only. Never rewrite or drop authoritative events.
2
+ * Transient chunks share a paint; durable/reconnect changes publish immediately. */
3
+ export function createTimelineEventFeed(source, {
4
+ schedule = callback => typeof requestAnimationFrame === 'function' ? requestAnimationFrame(callback) : setTimeout(callback, 16),
5
+ cancel = handle => typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame(handle) : clearTimeout(handle),
6
+ } = {}) {
7
+ let snapshot = source.getSnapshot(), release = null, frame = null, generation = 0;
8
+ const listeners = new Set();
9
+ const cancelPending = () => { generation++; if (frame !== null) cancel(frame); frame = null; };
10
+ const publish = () => {
11
+ const next = source.getSnapshot();
12
+ if (next === snapshot) return;
13
+ snapshot = next;
14
+ for (const listener of [...listeners]) listener();
15
+ };
16
+ const changed = () => {
17
+ const change = source.getSnapshot().change;
18
+ const transient = change?.kind === 'append' && change.entries.length > 0
19
+ && change.entries.every(entry => entry.event?.type === 'assistant/live-chunk');
20
+ if (!transient) { cancelPending(); publish(); return; }
21
+ if (frame !== null) return;
22
+ const current = generation;
23
+ frame = schedule(() => { if (current !== generation) return; frame = null; publish(); });
24
+ };
25
+ return {
26
+ getSnapshot() { if (!listeners.size) snapshot = source.getSnapshot(); return snapshot; },
27
+ subscribe(listener) {
28
+ listeners.add(listener);
29
+ if (listeners.size === 1) { release = source.subscribe(changed); publish(); }
30
+ return () => {
31
+ listeners.delete(listener);
32
+ if (!listeners.size) { cancelPending(); release?.(); release = null; }
33
+ };
34
+ },
35
+ };
36
+ }
@@ -7,6 +7,7 @@ import { 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';
10
+ import { createTimelineEventFeed } from './state/timeline-event-feed.mjs';
10
11
  import { createSessionTaskProjector, nativeTaskState, nativeStatusForTurn, bindNativeSubagents, nativeHistoricalToolState } from './session-task-events.mjs';
11
12
 
12
13
  const labels = { result: '执行结果', thought: '思考', running: '执行中', thinking: '思考中…', ended: '本轮已结束', contextRunning: '正在压缩上下文', contextCompleted: '上下文已自动压缩',
@@ -21,6 +22,7 @@ const labels = { result: '执行结果', thought: '思考', running: '执行中'
21
22
  toolDetails: '工具详情', close: '关闭', state: '状态', arguments: '调用参数', noSettledResult: '尚无已确认的结果', appliedChanges: '实际文件变更',
22
23
  diffTruncated: '差异预览已截断', diffUnavailable: '无可用差异预览', diffFilesOmitted: '个文件预览已省略', plan: '计划',
23
24
  writePending: '请求写入', editPending: '请求修改',
25
+ requestedArguments: '请求参数(非执行结果)',
24
26
  subagent: '子智能体', openSubagent: '在右侧打开', childSyncing: '同步中', childOmitted: '当前显示过程窗口,较早内容或较长字段已省略。',
25
27
  toolPreparing: '正在生成工具参数', previewStopped: '工具参数生成已中断' };
26
28
 
@@ -179,7 +181,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
179
181
  inject: sessionId => {
180
182
  const binding = ctx.sessions.binding(sessionId);
181
183
  if (!binding) throw Error('Task timeline session is unavailable');
182
- return { hooks: { harnessEvents: binding.eventSource } };
184
+ return { hooks: { harnessEvents: createTimelineEventFeed(binding.eventSource) } };
183
185
  },
184
186
  }, TaskView));
185
187
  }
package/src/inspector.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { redactValue, truncateText } from './summary.mjs';
2
+ import { toolInputPreview } from './tool-detail.mjs';
2
3
 
3
4
  const bounded = value => {
4
5
  let parsed = value;
@@ -27,7 +28,7 @@ export function createToolInspector(React) {
27
28
  h('header', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
28
29
  h('strong', null, item.name), h('button', { type: 'button', onClick: onClose, autoFocus: true }, labels.close || 'Close')),
29
30
  h('p', null, `${labels.state || 'State'}: ${item.status}`),
30
- h('h4', null, labels.arguments || 'Arguments'), h('pre', null, bounded(item.input ?? {})),
31
+ h('h4', null, labels.arguments || 'Arguments'), h('pre', null, toolInputPreview(item.input)),
31
32
  h('h4', null, labels.result || 'Result'),
32
33
  h('pre', null, item.error ? bounded(item.error) : item.result != null ? bounded(item.result)
33
34
  : labels.noSettledResult || 'No settled result is available'),
package/src/project.mjs CHANGED
@@ -22,6 +22,7 @@ export function visibleItems(state, { includeInternal = false } = {}) {
22
22
  const visible = [];
23
23
  for (const item of timeline) {
24
24
  if (['tool', 'tool-preview'].includes(item.kind) && !toolConversationVisible(item)) continue;
25
+ if (item.kind === 'text' && !String(item.text ?? '').trim()) continue;
25
26
  if (item.kind === 'thought' && !String(item.text ?? '').trim()) continue;
26
27
  const previous = visible.at(-1);
27
28
  if (item.kind === 'thought' && previous?.kind === 'thought') {
@@ -245,10 +245,16 @@ export function createHarnessComponents(React) {
245
245
  };
246
246
  const callbacks = useMemo(() => ({ onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent }),
247
247
  [onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent]);
248
+ // Tool view trees contain action descriptors, not callback closures. Stable
249
+ // completed items can retain both their parsed view and React subtree while
250
+ // the live tail changes. Disclosure and presentation options invalidate it.
251
+ const toolViewCache = useMemo(() => new WeakMap(), [toolOpen, labels, locale, workspaceRoot,
252
+ Boolean(onOpenFile), Boolean(onCopy), Boolean(onOpenTerminal), Boolean(onRetrieveFullDiff), Boolean(onInspectTool), Boolean(onOpenSubagent)]);
253
+ const toolElementCache = useMemo(() => new WeakMap(), [toolViewCache, reducedMotion]);
248
254
  const tree = buildViewModel(state, {
249
- thoughtOpen, toolOpen, historyOpen, labels, locale, showPlanDock, workspaceRoot, following, rootProps, ...callbacks,
255
+ thoughtOpen, toolOpen, historyOpen, labels, locale, showPlanDock, workspaceRoot, following, rootProps, toolViewCache, ...callbacks,
250
256
  });
251
- const rendered = renderTree(tree, renderText, callbacks, React, reducedMotion);
257
+ const rendered = renderTree(tree, renderText, callbacks, React, reducedMotion, toolElementCache);
252
258
  if (styleSheet === null) return rendered;
253
259
  return createElement(Fragment, null,
254
260
  createElement("style", { "data-harness-ui": true }, styleSheet === undefined ? styles : styleSheet),
@@ -262,17 +268,18 @@ export function createHarnessComponents(React) {
262
268
  * summary) are wrapped in small behavior components that attach their own
263
269
  * refs/effects; everything else maps straight through.
264
270
  */
265
- function renderTree(node, renderText, callbacks, React, reducedMotion) {
271
+ function renderTree(node, renderText, callbacks, React, reducedMotion, toolElementCache) {
266
272
  if (node == null || node === false) return null;
267
273
  if (typeof node !== "object") return node;
268
274
  const { createElement } = React;
269
275
  const testid = node.props?.["data-testid"];
270
276
  const props = node.props || {};
277
+ if (testid === 'tool-block' && toolElementCache?.has(node)) return toolElementCache.get(node);
271
278
 
272
279
  if (testid === "execute-command") {
273
280
  return createElement(CommandBox, {
274
281
  key: props["data-call-id"], type: node.type, props,
275
- renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion)),
282
+ renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion, toolElementCache)),
276
283
  });
277
284
  }
278
285
 
@@ -286,7 +293,7 @@ function renderTree(node, renderText, callbacks, React, reducedMotion) {
286
293
  axis: "vertical",
287
294
  mask: "vertical",
288
295
  reducedMotion,
289
- renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion)),
296
+ renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion, toolElementCache)),
290
297
  type: node.type,
291
298
  props: node.props,
292
299
  });
@@ -299,7 +306,7 @@ function renderTree(node, renderText, callbacks, React, reducedMotion) {
299
306
  axis: "vertical",
300
307
  freezeWhileReading: true,
301
308
  mask: "vertical",
302
- renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion)),
309
+ renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion, toolElementCache)),
303
310
  type: node.type,
304
311
  props: node.props,
305
312
  });
@@ -310,7 +317,7 @@ function renderTree(node, renderText, callbacks, React, reducedMotion) {
310
317
  return createElement(ScrollEnd, {
311
318
  key: props["data-item-id"] || testid,
312
319
  reducedMotion,
313
- renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion)),
320
+ renderChildren: (node.children || []).map(c => renderTree(c, renderText, callbacks, React, reducedMotion, toolElementCache)),
314
321
  type: node.type,
315
322
  props: node.props,
316
323
  });
@@ -319,8 +326,10 @@ function renderTree(node, renderText, callbacks, React, reducedMotion) {
319
326
  const isText = testid === "text-block" && props["data-role"] !== "user";
320
327
  const text = node.children?.[0]?.children?.[0];
321
328
  const children = isText && renderText ? [renderText(String(text ?? ""), { streaming: props["data-streaming"] === "true" })]
322
- : (node.children || []).map(child => renderTree(child, renderText, callbacks, React, reducedMotion));
323
- return createElement(node.type, { key: props["data-item-id"] ?? props["data-call-id"], ...props }, ...children);
329
+ : (node.children || []).map(child => renderTree(child, renderText, callbacks, React, reducedMotion, toolElementCache));
330
+ const element = createElement(node.type, { key: props["data-item-id"] ?? props["data-call-id"], ...props }, ...children);
331
+ if (testid === "tool-block") toolElementCache?.set(node, element);
332
+ return element;
324
333
  }
325
334
 
326
335
  // ── scroll mask helpers (reasoning.tsx / scrollMask.ts semantics) ───────────
package/src/renderers.mjs CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  import { h, terminalIcon, fileTextIcon, searchIcon, pencilIcon, wrenchIcon, chevronIcon, skillIcon, globeIcon } from "./view.mjs";
20
20
  import { ToolStatus } from "./protocol.mjs";
21
- import { toolTitle, toolDetailLines, workspaceRelative, redactError } from "./tool-detail.mjs";
21
+ import { toolTitle, toolDetailLines, toolInputPreview, workspaceRelative, redactError } from "./tool-detail.mjs";
22
22
  import { truncateText, latestNonEmptyLine, redactValue, boundedDetailLines } from "./summary.mjs";
23
23
  import { parseDiffHunks, countChangeStat, inferOperationKind } from "./diff.mjs";
24
24
  import { extractCommand, extractOutput } from "./terminal.mjs";
@@ -120,7 +120,8 @@ function toolShell(item, opts, { icon, summary, body, canToggle = true, defaultO
120
120
  if (action) summaryKids.push(action);
121
121
  }
122
122
  if (canToggle) summaryKids.push(chevronIcon("harness-tool-chevron"));
123
- const bodyKids = Array.isArray(body) ? body : [body];
123
+ const visibleBody = open && canToggle ? (typeof body === 'function' ? body() : body) : [];
124
+ const bodyKids = Array.isArray(visibleBody) ? visibleBody : [visibleBody];
124
125
  if (error && open && canToggle) bodyKids.push(h("div", {
125
126
  className: "harness-tool-error", role: "alert", "data-testid": "tool-error",
126
127
  }, error));
@@ -447,9 +448,9 @@ function editRenderer(item, opts) {
447
448
  // Never infer a write succeeded: the diff/count come from the result display
448
449
  // only. While running (no result), show the intent + file chips, no diff.
449
450
  const opKind = files.length ? inferOperationKind(files[0].operationKind, null, files[0].patch) : "edit";
450
- const pending = files.some(file => file.pending);
451
- const title = pending ? /write|Write/.test(item.name) ? opts.labels.writePending || 'Write requested'
452
- : opts.labels.editPending || 'Edit requested' : editKindLabel(opKind, running, opts) || toolTitle(item.name, item.input) || item.name;
451
+ const pending = item.kind === 'tool-preview' || !['file_edit', 'file_diff'].includes(item.display?.kind);
452
+ const title = pending ? /write|Write/.test(item.name) ? opts.labels?.writePending || 'Write requested'
453
+ : opts.labels?.editPending || 'Edit requested' : editKindLabel(opKind, running, opts) || toolTitle(item.name, item.input) || item.name;
453
454
  const summary = [h("span", {
454
455
  className: running
455
456
  ? "harness-tool-title harness-tool-title-streaming"
@@ -475,19 +476,27 @@ function editRenderer(item, opts) {
475
476
  totalStat.removed > 0 ? h("span", { className: "harness-diff-removed" }, `-${totalStat.removed}`) : null));
476
477
  }
477
478
 
478
- const body = [];
479
- for (const f of files) {
480
- if (!f.patch) continue;
481
- const parsed = parseDiffHunks(f.patch, { maxLines: opts.diffMaxLines || 200 });
482
- if (parsed) body.push(diffBlock(item.callId, f, { ...parsed, truncated: parsed.truncated || f.truncated }, opts));
483
- else if (f.truncated) body.push(h("p", { className: "harness-diff-truncated", "data-testid": "edit-diff-truncated" }, opts.labels.diffUnavailable || "Diff preview omitted because of its size"));
484
- }
485
- if (item.display?.omittedFiles) body.push(h("p", { className: "harness-diff-truncated", "data-testid": "edit-diff-omitted" }, `${item.display.omittedFiles} ${opts.labels.diffFilesOmitted || "file previews omitted"}`));
486
- if (!body.length && !running && files.length) {
487
- // Result arrived without a patch: surface the file chips only, no diff.
488
- }
479
+ const body = () => {
480
+ const nodes = [];
481
+ for (const f of files) {
482
+ if (!f.patch) continue;
483
+ const parsed = parseDiffHunks(f.patch, { maxLines: opts.diffMaxLines || 200 });
484
+ if (parsed) nodes.push(diffBlock(item.callId, f, { ...parsed, truncated: parsed.truncated || f.truncated }, opts));
485
+ else if (f.truncated) nodes.push(h("p", { className: "harness-diff-truncated", "data-testid": "edit-diff-truncated" }, opts.labels.diffUnavailable || "Diff preview omitted because of its size"));
486
+ }
487
+ if (item.display?.omittedFiles) nodes.push(h("p", { className: "harness-diff-truncated", "data-testid": "edit-diff-omitted" }, `${item.display.omittedFiles} ${opts.labels.diffFilesOmitted || "file previews omitted"}`));
488
+ // A committed request awaiting approval has no result diff. Keep its
489
+ // disclosure useful without representing proposed content as applied code.
490
+ if (!nodes.length && pending && item.kind !== 'tool-preview') {
491
+ const preview = toolInputPreview(item.input);
492
+ if (preview) nodes.push(h('section', { 'data-testid': 'edit-request-preview' },
493
+ h('p', null, opts.labels?.requestedArguments || 'Requested arguments (not an execution result)'),
494
+ h('pre', { style: { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', maxHeight: '24rem', overflow: 'auto' } }, preview)));
495
+ }
496
+ return nodes;
497
+ };
489
498
  return toolShell(item, opts, { icon: pencilIcon("harness-tool-kind-icon"), summary, body, canToggle: true,
490
- defaultOpen: running && !files.some(f => f.patch) ? true : (files.length > 1 ? false : running) });
499
+ defaultOpen: !pending && files.length === 1 && running });
491
500
  }
492
501
 
493
502
  function editFiles(item) {
@@ -424,7 +424,7 @@ export const statusPanelStyles = `
424
424
  .harness-status-panel__plan-icon--done{ color:var(--sp-success); }
425
425
  .harness-status-panel__plan-icon--active{ color:var(--sp-fg); }
426
426
  .harness-status-panel__plan-icon--pending{ color:var(--sp-fg-subtlest); }
427
- .harness-status-panel__plan-content{ flex:1; min-width:0; line-height:1.25; overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
427
+ .harness-status-panel__plan-content{ flex:1; min-width:0; line-height:20px; overflow:hidden; overflow-wrap:anywhere; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
428
428
  .harness-status-panel__plan-content--done{ color:var(--sp-fg-subtlest); text-decoration:line-through; }
429
429
  .harness-status-panel__plan-count{ font-variant-numeric:tabular-nums; }
430
430
  .harness-status-panel__plan-count--done{ color:var(--sp-success); }
@@ -438,6 +438,7 @@ export const statusPanelStyles = `
438
438
  .harness-status-panel__fold-trigger .harness-status-panel__fold-chevron{ width:0.875em; height:0.875em; }
439
439
  .harness-status-panel__fold-preview{
440
440
  display:none; position:absolute; left:0; bottom:100%; z-index:20;
441
+ box-sizing:border-box;
441
442
  width:20rem; max-width:min(20rem, calc(100cqw - 2rem));
442
443
  border:1px solid var(--sp-border); border-radius:0.75rem; background:var(--sp-bg);
443
444
  box-shadow:0 4px 12px rgba(0,0,0,.12); padding:0.75rem;
@@ -782,9 +783,10 @@ export function createStatusPanelComponents(React, ReactDOM = {}) {
782
783
  const template = group === "preceding" ? allCompleted ? labels.todoCompletedFold : labels.todoEarlierFold
783
784
  : allPending ? labels.todoWaitingFold : labels.todoLaterFold;
784
785
  const text = String(template).replace("{count}", String(items.length));
785
- const ref = useRef(null), previewRef = useRef(null), closeTimer = useRef(null);
786
+ const ref = useRef(null), previewRef = useRef(null), closeTimer = useRef(null), clickedOpen = useRef(false);
786
787
  const [position, setPosition] = useState(null);
787
- const close = () => { clearTimeout(closeTimer.current); closeTimer.current = setTimeout(() => setPosition(null), 120); };
788
+ const hide = () => { clickedOpen.current = false; setPosition(null); };
789
+ const close = () => { clearTimeout(closeTimer.current); closeTimer.current = setTimeout(hide, 120); };
788
790
  const show = () => {
789
791
  clearTimeout(closeTimer.current);
790
792
  const node = ref.current;
@@ -798,7 +800,7 @@ export function createStatusPanelComponents(React, ReactDOM = {}) {
798
800
  useEffect(() => () => clearTimeout(closeTimer.current), []);
799
801
  const preview = h("div", { ref: previewRef, role: "tooltip", className: "harness-status-panel__fold-preview",
800
802
  "data-fold-preview": group,
801
- style: position && ReactDOM.createPortal ? { ...position, position: "fixed", display: "block", overflowY: "auto", pointerEvents: "auto" } : undefined,
803
+ style: position && ReactDOM.createPortal ? { ...position, bottom: "auto", right: "auto", position: "fixed", display: "block", overflowY: "auto", pointerEvents: "auto" } : undefined,
802
804
  onMouseEnter: () => clearTimeout(closeTimer.current), onMouseLeave: close },
803
805
  h("div", { className: "harness-status-panel__fold-preview-header" }, text),
804
806
  h("ul", { className: "harness-status-panel__plan-list" }, items.map(i => h(PlanRow, { key: i.id, item: i }))));
@@ -806,9 +808,15 @@ export function createStatusPanelComponents(React, ReactDOM = {}) {
806
808
  return h("div", { ref, className: "harness-status-panel__fold", "data-fold-group": group,
807
809
  onMouseEnter: show, onMouseLeave: close, onFocus: show,
808
810
  onBlur: event => { if (!ref.current?.contains(event.relatedTarget) && !previewRef.current?.contains(event.relatedTarget)) close(); },
809
- onKeyDown: event => { if (event.key === "Escape") { clearTimeout(closeTimer.current); setPosition(null); } } },
811
+ onKeyDown: event => { if (event.key === "Escape") { clearTimeout(closeTimer.current); hide(); } } },
810
812
  h("button", { type: "button", className: "harness-status-panel__fold-trigger", "aria-expanded": !!position,
811
- "data-fold-trigger": group, onClick: () => position ? setPosition(null) : show() },
813
+ // Hover/focus may have opened the preview before the click. Track
814
+ // clicks separately so the first click cannot immediately close it.
815
+ "data-fold-trigger": group, onClick: () => {
816
+ clearTimeout(closeTimer.current);
817
+ if (clickedOpen.current) hide();
818
+ else { clickedOpen.current = true; show(); }
819
+ } },
812
820
  Icon("chevronLeft", { className: "harness-status-panel__fold-chevron" }), h("span", null, text)),
813
821
  root && ReactDOM.createPortal ? position && ReactDOM.createPortal(preview, root) : preview);
814
822
  }
@@ -90,6 +90,18 @@ export function toolDetailLines(name, input = {}, opts = {}) {
90
90
  return boundedDetailLines(input, { maxLines, maxChars });
91
91
  }
92
92
 
93
+ /** Read-only argument inspection shared by the timeline and inspector.
94
+ * This is a bounded, redacted request preview, never evidence of execution.
95
+ */
96
+ export function toolInputPreview(input) {
97
+ let value = input;
98
+ if (typeof value === 'string') { try { value = JSON.parse(value); } catch { /* plain argument text */ } }
99
+ let raw;
100
+ try { raw = typeof value === 'string' ? value : JSON.stringify(value ?? {}, (key, value) => redactValue(key, value), 2); }
101
+ catch { return ''; }
102
+ return truncateText(redactDiagnosticText(raw, 8192), { maxLines: 80, maxChars: 240 });
103
+ }
104
+
93
105
  function knownToolDetail(tool, input, workspaceRoot, maxLines, maxChars) {
94
106
  const pushBounded = (rows, key, value) => {
95
107
  if (rows.length >= maxLines) return rows;
package/src/view.mjs CHANGED
@@ -220,8 +220,8 @@ function activityGroupBlock(group, opts) {
220
220
  h('span', { className: group.active ? 'harness-tool-title-streaming' : undefined }, title),
221
221
  h('span', { 'aria-hidden': true }, '·'),
222
222
  h('span', { 'data-testid': 'activity-counts' }, detail), chevronIcon('harness-tool-chevron')),
223
- h('div', { className: 'harness-activity-children' }, group.family === 'browser'
224
- ? renderTimelineItems(group.events, opts, false, false) : group.children.map(item => toolBlock(item, opts)))));
223
+ open || group.family !== 'changes' ? h('div', { className: 'harness-activity-children' }, group.family === 'browser'
224
+ ? renderTimelineItems(group.events, opts, false, false) : group.children.map(item => toolBlock(item, opts))) : null));
225
225
  }
226
226
 
227
227
  function contextMarker(item, opts) {
@@ -335,7 +335,11 @@ function toolBlock(item, opts) {
335
335
  // Dispatch to the renderer registry (execute / read / edit / default). Each
336
336
  // renderer owns its summary, body, and host-action data attributes; this
337
337
  // function is now a thin seam so the view stays a single projection.
338
- return renderTool(item, opts);
338
+ const cached = opts.toolViewCache?.get(item);
339
+ if (cached) return cached;
340
+ const view = renderTool(item, opts);
341
+ opts.toolViewCache?.set(item, view);
342
+ return view;
339
343
  }
340
344
 
341
345
  function planDock(plan, opts) {