@steerable/agent-shell-web 0.12.5 → 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.
@@ -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>
@@ -9,6 +9,7 @@ import { formatElapsedCompact } from './elapsed';
9
9
  import {
10
10
  countProcessReasoning,
11
11
  countProcessTools,
12
+ type ProcessTimelineBlock,
12
13
  type TurnBlock,
13
14
  } from './turn-timeline';
14
15
 
@@ -71,15 +72,16 @@ function formatElapsedPart(
71
72
 
72
73
  /** Work disclosure: live is only 「工作中」; finished is a counts + duration summary. */
73
74
  export function processStatusLabel(input: {
74
- process: TurnBlock[];
75
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>;
75
76
  isStreaming: boolean;
76
77
  elapsedMs?: number;
78
+ hideThinking?: boolean;
77
79
  }): string {
78
- const { process, isStreaming, elapsedMs } = input;
80
+ const { process, isStreaming, elapsedMs, hideThinking } = input;
79
81
  if (isStreaming) return t('Working');
80
82
 
81
83
  const parts: string[] = [];
82
- const thinks = countProcessReasoning(process);
84
+ const thinks = hideThinking ? 0 : countProcessReasoning(process);
83
85
  const tools = countProcessTools(process);
84
86
  const elapsed = formatElapsedPart(false, elapsedMs);
85
87
  if (elapsed) parts.push(t('Worked {elapsed}', { elapsed }));
@@ -10,7 +10,7 @@
10
10
 
11
11
  import type { ExecutedAction } from './ExecutedActionsCard';
12
12
 
13
- export type TurnBlock =
13
+ export type ProcessTimelineBlock<TTool = unknown> =
14
14
  | {
15
15
  type: 'reasoning';
16
16
  content: string;
@@ -19,7 +19,9 @@ export type TurnBlock =
19
19
  durationMs?: number;
20
20
  }
21
21
  | { type: 'text'; content: string; sealed?: boolean }
22
- | { type: 'tools'; actions: ExecutedAction[] };
22
+ | { type: 'tools'; actions: TTool[] };
23
+
24
+ export type TurnBlock = ProcessTimelineBlock<ExecutedAction>;
23
25
 
24
26
  /**
25
27
  * 内容指纹:只要屏上会多出/变化一行,它就变。过程面板用它决定「要不要把
@@ -204,26 +206,56 @@ export function parseTurnBlocks(raw: unknown): TurnBlock[] | null {
204
206
  * While streaming, every text block stays in the process as a post-think
205
207
  * response so the next reasoning burst cannot restyle it as thinking.
206
208
  */
207
- export function splitTurnProcess(
208
- blocks: TurnBlock[],
209
+ export function splitTurnProcess<TTool = ExecutedAction>(
210
+ blocks: ReadonlyArray<ProcessTimelineBlock<TTool>>,
209
211
  options?: { finalize?: boolean },
210
212
  ): {
211
- process: TurnBlock[];
212
- answer: Extract<TurnBlock, { type: 'text' }>[];
213
+ process: ProcessTimelineBlock<TTool>[];
214
+ answer: Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>[];
213
215
  } {
214
216
  const finalize = options?.finalize ?? true;
215
217
  if (!finalize) {
216
- return { process: blocks, answer: [] };
218
+ return { process: [...blocks], answer: [] };
217
219
  }
218
220
  let split = blocks.length;
219
221
  while (split > 0 && blocks[split - 1].type === 'text') split -= 1;
220
222
  return {
221
223
  process: blocks.slice(0, split),
222
- answer: blocks.slice(split) as Extract<TurnBlock, { type: 'text' }>[],
224
+ answer: blocks.slice(split) as Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>[],
223
225
  };
224
226
  }
225
227
 
226
- export function countProcessTools(process: TurnBlock[]): number {
228
+ /**
229
+ * Filter thinking blocks and merge consecutive tool groups that become adjacent
230
+ * once reasoning is hidden (Codex-style compact process presentation).
231
+ */
232
+ export function compactProcessBlocks<TTool>(
233
+ process: ReadonlyArray<ProcessTimelineBlock<TTool>>,
234
+ options: { hideThinking: boolean; mergeAdjacentTools?: boolean },
235
+ ): ProcessTimelineBlock<TTool>[] {
236
+ if (!options.hideThinking) return [...process];
237
+ const mergeAdjacentTools = options.mergeAdjacentTools ?? true;
238
+ const out: ProcessTimelineBlock<TTool>[] = [];
239
+ for (const block of process) {
240
+ if (block.type === 'reasoning') continue;
241
+ if (block.type === 'tools' && mergeAdjacentTools) {
242
+ const prev = out[out.length - 1];
243
+ if (prev && prev.type === 'tools') {
244
+ out[out.length - 1] = {
245
+ type: 'tools',
246
+ actions: [...prev.actions, ...block.actions],
247
+ };
248
+ continue;
249
+ }
250
+ }
251
+ out.push(block);
252
+ }
253
+ return out;
254
+ }
255
+
256
+ export function countProcessTools(
257
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
258
+ ): number {
227
259
  let n = 0;
228
260
  for (const block of process) {
229
261
  if (block.type === 'tools') n += block.actions.length;
@@ -231,7 +263,9 @@ export function countProcessTools(process: TurnBlock[]): number {
231
263
  return n;
232
264
  }
233
265
 
234
- export function countProcessReasoning(process: TurnBlock[]): number {
266
+ export function countProcessReasoning(
267
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
268
+ ): number {
235
269
  let n = 0;
236
270
  for (const block of process) {
237
271
  if (block.type === 'reasoning' && block.content.trim().length > 0) n += 1;
@@ -239,6 +273,8 @@ export function countProcessReasoning(process: TurnBlock[]): number {
239
273
  return n;
240
274
  }
241
275
 
242
- export function processHasReasoning(process: TurnBlock[]): boolean {
276
+ export function processHasReasoning(
277
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
278
+ ): boolean {
243
279
  return process.some((block) => block.type === 'reasoning' && block.content.trim().length > 0);
244
280
  }
@@ -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}
package/vite.base.js CHANGED
@@ -72,6 +72,9 @@ export function createProductViteConfig(options) {
72
72
  // shell 渲染层源码(产品入口与包 web 模块都以 `@/` 引用它)。
73
73
  '@': webSrcDir,
74
74
  },
75
+ // 跨仓 `shell:link` 时产品与 shell 各自有独立 node_modules;必须去重
76
+ // React 与 Router,否则 AppShell 的 <Outlet /> 会读到另一份 Context 而白屏。
77
+ dedupe: ['react', 'react-dom', 'react-router-dom'],
75
78
  },
76
79
  // 静态资产(favicon 等中性默认)随 shell web 包分发;产品可在自己的
77
80
  // web root 放 public/ 覆盖(vite 不合并双 publicDir——需要产品级资产