@steerable/agent-shell-web 0.12.6 → 0.12.7

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": "@steerable/agent-shell-web",
3
- "version": "0.12.6",
3
+ "version": "0.12.7",
4
4
  "type": "module",
5
5
  "description": "Steerable framework — product-neutral renderer SPA source for @steerable/agent-shell (React + Vite). Consumed by product web entry points via the `@/` alias (anchored at this package's src/) and the createProductViteConfig factory. Published as a source package (src/), plus the compiled vite.base config factory (vite.base.js + .d.ts) for Node-side config loading.",
6
6
  "license": "Apache-2.0",
@@ -45,8 +45,8 @@
45
45
  "react-router-dom": "^6.30.0",
46
46
  "rehype-raw": "^7.0.0",
47
47
  "remark-gfm": "^4.0.1",
48
- "@steerable/agent-protocol": "0.12.6",
49
- "@steerable/agent-ui": "0.12.6"
48
+ "@steerable/agent-protocol": "0.12.7",
49
+ "@steerable/agent-ui": "0.12.7"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@tailwindcss/vite": "^4.3.0",
@@ -59,7 +59,7 @@
59
59
  "typescript": "^5.8.3",
60
60
  "vite": "^5.4.21",
61
61
  "vitest": "^3.2.4",
62
- "@steerable/pack-sdk": "0.12.6"
62
+ "@steerable/pack-sdk": "0.12.7"
63
63
  },
64
64
  "scripts": {
65
65
  "gen": "echo agent-shell-web",
@@ -237,8 +237,46 @@ function mentionChipClassName(ref?: MentionReference): string {
237
237
  return `${base} bg-agent-foreground/10 text-agent-foreground`;
238
238
  }
239
239
 
240
+ function isIgnoredEditorBr(root: HTMLElement, br: HTMLBRElement): boolean {
241
+ if (
242
+ br.hasAttribute('data-empty-scaffold') ||
243
+ br.hasAttribute('data-editor-sentinel')
244
+ ) {
245
+ return true;
246
+ }
247
+ return (
248
+ (root.textContent ?? '') === '' &&
249
+ root.querySelectorAll('br').length === 1 &&
250
+ !root.querySelector('[data-mention-chip]')
251
+ );
252
+ }
253
+
240
254
  function getEditableText(element: HTMLDivElement): string {
241
- return (element.textContent ?? '').replace(/\u00a0/g, ' ');
255
+ let out = '';
256
+ const walk = (node: Node) => {
257
+ if (
258
+ node instanceof HTMLElement &&
259
+ (node.getAttribute('contenteditable') === 'false' || node.tagName === 'BUTTON')
260
+ ) {
261
+ out += (node.textContent ?? '').replace(/\u00a0/g, ' ');
262
+ return;
263
+ }
264
+ if (node.nodeType === Node.TEXT_NODE) {
265
+ out += (node.textContent ?? '').replace(/\u00a0/g, ' ');
266
+ return;
267
+ }
268
+ if (node instanceof HTMLBRElement) {
269
+ if (!isIgnoredEditorBr(element, node)) {
270
+ out += '\n';
271
+ }
272
+ return;
273
+ }
274
+ for (const child of Array.from(node.childNodes)) {
275
+ walk(child);
276
+ }
277
+ };
278
+ walk(element);
279
+ return out;
242
280
  }
243
281
  function isEditorDomEmpty(editor: HTMLDivElement): boolean {
244
282
  return getEditableText(editor).length === 0;
@@ -354,6 +392,12 @@ function parseMentionSegments(
354
392
  return segments;
355
393
  }
356
394
 
395
+ function createEditorSentinelBr(): HTMLBRElement {
396
+ const br = document.createElement('br');
397
+ br.setAttribute('data-editor-sentinel', 'true');
398
+ return br;
399
+ }
400
+
357
401
  /**
358
402
  * Empty editors need a text node (IME marked-text attachment) plus a `<br>`
359
403
  * (caret height). Replacing this while focused kills the first Pinyin letter.
@@ -369,14 +413,20 @@ function writeEditorValue(
369
413
  mcpTools: McpToolItem[] = [],
370
414
  ) {
371
415
  if (next.length === 0) {
372
- editor.replaceChildren(document.createTextNode(''), document.createElement('br'));
416
+ const scaffoldBr = document.createElement('br');
417
+ scaffoldBr.setAttribute('data-empty-scaffold', 'true');
418
+ editor.replaceChildren(document.createTextNode(''), scaffoldBr);
373
419
  return;
374
420
  }
375
421
 
376
422
  const segments = parseMentionSegments(next, mentionReferences, agents, chats, skills, mcpTools);
377
423
  const hasMentions = segments.some((s) => s.type === 'mention');
378
424
  if (!hasMentions) {
379
- editor.textContent = next;
425
+ const nodes: Node[] = [document.createTextNode(next)];
426
+ if (next.endsWith('\n')) {
427
+ nodes.push(createEditorSentinelBr());
428
+ }
429
+ editor.replaceChildren(...nodes);
380
430
  return;
381
431
  }
382
432
 
@@ -455,6 +505,8 @@ function writeEditorValue(
455
505
  const last = nodes[nodes.length - 1];
456
506
  if (last instanceof HTMLButtonElement) {
457
507
  nodes.push(document.createTextNode(''));
508
+ } else if (next.endsWith('\n')) {
509
+ nodes.push(document.createTextNode(''), createEditorSentinelBr());
458
510
  }
459
511
 
460
512
  editor.replaceChildren(...nodes);
@@ -479,6 +531,85 @@ function updateEditorHeight(editor: HTMLDivElement) {
479
531
  editor.style.height = `${next}px`;
480
532
  }
481
533
 
534
+ function domNodeTextLength(root: HTMLDivElement, node: Node): number {
535
+ if (
536
+ node instanceof HTMLElement &&
537
+ (node.getAttribute('contenteditable') === 'false' || node.tagName === 'BUTTON')
538
+ ) {
539
+ return (node.textContent ?? '').length;
540
+ }
541
+ if (node.nodeType === Node.TEXT_NODE) {
542
+ return node.textContent?.length ?? 0;
543
+ }
544
+ if (node instanceof HTMLBRElement) {
545
+ return isIgnoredEditorBr(root, node) ? 0 : 1;
546
+ }
547
+ let sum = 0;
548
+ for (const child of Array.from(node.childNodes)) {
549
+ sum += domNodeTextLength(root, child);
550
+ }
551
+ return sum;
552
+ }
553
+
554
+ function domPointToTextOffset(root: HTMLDivElement, container: Node, offset: number): number {
555
+ let acc = 0;
556
+ let found = false;
557
+
558
+ const walk = (node: Node): boolean => {
559
+ if (node === container) {
560
+ if (node.nodeType === Node.TEXT_NODE) {
561
+ acc += Math.min(Math.max(offset, 0), node.textContent?.length ?? 0);
562
+ } else if (
563
+ node instanceof HTMLElement &&
564
+ (node.getAttribute('contenteditable') === 'false' || node.tagName === 'BUTTON')
565
+ ) {
566
+ acc += offset > 0 ? (node.textContent ?? '').length : 0;
567
+ } else if (node instanceof HTMLBRElement) {
568
+ acc += offset > 0 && !isIgnoredEditorBr(root, node) ? 1 : 0;
569
+ } else {
570
+ const children = Array.from(node.childNodes);
571
+ const bound = Math.min(Math.max(offset, 0), children.length);
572
+ for (let i = 0; i < bound; i += 1) {
573
+ acc += domNodeTextLength(root, children[i]);
574
+ }
575
+ }
576
+ found = true;
577
+ return true;
578
+ }
579
+
580
+ if (
581
+ node instanceof HTMLElement &&
582
+ (node.getAttribute('contenteditable') === 'false' || node.tagName === 'BUTTON')
583
+ ) {
584
+ if (node.contains(container)) {
585
+ acc += (node.textContent ?? '').length;
586
+ found = true;
587
+ return true;
588
+ }
589
+ acc += (node.textContent ?? '').length;
590
+ return false;
591
+ }
592
+
593
+ if (node.nodeType === Node.TEXT_NODE) {
594
+ acc += node.textContent?.length ?? 0;
595
+ return false;
596
+ }
597
+
598
+ if (node instanceof HTMLBRElement) {
599
+ acc += isIgnoredEditorBr(root, node) ? 0 : 1;
600
+ return false;
601
+ }
602
+
603
+ for (const child of Array.from(node.childNodes)) {
604
+ if (walk(child)) return true;
605
+ }
606
+ return false;
607
+ };
608
+
609
+ walk(root);
610
+ return found ? acc : getEditableText(root).length;
611
+ }
612
+
482
613
  function offsetFromPoint(root: HTMLDivElement, x: number, y: number): number | null {
483
614
  const doc = document as Document & {
484
615
  caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
@@ -487,23 +618,17 @@ function offsetFromPoint(root: HTMLDivElement, x: number, y: number): number | n
487
618
  if (typeof doc.caretPositionFromPoint === 'function') {
488
619
  const pos = doc.caretPositionFromPoint(x, y);
489
620
  if (!pos || !root.contains(pos.offsetNode)) return null;
490
- const measure = document.createRange();
491
- measure.selectNodeContents(root);
492
- measure.setEnd(pos.offsetNode, pos.offset);
493
- return measure.toString().length;
621
+ return domPointToTextOffset(root, pos.offsetNode, pos.offset);
494
622
  }
495
623
  const range = doc.caretRangeFromPoint?.(x, y);
496
624
  if (!range || !root.contains(range.startContainer)) return null;
497
- const measure = document.createRange();
498
- measure.selectNodeContents(root);
499
- measure.setEnd(range.startContainer, range.startOffset);
500
- return measure.toString().length;
625
+ return domPointToTextOffset(root, range.startContainer, range.startOffset);
501
626
  }
502
627
 
503
628
  function getSelectionOffsets(root: HTMLDivElement): { start: number; end: number } {
504
629
  const selection = window.getSelection();
505
630
  if (!selection || selection.rangeCount === 0) {
506
- const end = root.innerText.length;
631
+ const end = getEditableText(root).length;
507
632
  return { start: end, end };
508
633
  }
509
634
 
@@ -512,28 +637,14 @@ function getSelectionOffsets(root: HTMLDivElement): { start: number; end: number
512
637
  !root.contains(range.startContainer) ||
513
638
  !root.contains(range.endContainer)
514
639
  ) {
515
- const end = root.textContent?.length ?? 0;
640
+ const end = getEditableText(root).length;
516
641
  return { start: end, end };
517
642
  }
518
643
 
519
- const getOffset = (container: Node, offset: number) => {
520
- const measureRange = document.createRange();
521
- measureRange.selectNodeContents(root);
522
- measureRange.setEnd(container, offset);
523
- return measureRange.toString().length;
644
+ return {
645
+ start: domPointToTextOffset(root, range.startContainer, range.startOffset),
646
+ end: domPointToTextOffset(root, range.endContainer, range.endOffset),
524
647
  };
525
-
526
- try {
527
- return {
528
- start: getOffset(range.startContainer, range.startOffset),
529
- end: getOffset(range.endContainer, range.endOffset),
530
- };
531
- } catch {
532
- // The caret can sit on the empty scaffold's <br> with an offset the
533
- // range rejects. Paste still belongs at the end of the draft.
534
- const end = getEditableText(root).length;
535
- return { start: end, end };
536
- }
537
648
  }
538
649
 
539
650
  function setCaretOffset(root: HTMLDivElement, offset: number) {
@@ -577,7 +688,16 @@ function setCaretOffset(root: HTMLDivElement, offset: number) {
577
688
  }
578
689
 
579
690
  if (node instanceof HTMLBRElement) {
580
- if (remaining <= 1) {
691
+ if (isIgnoredEditorBr(root, node)) {
692
+ return false;
693
+ }
694
+ if (remaining === 0) {
695
+ range.setStartBefore(node);
696
+ range.collapse(true);
697
+ placed = true;
698
+ return true;
699
+ }
700
+ if (remaining === 1) {
581
701
  range.setStartAfter(node);
582
702
  range.collapse(true);
583
703
  placed = true;
@@ -885,6 +1005,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
885
1005
  // this guard that Enter falls through to the "insert newline" branch below
886
1006
  // and the user ends up with a stray blank line after committing text.
887
1007
  const compositionEndAtRef = useRef<number>(0);
1008
+ const enterPressedDuringCompositionRef = useRef(false);
1009
+ const swallowPostCompositionEnterRef = useRef(false);
888
1010
 
889
1011
  const fileInputRef = useRef<HTMLInputElement>(null);
890
1012
  const dropBoxRef = useRef<HTMLDivElement>(null);
@@ -1182,11 +1304,16 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1182
1304
  return;
1183
1305
  }
1184
1306
 
1307
+ const needsTrailingSentinel =
1308
+ value.endsWith('\n') &&
1309
+ !editor.querySelector('br[data-editor-sentinel="true"]');
1310
+
1185
1311
  const wrote =
1186
1312
  editorText !== value ||
1187
1313
  pendingCaretOffset !== null ||
1314
+ needsTrailingSentinel ||
1188
1315
  (!value && !hasEmptyImeScaffold(editor));
1189
- if (editorText !== value || pendingCaretOffset !== null) {
1316
+ if (editorText !== value || pendingCaretOffset !== null || needsTrailingSentinel) {
1190
1317
  writeEditorValue(
1191
1318
  editor,
1192
1319
  value,
@@ -1397,9 +1524,19 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1397
1524
  return { start: caret, end: caret };
1398
1525
  };
1399
1526
 
1527
+ const flushPendingInputSync = () => {
1528
+ if (inputSyncTimerRef.current === null) return;
1529
+ cancelPendingInputSync();
1530
+ if (!isComposingRef.current) {
1531
+ editorRef.current?.removeAttribute('data-composing');
1532
+ syncFromEditor();
1533
+ }
1534
+ };
1535
+
1400
1536
  const replaceSelection = (insertText: string) => {
1401
1537
  const editor = editorRef.current;
1402
1538
  if (!editor) return;
1539
+ flushPendingInputSync();
1403
1540
  const { start, end } = editCaret(editor);
1404
1541
  applyEdit((current) => ({
1405
1542
  next: `${current.slice(0, start)}${insertText}${current.slice(end)}`,
@@ -1428,6 +1565,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1428
1565
  };
1429
1566
 
1430
1567
  const handleEditorPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
1568
+ swallowPostCompositionEnterRef.current = false;
1431
1569
  if (event.button !== 0) return;
1432
1570
  const editor = editorRef.current;
1433
1571
  if (!editor) return;
@@ -1470,6 +1608,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1470
1608
 
1471
1609
  const markComposing = () => {
1472
1610
  isComposingRef.current = true;
1611
+ enterPressedDuringCompositionRef.current = false;
1612
+ swallowPostCompositionEnterRef.current = false;
1473
1613
  cancelPendingInputSync();
1474
1614
  editorRef.current?.setAttribute('data-composing', 'true');
1475
1615
  };
@@ -1542,6 +1682,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1542
1682
  const handleCompositionEnd = () => {
1543
1683
  isComposingRef.current = false;
1544
1684
  compositionEndAtRef.current = Date.now();
1685
+ swallowPostCompositionEnterRef.current = !enterPressedDuringCompositionRef.current;
1686
+ enterPressedDuringCompositionRef.current = false;
1545
1687
  editorRef.current?.removeAttribute('data-composing');
1546
1688
  syncFromEditor();
1547
1689
  // Safari can flush the committed glyphs after compositionend.
@@ -1566,6 +1708,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1566
1708
  setComposerPasteTarget(editor);
1567
1709
  const onCompositionStart = () => {
1568
1710
  isComposingRef.current = true;
1711
+ enterPressedDuringCompositionRef.current = false;
1712
+ swallowPostCompositionEnterRef.current = false;
1569
1713
  inputSyncGenRef.current += 1;
1570
1714
  if (inputSyncTimerRef.current !== null) {
1571
1715
  clearTimeout(inputSyncTimerRef.current);
@@ -1648,6 +1792,13 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1648
1792
  // no-op without mirror overlay
1649
1793
  };
1650
1794
 
1795
+ const handleKeyUp = (event: KeyboardEvent<HTMLDivElement>) => {
1796
+ if (event.key === 'Enter') {
1797
+ enterPressedDuringCompositionRef.current = false;
1798
+ swallowPostCompositionEnterRef.current = false;
1799
+ }
1800
+ };
1801
+
1651
1802
  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
1652
1803
  // Cmd/Ctrl+V never reaches a paste event when the app menu owns the
1653
1804
  // shortcut, and WKWebView leaves that event's clipboard empty. Read the
@@ -1661,14 +1812,21 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1661
1812
  requestHostPaste(event.currentTarget);
1662
1813
  return;
1663
1814
  }
1664
- // An open composition session owns the keystroke, including Enter used
1665
- // to confirm the highlighted candidate. Returning without
1666
- // preventDefault lets the IME commit the word. WKWebView can report
1667
- // isComposing / keyCode 229 on Enter after the session has already
1668
- // ended; that case is not an open session (`isComposingRef` is false)
1669
- // and must still send.
1670
- if (isComposingRef.current) return;
1671
- if (event.key !== 'Enter' && event.nativeEvent.isComposing) return;
1815
+ // An open composition session (including Chinese IME English sub-buffers
1816
+ // where nativeEvent.isComposing is true) owns the keystroke, including
1817
+ // Enter used to confirm raw English or highlighted candidates. WKWebView
1818
+ // reports keyCode 229 with isComposing === false on plain Enter, which
1819
+ // passes through here and still submits.
1820
+ if (isComposingRef.current || event.nativeEvent.isComposing) {
1821
+ if (event.key === 'Enter') {
1822
+ enterPressedDuringCompositionRef.current = true;
1823
+ }
1824
+ return;
1825
+ }
1826
+
1827
+ if (event.key !== 'Enter') {
1828
+ swallowPostCompositionEnterRef.current = false;
1829
+ }
1672
1830
 
1673
1831
  if (event.key === 'Backspace' || event.key === 'Delete') {
1674
1832
  const editor = editorRef.current;
@@ -1700,10 +1858,17 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1700
1858
  ) {
1701
1859
  editorRef.current?.setAttribute('data-composing', 'true');
1702
1860
  }
1703
- // See `compositionEndAtRef` above: treat an Enter that lands right after
1704
- // `compositionend` as "confirm candidate", not "submit/newline".
1705
- if (event.key === 'Enter' && Date.now() - compositionEndAtRef.current < 50) {
1706
- return;
1861
+ // Treat an Enter that lands right after `compositionend` (same physical
1862
+ // keystroke confirming IME text) as "confirm candidate", not "submit/newline".
1863
+ if (event.key === 'Enter') {
1864
+ const sinceCompositionEnd = Date.now() - compositionEndAtRef.current;
1865
+ if (
1866
+ (swallowPostCompositionEnterRef.current && sinceCompositionEnd < 300) ||
1867
+ sinceCompositionEnd < 50
1868
+ ) {
1869
+ swallowPostCompositionEnterRef.current = false;
1870
+ return;
1871
+ }
1707
1872
  }
1708
1873
 
1709
1874
  if (mentionQuery && mentionSuggestions.length > 0) {
@@ -1761,6 +1926,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1761
1926
  event.key === 'Enter' && !event.shiftKey;
1762
1927
  if (isSendCombo) {
1763
1928
  event.preventDefault();
1929
+ flushPendingInputSync();
1764
1930
  const submittedText = getEditableText(event.currentTarget).trim();
1765
1931
  // streaming 期间:Enter = follow-up 排队(本轮结束后自动作为下一轮
1766
1932
  // 发出);⌘/Ctrl+Enter = 轮中插队(注入运行中的回合;注入不了时
@@ -1788,7 +1954,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1788
1954
  }
1789
1955
  return;
1790
1956
  }
1791
- if (canSend) {
1957
+ if (!disabled && (Boolean(submittedText) || actualFiles.length > 0)) {
1792
1958
  void onSubmit();
1793
1959
  }
1794
1960
  return;
@@ -2112,6 +2278,7 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
2112
2278
  onBeforeInput={handleBeforeInput}
2113
2279
  onPaste={handlePaste}
2114
2280
  onKeyDown={handleKeyDown}
2281
+ onKeyUp={handleKeyUp}
2115
2282
  onCompositionStart={handleCompositionStart}
2116
2283
  onCompositionEnd={handleCompositionEnd}
2117
2284
  onScroll={handleEditorScroll}
@@ -156,6 +156,8 @@ export interface LocalChatPanelProps {
156
156
  inputBanner?: ReactNode;
157
157
  /** W1.2.1: regenerate an assistant turn (fork-preserving). */
158
158
  onRegenerate?: (messageId: string) => Promise<void>;
159
+ /** Edit the latest user message and resubmit (fork-preserving). */
160
+ onEditUserMessage?: (messageId: string, nextContent: string) => void | Promise<void>;
159
161
  /** W7-1: 上一轮被中断(崩溃/强杀)——消息列表尾部展示「继续上次回复」卡片。 */
160
162
  interrupted?: boolean;
161
163
  /** W7-1: 点击「继续上次回复」。 */
@@ -231,6 +233,7 @@ export function LocalChatPanel({
231
233
  pendingFollowUps,
232
234
  onRemoveFollowUp,
233
235
  onRegenerate,
236
+ onEditUserMessage,
234
237
  interrupted,
235
238
  onContinueInterrupted,
236
239
  onDismissInterrupted,
@@ -543,6 +546,7 @@ export function LocalChatPanel({
543
546
  emptyState={emptyState ?? <EmptyChat onSelectPrompt={handleSelectPrompt} />}
544
547
  mode={mode}
545
548
  onRegenerate={onRegenerate}
549
+ onEditUserMessage={onEditUserMessage}
546
550
  interrupted={interrupted}
547
551
  onContinueInterrupted={onContinueInterrupted}
548
552
  onDismissInterrupted={onDismissInterrupted}
@@ -175,6 +175,8 @@ interface MessageListProps {
175
175
  mode?: ChatMode;
176
176
  /** W1.2.1: regenerate an assistant turn (fork-preserving). */
177
177
  onRegenerate?: (messageId: string) => Promise<void>;
178
+ /** Edit the latest user message and resubmit (fork-preserving). */
179
+ onEditUserMessage?: (messageId: string, nextContent: string) => void | Promise<void>;
178
180
  /**
179
181
  * W7-1: the chat's last turn was interrupted (crash/kill — no completion
180
182
  * record). Rendered as a tail card offering to continue the turn; hidden
@@ -236,6 +238,7 @@ export function MessageList({
236
238
  failureAction,
237
239
  mode,
238
240
  onRegenerate,
241
+ onEditUserMessage,
239
242
  interrupted = false,
240
243
  onContinueInterrupted,
241
244
  onDismissInterrupted,
@@ -418,6 +421,16 @@ export function MessageList({
418
421
  return turns;
419
422
  }, [visibleMessages]);
420
423
 
424
+ const lastUserId = useMemo(() => {
425
+ for (let i = visibleMessages.length - 1; i >= 0; i -= 1) {
426
+ const m = visibleMessages[i];
427
+ if (m.role === 'user' && internalTrigger(m) === null) {
428
+ return m.id;
429
+ }
430
+ }
431
+ return null;
432
+ }, [visibleMessages]);
433
+
421
434
  return (
422
435
  <div className="relative flex-1 overflow-hidden">
423
436
  <div
@@ -446,6 +459,11 @@ export function MessageList({
446
459
  message={turn.userGroup.messages[0]}
447
460
  agents={agents}
448
461
  chats={chats}
462
+ onEdit={
463
+ turn.userGroup.messages[0].id === lastUserId && onEditUserMessage
464
+ ? (nextText) => onEditUserMessage(turn.userGroup!.messages[0].id, nextText)
465
+ : undefined
466
+ }
449
467
  />
450
468
  )
451
469
  ) : (
@@ -467,6 +485,11 @@ export function MessageList({
467
485
  chats={chats}
468
486
  isGrouped
469
487
  isAppended={idx > 0}
488
+ onEdit={
489
+ msg.id === lastUserId && onEditUserMessage
490
+ ? (nextText) => onEditUserMessage(msg.id, nextText)
491
+ : undefined
492
+ }
470
493
  />
471
494
  )
472
495
  ))}
@@ -1,6 +1,13 @@
1
- import { useLayoutEffect, useRef, useState } from 'react';
1
+ import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from 'react';
2
2
  import { motion } from 'framer-motion';
3
- import { LuChevronDown, LuChevronUp, LuCheck, LuCopy, LuCornerDownRight } from 'react-icons/lu';
3
+ import {
4
+ LuChevronDown,
5
+ LuChevronUp,
6
+ LuCheck,
7
+ LuCopy,
8
+ LuCornerDownRight,
9
+ LuPencil,
10
+ } from 'react-icons/lu';
4
11
  import type { ChatMessage } from '@steerable/agent-protocol';
5
12
  import type { LocalChat, LocalChatAgent } from '@/lib/local-api';
6
13
  import { t } from '@/i18n';
@@ -9,19 +16,6 @@ import { Markdown } from './Markdown';
9
16
  import { getFriendlyDate } from './timestamp';
10
17
  import { useCopy } from './useCopy';
11
18
 
12
- /**
13
- * UserMessage — port of `deeppath`'s user-bubble component, trimmed to the
14
- * agent-only surface.
15
- *
16
- * Grouping (方案 A):
17
- * When multiple user messages occur consecutively without an assistant reply
18
- * in between, MessageList renders them as a single connected card:
19
- * - The first message has `isGroupStart = true`
20
- * - Mid-turn / follow-up steered additions have `isAppended = true`
21
- * - The outer container groups them with a subtle dashed divider and a
22
- * 「↳ 追加」 badge.
23
- */
24
-
25
19
  interface UserMessageProps {
26
20
  message: ChatMessage;
27
21
  agents?: LocalChatAgent[];
@@ -30,6 +24,8 @@ interface UserMessageProps {
30
24
  isGrouped?: boolean;
31
25
  /** Whether this message is an appended follow-up inside the group (not the first one). */
32
26
  isAppended?: boolean;
27
+ /** Edit and resubmit callback (offered on the latest user message). */
28
+ onEdit?: (nextContent: string) => void | Promise<void>;
33
29
  }
34
30
 
35
31
  export function UserMessage({
@@ -38,41 +34,151 @@ export function UserMessage({
38
34
  chats = [],
39
35
  isGrouped = false,
40
36
  isAppended = false,
37
+ onEdit,
41
38
  }: UserMessageProps) {
42
39
  const content = message.content || '';
43
- // 发出去的消息里 `/技能` `/mcp__srv__tool` 要和输入框里同样渲染成工具卡片。
44
- // 目录来自共享缓存,整屏消息只拉一次。
45
40
  const { skills, mcpTools } = useSlashSources();
46
41
 
47
42
  const [isExpanded, setIsExpanded] = useState(false);
48
43
  const [isOverflowing, setIsOverflowing] = useState(false);
44
+ const [isEditing, setIsEditing] = useState(false);
45
+ const [draft, setDraft] = useState(content);
46
+ const [isSubmittingEdit, setIsSubmittingEdit] = useState(false);
47
+
49
48
  const contentRef = useRef<HTMLDivElement>(null);
49
+ const editTextareaRef = useRef<HTMLTextAreaElement>(null);
50
+ const isComposingRef = useRef(false);
51
+ const compositionEndAtRef = useRef(0);
52
+ const swallowPostCompositionEnterRef = useRef(false);
53
+ const enterPressedDuringCompositionRef = useRef(false);
50
54
  const { copied, copy } = useCopy(content);
51
55
 
52
56
  useLayoutEffect(() => {
53
57
  const el = contentRef.current;
54
- if (!el || isExpanded) return;
58
+ if (!el || isExpanded || isEditing) return;
55
59
  setIsOverflowing(el.scrollHeight > el.clientHeight + 1);
56
- }, [content, isExpanded]);
60
+ }, [content, isExpanded, isEditing]);
57
61
 
58
- // When rendered as an item inside a group, the parent handles the outer card.
59
- if (isGrouped) {
60
- return (
61
- <div
62
- className={`group/message relative px-3 py-2 text-xs text-agent-foreground ${
63
- isAppended ? 'border-t border-dashed border-agent-border/60 bg-agent-muted/30' : ''
64
- }`}
65
- data-message-role="user"
66
- data-message-id={message.id}
67
- >
68
- {isAppended && (
69
- <div className="mb-1 flex items-center gap-1 text-[11px] font-medium text-agent-muted-foreground select-none">
70
- <LuCornerDownRight className="h-3 w-3 text-agent-primary/80" />
71
- <span className="rounded bg-agent-primary/10 px-1 py-0.5 text-[10px] text-agent-primary font-medium">
72
- {t('Appended')}
73
- </span>
62
+ useEffect(() => {
63
+ if (!isEditing) return;
64
+ const textarea = editTextareaRef.current;
65
+ if (!textarea) return;
66
+ textarea.focus();
67
+ const len = textarea.value.length;
68
+ textarea.setSelectionRange(len, len);
69
+ }, [isEditing]);
70
+
71
+ const startEditing = () => {
72
+ setDraft(content);
73
+ setIsEditing(true);
74
+ };
75
+
76
+ const cancelEditing = () => {
77
+ setIsEditing(false);
78
+ setDraft(content);
79
+ };
80
+
81
+ const submitEditing = async () => {
82
+ const trimmed = draft.trim();
83
+ if (!trimmed || !onEdit || isSubmittingEdit) return;
84
+ setIsSubmittingEdit(true);
85
+ try {
86
+ setIsEditing(false);
87
+ await onEdit(trimmed);
88
+ } finally {
89
+ setIsSubmittingEdit(false);
90
+ }
91
+ };
92
+
93
+ const handleEditKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
94
+ if (isComposingRef.current || event.nativeEvent.isComposing) {
95
+ if (event.key === 'Enter') {
96
+ enterPressedDuringCompositionRef.current = true;
97
+ }
98
+ return;
99
+ }
100
+ if (event.key !== 'Enter') {
101
+ swallowPostCompositionEnterRef.current = false;
102
+ }
103
+ if (event.key === 'Escape') {
104
+ event.preventDefault();
105
+ event.stopPropagation();
106
+ cancelEditing();
107
+ return;
108
+ }
109
+ if (event.key === 'Enter') {
110
+ const sinceEnd = Date.now() - compositionEndAtRef.current;
111
+ if (
112
+ (swallowPostCompositionEnterRef.current && sinceEnd < 300) ||
113
+ sinceEnd < 50
114
+ ) {
115
+ swallowPostCompositionEnterRef.current = false;
116
+ return;
117
+ }
118
+ if (!event.shiftKey) {
119
+ event.preventDefault();
120
+ void submitEditing();
121
+ }
122
+ }
123
+ };
124
+
125
+ const handleEditKeyUp = (event: KeyboardEvent<HTMLTextAreaElement>) => {
126
+ if (event.key === 'Enter') {
127
+ enterPressedDuringCompositionRef.current = false;
128
+ swallowPostCompositionEnterRef.current = false;
129
+ }
130
+ };
131
+
132
+ const renderMessageBody = () => {
133
+ if (isEditing) {
134
+ return (
135
+ <div className="space-y-2" data-testid="user-message-editor">
136
+ <textarea
137
+ ref={editTextareaRef}
138
+ value={draft}
139
+ rows={Math.min(Math.max(draft.split('\n').length, 2), 8)}
140
+ onChange={(e) => setDraft(e.target.value)}
141
+ onKeyDown={handleEditKeyDown}
142
+ onKeyUp={handleEditKeyUp}
143
+ onCompositionStart={() => {
144
+ isComposingRef.current = true;
145
+ enterPressedDuringCompositionRef.current = false;
146
+ swallowPostCompositionEnterRef.current = false;
147
+ }}
148
+ onCompositionEnd={() => {
149
+ isComposingRef.current = false;
150
+ compositionEndAtRef.current = Date.now();
151
+ swallowPostCompositionEnterRef.current = !enterPressedDuringCompositionRef.current;
152
+ enterPressedDuringCompositionRef.current = false;
153
+ }}
154
+ data-testid="edit-user-message-input"
155
+ className="w-full resize-y rounded-agent-md border border-agent-border bg-agent-background px-2.5 py-1.5 text-xs text-agent-foreground outline-none focus:border-agent-primary"
156
+ />
157
+ <div className="flex items-center justify-end gap-2">
158
+ <button
159
+ type="button"
160
+ onClick={cancelEditing}
161
+ data-action="cancel-edit-user-message"
162
+ className="rounded-agent-sm border border-agent-border px-2 py-0.5 text-[11px] text-agent-muted-foreground transition-colors hover:bg-agent-foreground/5 hover:text-agent-foreground"
163
+ >
164
+ {t('Cancel')}
165
+ </button>
166
+ <button
167
+ type="button"
168
+ disabled={!draft.trim() || isSubmittingEdit}
169
+ onClick={() => void submitEditing()}
170
+ data-action="save-edit-user-message"
171
+ className="rounded-agent-sm bg-agent-primary px-2.5 py-0.5 text-[11px] font-medium text-agent-primary-foreground transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
172
+ >
173
+ {t('Save and submit')}
174
+ </button>
74
175
  </div>
75
- )}
176
+ </div>
177
+ );
178
+ }
179
+
180
+ return (
181
+ <>
76
182
  <div className="relative">
77
183
  <div
78
184
  ref={contentRef}
@@ -124,30 +230,66 @@ export function UserMessage({
124
230
  )}
125
231
 
126
232
  <div className="mt-1 flex items-center justify-between">
127
- <button
128
- type="button"
129
- onClick={() => void copy()}
130
- className="inline-flex items-center gap-0.5 rounded text-xs text-agent-muted-foreground opacity-0 transition-all duration-200 hover:text-agent-foreground focus:opacity-100 group-hover/message:opacity-100"
131
- title={copied ? t('Copied') : t('Copy message')}
132
- aria-label={copied ? t('Copied') : t('Copy message')}
133
- >
134
- {copied ? (
135
- <>
136
- <LuCheck className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
137
- <span className="text-emerald-600 dark:text-emerald-400">
138
- {t('Copied')}
139
- </span>
140
- </>
141
- ) : (
142
- <LuCopy className="h-3 w-3" />
233
+ <div className="flex items-center gap-2">
234
+ <button
235
+ type="button"
236
+ onClick={() => void copy()}
237
+ className="inline-flex items-center gap-0.5 rounded text-xs text-agent-muted-foreground opacity-0 transition-all duration-200 hover:text-agent-foreground focus:opacity-100 group-hover/message:opacity-100"
238
+ title={copied ? t('Copied') : t('Copy message')}
239
+ aria-label={copied ? t('Copied') : t('Copy message')}
240
+ >
241
+ {copied ? (
242
+ <>
243
+ <LuCheck className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
244
+ <span className="text-emerald-600 dark:text-emerald-400">
245
+ {t('Copied')}
246
+ </span>
247
+ </>
248
+ ) : (
249
+ <LuCopy className="h-3 w-3" />
250
+ )}
251
+ </button>
252
+ {onEdit && (
253
+ <button
254
+ type="button"
255
+ onClick={startEditing}
256
+ data-action="edit-user-message"
257
+ className="inline-flex items-center gap-0.5 rounded text-xs text-agent-muted-foreground opacity-0 transition-all duration-200 hover:text-agent-foreground focus:opacity-100 group-hover/message:opacity-100"
258
+ title={t('Edit and resubmit')}
259
+ aria-label={t('Edit message')}
260
+ >
261
+ <LuPencil className="h-3 w-3" />
262
+ </button>
143
263
  )}
144
- </button>
264
+ </div>
145
265
  <div className="text-[11px] text-agent-muted-foreground">
146
266
  {message.createdAt
147
267
  ? getFriendlyDate(new Date(message.createdAt))
148
268
  : getFriendlyDate(new Date())}
149
269
  </div>
150
270
  </div>
271
+ </>
272
+ );
273
+ };
274
+
275
+ if (isGrouped) {
276
+ return (
277
+ <div
278
+ className={`group/message relative px-3 py-2 text-xs text-agent-foreground ${
279
+ isAppended ? 'border-t border-dashed border-agent-border/60 bg-agent-muted/30' : ''
280
+ }`}
281
+ data-message-role="user"
282
+ data-message-id={message.id}
283
+ >
284
+ {isAppended && (
285
+ <div className="mb-1 flex items-center gap-1 text-[11px] font-medium text-agent-muted-foreground select-none">
286
+ <LuCornerDownRight className="h-3 w-3 text-agent-primary/80" />
287
+ <span className="rounded bg-agent-primary/10 px-1 py-0.5 text-[10px] text-agent-primary font-medium">
288
+ {t('Appended')}
289
+ </span>
290
+ </div>
291
+ )}
292
+ {renderMessageBody()}
151
293
  </div>
152
294
  );
153
295
  }
@@ -163,81 +305,7 @@ export function UserMessage({
163
305
  >
164
306
  <div className="flex justify-start">
165
307
  <div className="mx-auto w-full max-w-[var(--chat-input-box-width)] rounded-agent-lg border border-agent-border/80 bg-agent-muted/70 px-3 py-2 text-xs text-agent-foreground">
166
- <div className="relative">
167
- <div
168
- ref={contentRef}
169
- className={`markdown-content pl-1 ${
170
- !isExpanded ? 'overflow-hidden' : ''
171
- }`}
172
- style={!isExpanded ? { maxHeight: '4.5em' } : undefined}
173
- >
174
- {content ? (
175
- <Markdown
176
- inlineParagraph
177
- agents={agents}
178
- chats={chats}
179
- skills={skills}
180
- mcpTools={mcpTools}
181
- >
182
- {content}
183
- </Markdown>
184
- ) : (
185
- <div className="h-4" />
186
- )}
187
- </div>
188
- {!isExpanded && isOverflowing && (
189
- <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-5 bg-gradient-to-t from-agent-muted to-transparent" />
190
- )}
191
- </div>
192
-
193
- {isOverflowing && (
194
- <button
195
- type="button"
196
- onClick={(event) => {
197
- event.stopPropagation();
198
- setIsExpanded((prev) => !prev);
199
- }}
200
- className="mt-1 inline-flex items-center gap-0.5 text-xs text-agent-muted-foreground transition-colors hover:text-agent-foreground"
201
- >
202
- {isExpanded ? (
203
- <>
204
- {t('Collapse')}
205
- <LuChevronUp className="h-3 w-3" />
206
- </>
207
- ) : (
208
- <>
209
- {t('Expand all')}
210
- <LuChevronDown className="h-3 w-3" />
211
- </>
212
- )}
213
- </button>
214
- )}
215
-
216
- <div className="mt-1 flex items-center justify-between">
217
- <button
218
- type="button"
219
- onClick={() => void copy()}
220
- className="inline-flex items-center gap-0.5 rounded text-xs text-agent-muted-foreground opacity-0 transition-all duration-200 hover:text-agent-foreground focus:opacity-100 group-hover/message:opacity-100"
221
- title={copied ? t('Copied') : t('Copy message')}
222
- aria-label={copied ? t('Copied') : t('Copy message')}
223
- >
224
- {copied ? (
225
- <>
226
- <LuCheck className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
227
- <span className="text-emerald-600 dark:text-emerald-400">
228
- {t('Copied')}
229
- </span>
230
- </>
231
- ) : (
232
- <LuCopy className="h-3 w-3" />
233
- )}
234
- </button>
235
- <div className="text-[11px] text-agent-muted-foreground">
236
- {message.createdAt
237
- ? getFriendlyDate(new Date(message.createdAt))
238
- : getFriendlyDate(new Date())}
239
- </div>
240
- </div>
308
+ {renderMessageBody()}
241
309
  </div>
242
310
  </div>
243
311
  </motion.div>
@@ -224,13 +224,18 @@ export interface HostChatTransport extends ChatStreamTransport {
224
224
  * 直接调它把主进程里的 agent 循环真正停下来。
225
225
  */
226
226
  cancelActive: () => void;
227
+ /** 等待当前正在进行的流彻底结束(若空闲则立即完成)。 */
228
+ waitForIdle: () => Promise<void>;
227
229
  }
228
230
 
229
231
  export function createHostChatTransport(chatId: string): HostChatTransport {
230
232
  // 当前 in-flight 流的 id。startStream resolve 后写入,流结束(end/error)
231
233
  // 或被取消后清空。同一 transport 一次只会有一条流(useChatStream 在
232
234
  // isStreaming 时拒绝重入)。
233
- const active: { streamId: string | null } = { streamId: null };
235
+ const active: { streamId: string | null; inFlight: Promise<void> | null } = {
236
+ streamId: null,
237
+ inFlight: null,
238
+ };
234
239
 
235
240
  return {
236
241
  cancelActive: () => {
@@ -252,6 +257,11 @@ export function createHostChatTransport(chatId: string): HostChatTransport {
252
257
  .catch(() => {});
253
258
  }
254
259
  },
260
+ waitForIdle: async () => {
261
+ if (active.inFlight) {
262
+ await active.inFlight.catch(() => {});
263
+ }
264
+ },
255
265
  // 轮中转向:仅在 CoreLoop 路径(STEERABLE_USE_CORELOOP=1)且回合仍
256
266
  // 运行时生效;否则主进程软失败,useChatStream 保留草稿。
257
267
  steer: async (content: string, options?: { execPolicy?: 'workspace' | 'full' }) => {
@@ -277,12 +287,24 @@ export function createHostChatTransport(chatId: string): HostChatTransport {
277
287
  // the cancel handle returned at the end. Declaring it up-front sidesteps
278
288
  // any temporal-dead-zone surprises.
279
289
  const ref: { streamId: string | null } = { streamId: null };
290
+ const rawMetadata = input.metadata ?? {};
291
+ const replaceMessageId =
292
+ typeof rawMetadata.replaceMessageId === 'string' && rawMetadata.replaceMessageId
293
+ ? rawMetadata.replaceMessageId
294
+ : null;
295
+ const { replaceMessageId: _omitted, ...forwardedMetadata } = rawMetadata;
296
+ const streamPath = replaceMessageId
297
+ ? `/api/v2/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(replaceMessageId)}/edit`
298
+ : `/api/v2/chats/${encodeURIComponent(chatId)}/run`;
280
299
 
281
- await new Promise<void>((resolve, reject) => {
300
+ const runPromise = new Promise<void>((resolve, reject) => {
282
301
  let settled = false;
283
302
  const settle = (err?: Error) => {
284
303
  if (settled) return;
285
304
  settled = true;
305
+ if (active.inFlight === runPromise) {
306
+ active.inFlight = null;
307
+ }
286
308
  if (err) reject(err);
287
309
  else resolve();
288
310
  };
@@ -291,10 +313,10 @@ export function createHostChatTransport(chatId: string): HostChatTransport {
291
313
  .startStream(
292
314
  {
293
315
  method: 'POST',
294
- path: `/api/v2/chats/${encodeURIComponent(chatId)}/run`,
316
+ path: streamPath,
295
317
  body: {
296
318
  message: input.content,
297
- ...(input.metadata ?? {}),
319
+ ...forwardedMetadata,
298
320
  },
299
321
  },
300
322
  (payload) => {
@@ -325,6 +347,8 @@ export function createHostChatTransport(chatId: string): HostChatTransport {
325
347
  settle(new Error(msg));
326
348
  });
327
349
  });
350
+ active.inFlight = runPromise;
351
+ await runPromise;
328
352
 
329
353
  // Return cancel handle per the transport contract. Note: framework's
330
354
  // hook stores this AFTER stream completion, so it's a no-op in practice.
@@ -515,6 +515,7 @@ function AgentChatView({
515
515
  const inner = createHostChatTransport(chatId);
516
516
  return {
517
517
  cancelActive: () => inner.cancelActive(),
518
+ waitForIdle: () => inner.waitForIdle(),
518
519
  stream: (
519
520
  input: { content: string; metadata?: Record<string, unknown> },
520
521
  onEvent: (event: SSEEvent) => void,
@@ -1089,6 +1090,30 @@ function AgentChatView({
1089
1090
  [sendUserMessage, modelOverride, effortOverride, execPolicy],
1090
1091
  );
1091
1092
 
1093
+ const handleEditUserMessage = useCallback(
1094
+ async (messageId: string, nextContent: string) => {
1095
+ const trimmed = nextContent.trim();
1096
+ if (!trimmed) return;
1097
+ if (isStreaming) {
1098
+ handleCancel();
1099
+ await transport.waitForIdle();
1100
+ await Promise.resolve();
1101
+ }
1102
+ const idx = messages.findIndex((m) => m.id === messageId);
1103
+ if (idx !== -1) {
1104
+ setMessages(messages.slice(0, idx));
1105
+ }
1106
+ await handleSubmit({
1107
+ content: trimmed,
1108
+ metadata: {
1109
+ ...(mode === "plan" ? { mode: "plan" } : {}),
1110
+ replaceMessageId: "latest",
1111
+ },
1112
+ });
1113
+ },
1114
+ [handleCancel, handleSubmit, isStreaming, messages, mode, setMessages, transport],
1115
+ );
1116
+
1092
1117
  const handleSelectSuggestion = useCallback(
1093
1118
  (text: string) => {
1094
1119
  void handleSubmit({ content: text });
@@ -1534,6 +1559,7 @@ function AgentChatView({
1534
1559
  }
1535
1560
  : undefined
1536
1561
  }
1562
+ onEditUserMessage={hasHostBridge() ? handleEditUserMessage : undefined}
1537
1563
  inputPlaceholder={t("Message the local Agent…")}
1538
1564
  agents={ctx.agents}
1539
1565
  chats={ctx.chats}