@kingsoftcloud/agentkit-harness-ui 0.0.22 → 0.0.24

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-ui",
3
- "version": "0.0.22",
3
+ "version": "0.0.24",
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.22"
101
+ "@kingsoftcloud/agentkit-harness-core": "0.0.24"
102
102
  }
103
103
  }
@@ -1,4 +1,5 @@
1
1
  import { initialState } from '../reducer.mjs';
2
+ import { imagePreviewUrl } from '../user-images.mjs';
2
3
 
3
4
  /** Only an exact durable request identity replaces its optimistic bubble.
4
5
  * Repeating the same text intentionally remains a distinct user message. */
@@ -16,7 +17,9 @@ export function pendingInputStates(inputs, eventWindow) {
16
17
  || committed.has(item.requestId) || seen.has(item.requestId) || typeof item.text !== 'string') return [];
17
18
  seen.add(item.requestId);
18
19
  return [{ requestId: item.requestId, state: { ...initialState(), items: [
19
- { kind: 'text', id: `pending:${item.requestId}`, role: 'user', text: item.text, streaming: false },
20
+ { kind: 'text', id: `pending:${item.requestId}`, role: 'user', text: item.text, streaming: false,
21
+ images: (item.attachments ?? []).filter(a => a.type === 'image' && imagePreviewUrl(a.value?.previewUrl))
22
+ .slice(0, 32).map(a => ({ previewUrl: a.value.previewUrl, name: a.value.name })) },
20
23
  ] } }];
21
24
  });
22
25
  }
@@ -119,7 +119,8 @@ export function createSessionTaskProjector({ sessionId } = {}) {
119
119
  if (value.type === 'reasoning') emit(done ? 'thinking.done' : 'thinking.delta', { itemId, ...(responseId ? { responseId } : {}), ...(sourceMessageId ? { sourceMessageId } : {}), ...(done ? { text: value.text } : { delta: value.text }) });
120
120
  };
121
121
  if (event.type === 'user/message' && ['user', 'user-rpc'].includes(data.source?.kind))
122
- emit('text.done', { itemId: `user:${data.id ?? event.seq}`, text: textOf(data.content), role: 'user' });
122
+ emit('text.done', { itemId: `user:${data.id ?? event.seq}`, text: textOf(data.content), role: 'user',
123
+ images: (data.content ?? []).filter(part => part.type === 'image').map(part => part.attachment) });
123
124
  const engine = engineTurns.get(turn);
124
125
  if (event.type === 'agentkit/native-engine-text') {
125
126
  if (event.ignorable !== true || engine?.runId !== data.runId || !task.modelThinkingId
@@ -16,7 +16,7 @@ export function createTimelineEventFeed(source, {
16
16
  const changed = () => {
17
17
  const change = source.getSnapshot().change;
18
18
  const transient = change?.kind === 'append' && change.entries.length > 0
19
- && change.entries.every(entry => entry.event?.type === 'assistant/live-chunk');
19
+ && change.entries.every(entry => ['assistant/live-chunk', 'agentkit/native-engine-text', 'agentkit/native-engine-tool-draft'].includes(entry.event?.type));
20
20
  if (!transient) { cancelPending(); publish(); return; }
21
21
  if (frame !== null) return;
22
22
  const current = generation;
@@ -44,7 +44,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
44
44
  onOpenFileLink: onOpenFile && (({ href }) => { const target = taskWorkspaceFileTarget(href, cwd); if (target) onOpenFile(target); }) }, text) });
45
45
  const markdownLabels = { copyCode: '复制代码', copied: '已复制', wrapLines: '自动换行', languageLabel: '代码' };
46
46
  function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile, openExternalLink,
47
- branchAt, renderAssistantActions, turnAnchors, pendingInputs, fallback, statusPanel }) {
47
+ branchAt, renderAssistantActions, turnAnchors, pendingInputs, fallback, statusPanel, loadImage }) {
48
48
  const [variant, setVariant] = useState(() => {
49
49
  try { const saved = localStorage.getItem('native.status-panel.variant'); return ['auto', 'mini', 'panel'].includes(saved) ? saved : 'auto'; }
50
50
  catch { return 'auto'; }
@@ -172,7 +172,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
172
172
  onOpenTerminal: terminal => commandPane.open({ ...terminal, agentId: nativeAgent, sessionId }),
173
173
  onOpenSubagentDirectory: () => childPane.openDirectory({ agentId: nativeAgent, parentSessionId: sessionId }) })), statusPanel.target) : null,
174
174
  ...presented.map(({ turn, state, reply, deliveries, deliverySeq }) => h(HarnessTurn, { key: turn,
175
- state, reply, onBranch: branchAt, assistantActions: reply?.messageId ? renderAssistantActions?.(reply.messageId) : null,
175
+ state, reply, loadImage, onBranch: branchAt, assistantActions: reply?.messageId ? renderAssistantActions?.(reply.messageId) : null,
176
176
  deliveries, resolveWebDelivery: resolveDelivery, deliverySeq, loadDeliveryEvidence: loadEvidence,
177
177
  containerProps: { 'data-chat-anchor-key': turnAnchors?.get(turn), 'data-chat-paging-anchor': true },
178
178
  labels, locale: 'zh-CN', showPlanDock: !statusPanel, theme: theme.active.colorScheme,
@@ -186,7 +186,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
186
186
  onOpenExternalUrl: openExternalLink ?? (url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); }),
187
187
  onOpenFileLink: ({ href }) => openWorkspaceFile(href) }, text) })),
188
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,
189
+ key: `pending:${requestId}`, state, loadImage, labels, locale: 'zh-CN', showPlanDock: false, theme: theme.active.colorScheme,
190
190
  containerProps: { 'aria-label': '待发送输入', 'data-pending-request-id': requestId },
191
191
  })),
192
192
  error ? h('p', { role: 'alert' }, error) : null,
package/src/project.mjs CHANGED
@@ -22,7 +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
+ if (item.kind === 'text' && !String(item.text ?? '').trim() && !(item.role === 'user' && item.images?.length)) continue;
26
26
  if (item.kind === 'thought' && !String(item.text ?? '').trim()) continue;
27
27
  const previous = visible.at(-1);
28
28
  if (item.kind === 'thought' && previous?.kind === 'thought') {
package/src/protocol.mjs CHANGED
@@ -11,6 +11,8 @@
11
11
  // The reducer accepts `v` up to its known ceiling and normalizes missing
12
12
  // optional fields. See README for host integration.
13
13
 
14
+ import { userImages } from './user-images.mjs';
15
+
14
16
  export const PROTOCOL_VERSION = 1;
15
17
 
16
18
  /**
@@ -189,7 +191,7 @@ function normalizePayload(type, event) {
189
191
  return { itemId: str(event.itemId), delta: str(event.delta) };
190
192
  case EventType.TextDone:
191
193
  return { itemId: str(event.itemId), ...(typeof event.sourceMessageId === "string" ? { sourceMessageId: event.sourceMessageId } : {}), ...(typeof event.text === "string" ? { text: event.text } : {}),
192
- ...(event.role === "user" ? { role: "user" } : {}) };
194
+ ...(event.role === "user" ? { role: "user", ...(event.images ? { images: userImages(event.images) } : {}) } : {}) };
193
195
  case EventType.ThinkingStart:
194
196
  return { itemId: str(event.itemId), provider: true };
195
197
  case EventType.ThinkingDelta:
@@ -24,6 +24,7 @@ import { styles } from "./styles.mjs";
24
24
  import { visibleItems } from "./project.mjs";
25
25
 
26
26
  import { createSummaryPlayback } from './summary-playback.mjs';
27
+ import { imagePreviewUrl } from './user-images.mjs';
27
28
 
28
29
  const FOLLOW_THRESHOLD_PX = 8;
29
30
 
@@ -93,7 +94,7 @@ export function createHarnessComponents(React) {
93
94
  const {
94
95
  state, className, workspaceRoot, labels, locale, showPlanDock, theme = "system", renderText, initiallyExpandedThoughts,
95
96
  initiallyExpandedTools, autoFollow, styleSheet, onJumpLatest, onOpenFile, onCopy,
96
- onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent,
97
+ onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent, loadImage,
97
98
  } = props || {};
98
99
  const [thoughtOpen, setThoughtOpen] = useState(() => new Map((initiallyExpandedThoughts || []).map(id => [id, true])));
99
100
  const [toolOpen, setToolOpen] = useState(() => new Map((initiallyExpandedTools || []).map(id => [id, true])));
@@ -243,8 +244,8 @@ export function createHarnessComponents(React) {
243
244
  "data-reduced-motion": reducedMotion ? "true" : "false",
244
245
  "data-theme": theme,
245
246
  };
246
- const callbacks = useMemo(() => ({ onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent }),
247
- [onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent]);
247
+ const callbacks = useMemo(() => ({ onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent, loadImage }),
248
+ [onOpenFile, onCopy, onOpenTerminal, onRetrieveFullDiff, onInspectTool, onOpenSubagent, loadImage]);
248
249
  // Tool view trees contain action descriptors, not callback closures. Stable
249
250
  // completed items can retain both their parsed view and React subtree while
250
251
  // the live tail changes. Disclosure and presentation options invalidate it.
@@ -274,6 +275,8 @@ function renderTree(node, renderText, callbacks, React, reducedMotion, toolEleme
274
275
  const { createElement } = React;
275
276
  const testid = node.props?.["data-testid"];
276
277
  const props = node.props || {};
278
+ if (testid === 'user-image') return createElement(UserImage, { key: props['data-item-id'], image: props.image,
279
+ loadImage: callbacks.loadImage, id: props['data-item-id'] });
277
280
  if (testid === 'tool-block' && toolElementCache?.has(node)) return toolElementCache.get(node);
278
281
 
279
282
  if (testid === "execute-command") {
@@ -332,6 +335,36 @@ function renderTree(node, renderText, callbacks, React, reducedMotion, toolEleme
332
335
  return element;
333
336
  }
334
337
 
338
+ function UserImage({ image, loadImage, id }) {
339
+ const { attachment, previewUrl } = image;
340
+ const [source, setSource] = useState(() => imagePreviewUrl(previewUrl ?? loadImage?.peek?.(attachment)));
341
+ const [error, setError] = useState(false), [attempt, setAttempt] = useState(0), [open, setOpen] = useState(false);
342
+ const dialog = useRef(null);
343
+ const identity = JSON.stringify(attachment ?? previewUrl);
344
+ useEffect(() => {
345
+ let active = true;
346
+ setError(false);
347
+ setSource(imagePreviewUrl(previewUrl ?? (attachment && loadImage?.peek?.(attachment))));
348
+ if (attachment && loadImage) Promise.resolve().then(() => loadImage(attachment)).then(url => {
349
+ if (active) { const valid = imagePreviewUrl(url); setSource(valid); setError(!valid); }
350
+ }).catch(() => { if (active) setError(true); });
351
+ else if (!previewUrl) setError(true);
352
+ return () => { active = false; };
353
+ }, [identity, loadImage, attempt]);
354
+ useEffect(() => {
355
+ if (open) dialog.current?.showModal?.();
356
+ else dialog.current?.close?.();
357
+ }, [open]);
358
+ const name = attachment?.name || image.name || '图片';
359
+ return createElement('span', { className: 'harness-user-image', 'data-testid': 'user-image', 'data-item-id': id },
360
+ source ? createElement('button', { type: 'button', className: 'harness-image-preview', 'aria-label': `查看图片:${name}`, onClick: () => setOpen(true) },
361
+ createElement('img', { src: source, alt: name, onError: () => { setSource(null); setError(true); } }))
362
+ : createElement('button', { type: 'button', disabled: !error, onClick: () => setAttempt(value => value + 1) }, error ? `${name} · 点击重新加载` : `${name} · 加载中…`),
363
+ open ? createElement('dialog', { ref: dialog, className: 'harness-image-dialog', 'aria-label': `图片预览:${name}`, onClose: () => setOpen(false) },
364
+ createElement('button', { type: 'button', onClick: () => setOpen(false) }, '关闭'),
365
+ createElement('img', { src: source, alt: name })) : null);
366
+ }
367
+
335
368
  // ── scroll mask helpers (reasoning.tsx / scrollMask.ts semantics) ───────────
336
369
  // The pure mask-state resolvers and style builders live at module scope (see
337
370
  // exports above) so they are testable without React. The behavior components
package/src/reducer.mjs CHANGED
@@ -249,7 +249,9 @@ function applyTextDone(state, e) {
249
249
  item.streaming = false;
250
250
  if (e.sourceMessageId) item.sourceMessageId = e.sourceMessageId;
251
251
  if (e.responseId) item.responseId = e.responseId;
252
- } else if (e.itemId && e.text) state.items.push({ kind: "text", id: e.itemId, text: e.text, role: e.role ?? "assistant", streaming: false,
252
+ if (e.role === 'user' && e.images) item.images = e.images;
253
+ } else if (e.itemId && (e.text || e.images?.length)) state.items.push({ kind: "text", id: e.itemId, text: e.text ?? '', role: e.role ?? "assistant", streaming: false,
254
+ ...(e.images?.length ? { images: e.images } : {}),
253
255
  ...(e.responseId ? { responseId: e.responseId } : {}), ...(e.sourceMessageId ? { sourceMessageId: e.sourceMessageId } : {}) });
254
256
  }
255
257
 
package/src/styles.mjs CHANGED
@@ -236,6 +236,15 @@ export const styles = `
236
236
  .harness-jump-latest:hover { border-color: var(--harness-running); color: var(--harness-running); }
237
237
 
238
238
  .harness-user-message { margin: 0 0 0 auto; padding: .8rem 1rem; max-width: 85%; border-radius: 14px; background: color-mix(in srgb, currentColor 7%, transparent); white-space: pre-wrap; overflow-wrap: anywhere; }
239
+ .harness-user-input { display:flex; flex-direction:column; align-items:flex-end; gap:8px; }
240
+ .harness-user-images { display:flex; flex-wrap:wrap; gap:8px; justify-content:flex-end; margin-bottom:8px; }
241
+ .harness-user-image { display:inline-flex; max-width:100%; }
242
+ .harness-image-preview { padding:0; border:1px solid var(--harness-border); border-radius:8px; overflow:hidden; background:transparent; cursor:zoom-in; }
243
+ .harness-image-preview img { display:block; max-width:240px; max-height:160px; width:auto; height:auto; object-fit:contain; }
244
+ .harness-image-dialog { max-width:90vw; max-height:90vh; border:1px solid var(--harness-border); border-radius:10px; padding:16px; background:var(--harness-bg, Canvas); color:inherit; }
245
+ .harness-image-dialog::backdrop { background:rgb(0 0 0 / .6); }
246
+ .harness-image-dialog > button { display:block; margin-left:auto; margin-bottom:8px; }
247
+ .harness-image-dialog img { display:block; max-width:80vw; max-height:75vh; object-fit:contain; }
239
248
 
240
249
  .harness-summary-roll { position: relative; display: inline-grid; vertical-align: middle; overflow: hidden; }
241
250
  .harness-summary-roll > span { grid-area: 1 / 1; white-space: nowrap; }
@@ -308,6 +317,7 @@ button.harness-tool-summary { border: 0; background: none; color: inherit; font:
308
317
  .harness-reply-actions button:hover, .harness-reply-actions button:focus-visible { background: color-mix(in srgb, currentColor 12%, transparent); }
309
318
  .harness-work-history-summary { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; border-bottom: 1px solid var(--harness-border); color: var(--harness-fg-muted); cursor: pointer; list-style: none; }
310
319
  .harness-work-history-summary::-webkit-details-marker { display: none; }
320
+ .harness-work-duration { cursor:default; }
311
321
  .harness-work-history-chevron { opacity: .7; }
312
322
  .harness-work-history[open] > summary .harness-work-history-chevron { transform: rotate(90deg); }
313
323
  .harness-work-history-content { padding-top: var(--harness-section-gap, 20px); }
@@ -0,0 +1,17 @@
1
+ // Durable image references only; URLs and bytes are supplied by the host's
2
+ // session-authorized loader, never recovered from model text or filesystem paths.
3
+ export function userImages(values) {
4
+ return (Array.isArray(values) ? values : []).slice(0, 32).flatMap(value => {
5
+ const image = value?.attachment ?? value;
6
+ if (!image || typeof image.attachmentId !== 'string' || !/^(?:sha256:)?[\w-]{1,256}$/.test(image.attachmentId)
7
+ || !['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(image.mediaType)
8
+ || ![image.bytes, image.width, image.height].every(n => Number.isSafeInteger(n) && n > 0)) return [];
9
+ return [{ attachment: { attachmentId: image.attachmentId, mediaType: image.mediaType,
10
+ bytes: image.bytes, width: image.width, height: image.height,
11
+ ...(typeof image.name === 'string' ? { name: image.name.slice(0, 256) } : {}) } }];
12
+ });
13
+ }
14
+
15
+ export function imagePreviewUrl(value) {
16
+ return typeof value === 'string' && /^(blob:|data:image\/(?:png|jpeg|webp|gif);base64,|https?:\/\/)/i.test(value) ? value : null;
17
+ }
package/src/view.mjs CHANGED
@@ -198,7 +198,9 @@ function timelineList(state, items, opts) {
198
198
  chevronIcon('harness-work-history-chevron')),
199
199
  open ? h('div', { className: 'harness-work-items harness-work-history-content', 'data-testid': 'work-history-content' },
200
200
  ...renderTimelineItems(segment.process, opts)) : null));
201
- } else if (segment.process.length || showModelActivity) kids.push(h('div', { className: 'harness-work-items', 'data-testid': 'work-process' },
201
+ } else if (segment.showDuration) kids.push(h('div', { className: 'harness-work-history-summary harness-work-duration', 'data-testid': 'work-duration' },
202
+ completedWorkLabel(state, opts.locale)));
203
+ else if (segment.process.length || showModelActivity) kids.push(h('div', { className: 'harness-work-items', 'data-testid': 'work-process' },
202
204
  ...renderTimelineItems(segment.process, opts, state.taskState === 'running'
203
205
  && index === segments.length - 1 && segment.following.length === 0),
204
206
  showModelActivity ? modelActivity(opts, state) : null));
@@ -266,12 +268,17 @@ function textBlock(item, opts) {
266
268
  const streaming = Boolean(item.streaming);
267
269
  const text = item.text || "";
268
270
  return h("div", {
269
- className: item.role === "user" ? "harness-user-message" : "harness-text",
271
+ className: item.role === "user" ? "harness-user-input" : "harness-text",
270
272
  "data-role": item.role || "assistant",
271
273
  "data-testid": "text-block",
272
274
  "data-item-id": item.id,
273
275
  "data-streaming": streaming ? "true" : "false",
274
- }, h("span", { className: "harness-text-content" }, text));
276
+ }, ...(item.role === 'user' && item.images?.length ? [h('div', { className: 'harness-user-images', 'data-testid': 'user-images' },
277
+ ...item.images.map((image, i) => h('span', { 'data-testid': 'user-image', 'data-item-id': `${item.id}:image:${i}`, image },
278
+ image.attachment?.name ?? image.name ?? (String(opts.locale ?? '').startsWith('zh') ? '图片' : 'Image'))))] : []),
279
+ ...(item.role === 'user' ? text ? [h('div', { className: 'harness-user-message' },
280
+ h('span', { className: 'harness-text-content' }, text))] : []
281
+ : [h('span', { className: 'harness-text-content' }, text)]));
275
282
  }
276
283
 
277
284
  function modelActivity(opts, state) {
@@ -23,7 +23,7 @@ export function conversationWorkSegments(state, items) {
23
23
  || final.sourceMessageId && item.sourceMessageId === final.sourceMessageId)) : -1;
24
24
  const process = answerIndex >= 0 ? rows.slice(0, answerIndex) : rows;
25
25
  return { ...segment, process, following: answerIndex >= 0 ? rows.slice(answerIndex) : [],
26
- collapsible: ended && process.length > 0 };
26
+ collapsible: ended && process.length > 0, showDuration: ended && rows.length > 0 };
27
27
  });
28
28
  }
29
29