@steerable/agent-shell-web 0.12.4 → 0.12.6

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.
@@ -4,17 +4,22 @@ import type {
4
4
  LocalBackendStreamEvent,
5
5
  } from './host-bridge';
6
6
  import type {
7
+ CatalogProviderDescriptor,
7
8
  ChatAgentWriteInput,
9
+ ChatLiveStream,
10
+ GatewayModelEntry,
8
11
  LocalChat,
9
12
  LocalChatAgent,
10
13
  LocalChatMessage,
14
+ LocalProject,
11
15
  LlmSettings,
12
16
  } from './local-api';
13
17
  import { pickDefaultAgentId } from '@/brand';
14
18
  import { isDemoMode } from './demo-flag';
19
+ import { buildPlaybookScript, DEMO_SAMPLE_FILES } from './demo-playbook';
15
20
  import browserDevData from '../fixtures/browser-dev-data.json';
16
21
 
17
- type MutableChat = LocalChat;
22
+ type MutableChat = LocalChat & { forkedFrom?: { chatId: string; title: string } | null };
18
23
  type MutableMessage = LocalChatMessage;
19
24
 
20
25
  interface BrowserDevFixture {
@@ -22,19 +27,42 @@ interface BrowserDevFixture {
22
27
  exportedAt?: string | null;
23
28
  source?: string | null;
24
29
  agents?: LocalChatAgent[];
30
+ projects?: LocalProject[];
25
31
  chats?: MutableChat[];
26
32
  messagesByChatId?: Record<string, MutableMessage[]>;
27
33
  llmSettings?: LlmSettings | null;
28
34
  skills?: Array<{ name: string; description: string; builtin?: boolean }>;
29
35
  }
30
36
 
37
+ interface ActiveStreamRecord {
38
+ streamId: string;
39
+ chatId: string;
40
+ timers: number[];
41
+ onEvent: (payload: LocalBackendStreamEvent) => void;
42
+ steerNote: string | null;
43
+ snapshot: ChatLiveStream;
44
+ }
45
+
31
46
  interface BrowserMockState {
32
47
  agents: LocalChatAgent[];
48
+ projects: LocalProject[];
33
49
  chats: MutableChat[];
34
50
  messagesByChatId: Record<string, MutableMessage[]>;
35
51
  llmSettings: LlmSettings;
52
+ webSearchSettings: { provider: 'ddg' | 'tavily'; apiKey: string };
53
+ telemetrySettings: { endpoint: string; privacyMode: 'metadata' | 'full'; serviceName: string };
54
+ insightsSettings: {
55
+ installId: string;
56
+ shareBehavior: boolean;
57
+ shareConversation: boolean;
58
+ shareProfile: boolean;
59
+ promptedAt: string;
60
+ profile: { displayName: string; email: string; company: string; note: string };
61
+ stats: { events: number; turns: number; profile: number; pending: number };
62
+ };
63
+ mcpServers: Array<Record<string, unknown>>;
36
64
  skills: Array<{ name: string; description: string; builtin?: boolean }>;
37
- activeStreams: Map<string, number[]>;
65
+ activeStreams: Map<string, ActiveStreamRecord>;
38
66
  source: 'fixture' | 'fallback';
39
67
  fixtureMeta: Pick<BrowserDevFixture, 'exportedAt' | 'source'> | null;
40
68
  }
@@ -42,204 +70,124 @@ interface BrowserMockState {
42
70
  const suggestedReplyListeners = new Set<
43
71
  (payload: { chatId: string; messageId: string; suggestions: string[] }) => void
44
72
  >();
73
+ const chatTitleListeners = new Set<(payload: { chatId: string; title: string }) => void>();
74
+ const chatActivityListeners = new Set<(payload: { chatId: string; updatedAt: string }) => void>();
75
+ const chatCreatedListeners = new Set<
76
+ (payload: { chatId: string; agentId?: string | null }) => void
77
+ >();
45
78
 
46
- const USER_ID = 'browser-preview-user';
47
- const now = new Date();
48
-
49
- function iso(minutesAgo: number): string {
50
- return new Date(now.getTime() - minutesAgo * 60_000).toISOString();
51
- }
52
-
53
- function createChatRecord(input: {
54
- id: string;
55
- title: string;
56
- agentId: string | null;
57
- minutesAgo: number;
58
- isPinned?: boolean;
59
- }): MutableChat {
60
- return {
61
- id: input.id,
62
- projectId: null,
63
- userId: USER_ID,
64
- title: input.title,
65
- agentId: input.agentId,
66
- createdAt: iso(input.minutesAgo + 10),
67
- updatedAt: iso(input.minutesAgo),
68
- isPinned: Boolean(input.isPinned),
69
- systemPrompt: null,
70
- pinnedRefs: null,
71
- };
72
- }
73
-
74
- function createMessage(input: {
75
- id: string;
76
- chatId: string;
77
- role: MutableMessage['role'];
78
- content: string;
79
- minutesAgo: number;
80
- messageMetadata?: string | null;
81
- }): MutableMessage {
82
- return {
83
- id: input.id,
84
- chatId: input.chatId,
85
- role: input.role,
86
- content: input.content,
87
- createdAt: iso(input.minutesAgo),
88
- messageMetadata: input.messageMetadata ?? null,
89
- };
90
- }
79
+ const DEMO_MODELS: GatewayModelEntry[] = [
80
+ {
81
+ id: 'glm-5.3-flash',
82
+ name: 'GLM-5.3-Flash',
83
+ window: 128_000,
84
+ modalities: ['text'],
85
+ reasoningLevels: ['low', 'medium', 'high', 'max'],
86
+ pricing: { promptPerMtok: 0.14, completionPerMtok: 0.56 },
87
+ joinedFrom: 'demo-catalog',
88
+ capabilities: 'known',
89
+ },
90
+ {
91
+ id: 'deepseek-v3.1-0731',
92
+ name: 'DeepSeek-V3.1-0731',
93
+ window: 128_000,
94
+ modalities: ['text'],
95
+ reasoningLevels: ['low', 'medium', 'high'],
96
+ pricing: { promptPerMtok: 0.27, completionPerMtok: 1.1 },
97
+ joinedFrom: 'demo-catalog',
98
+ capabilities: 'known',
99
+ },
100
+ {
101
+ id: 'qwen3-coder-plus',
102
+ name: 'Qwen3-Coder-Plus',
103
+ window: 128_000,
104
+ modalities: ['text'],
105
+ reasoningLevels: ['low', 'medium'],
106
+ pricing: { promptPerMtok: 0.3, completionPerMtok: 1.5 },
107
+ joinedFrom: 'demo-catalog',
108
+ capabilities: 'known',
109
+ },
110
+ {
111
+ id: 'claude-sonnet-4-6',
112
+ name: 'Claude Sonnet 4.6',
113
+ window: 200_000,
114
+ modalities: ['text', 'image'],
115
+ reasoningLevels: ['low', 'medium', 'high'],
116
+ pricing: { promptPerMtok: 3, completionPerMtok: 15 },
117
+ joinedFrom: 'demo-catalog',
118
+ capabilities: 'known',
119
+ },
120
+ ];
91
121
 
92
- function createInitialState(): BrowserMockState {
93
- const fixtureState = createStateFromFixture(browserDevData as BrowserDevFixture);
94
- if (fixtureState) return fixtureState;
122
+ const DEMO_CATALOG_PROVIDERS: CatalogProviderDescriptor[] = [
123
+ {
124
+ id: 'openrouter',
125
+ apiBaseUrl: 'https://openrouter.ai/api/v1',
126
+ envVars: ['OPENROUTER_API_KEY'],
127
+ wireKind: 'openai-compat',
128
+ models: ['glm-5.3-flash', 'deepseek-v3.1-0731', 'qwen3-coder-plus'],
129
+ },
130
+ {
131
+ id: 'deepseek',
132
+ apiBaseUrl: 'https://api.deepseek.com/v1',
133
+ envVars: ['DEEPSEEK_API_KEY'],
134
+ wireKind: 'openai-compat',
135
+ models: ['deepseek-chat', 'deepseek-reasoner'],
136
+ },
137
+ {
138
+ id: 'anthropic',
139
+ apiBaseUrl: 'https://api.anthropic.com',
140
+ envVars: ['ANTHROPIC_API_KEY'],
141
+ wireKind: 'anthropic',
142
+ models: ['claude-sonnet-4-6'],
143
+ },
144
+ {
145
+ id: 'ollama',
146
+ apiBaseUrl: 'http://127.0.0.1:11434',
147
+ envVars: [],
148
+ wireKind: 'ollama',
149
+ models: ['qwen3:8b', 'glm4:9b'],
150
+ },
151
+ ];
95
152
 
96
- const agents: LocalChatAgent[] = [
97
- {
98
- id: 'coach',
99
- slug: 'coach',
100
- name: 'Action coach',
101
- icon: null,
102
- color: '#2563eb',
103
- description: 'Breaks a goal into an executable plan. Useful for debugging the standard chat path.',
104
- rolePrompt: 'You are an action coach.',
105
- isBuiltin: true,
106
- sortOrder: 1,
107
- },
108
- {
109
- id: 'tool-demo',
110
- slug: 'tool-demo',
111
- name: 'Tool demo',
112
- icon: null,
113
- color: '#7c3aed',
114
- description: 'Simulates local tool calls and execution summaries. Useful for debugging tool cards.',
115
- rolePrompt: 'You are the tool-demo agent.',
116
- isBuiltin: true,
117
- sortOrder: 2,
118
- },
119
- {
120
- id: 'writer',
121
- slug: 'writer',
122
- name: 'Writing advisor',
123
- icon: null,
124
- color: '#16a34a',
125
- description: 'Longer text replies, for debugging markdown and scrolling.',
126
- rolePrompt: 'You are a writing advisor.',
127
- isBuiltin: true,
128
- sortOrder: 3,
129
- },
130
- ];
131
-
132
- const chats = [
133
- createChatRecord({
134
- id: 'chat-browser-demo',
135
- title: 'Browser UI debug sample',
136
- agentId: 'coach',
137
- minutesAgo: 8,
138
- isPinned: true,
139
- }),
140
- createChatRecord({
141
- id: 'chat-tool-demo',
142
- title: 'Tool-call card preview',
143
- agentId: 'tool-demo',
144
- minutesAgo: 64,
145
- }),
146
- ];
153
+ function createDefaultState(): BrowserMockState {
154
+ const fixture = browserDevData as BrowserDevFixture;
155
+ const agents = Array.isArray(fixture.agents) ? structuredClone(fixture.agents) : [];
156
+ const projects = Array.isArray(fixture.projects) ? structuredClone(fixture.projects) : [];
157
+ const chats = Array.isArray(fixture.chats) ? structuredClone(fixture.chats) : [];
158
+ const messagesByChatId = fixture.messagesByChatId ? structuredClone(fixture.messagesByChatId) : {};
147
159
 
148
160
  return {
149
161
  agents,
150
- chats,
151
- messagesByChatId: {
152
- 'chat-browser-demo': [
153
- createMessage({
154
- id: 'msg-demo-assistant-1',
155
- chatId: 'chat-browser-demo',
156
- role: 'assistant',
157
- content:
158
- 'You can debug the chat UI in a normal browser here. This reply comes from the dev mock bridge and does not call a live model.',
159
- minutesAgo: 7,
160
- }),
161
- createMessage({
162
- id: 'msg-demo-user-1',
163
- chatId: 'chat-browser-demo',
164
- role: 'user',
165
- content: 'I want to debug the chat UI in the browser.',
166
- minutesAgo: 8,
167
- }),
168
- ],
169
- 'chat-tool-demo': [
170
- createMessage({
171
- id: 'msg-tool-assistant-1',
172
- chatId: 'chat-tool-demo',
173
- role: 'assistant',
174
- content: 'I simulated a local command and put the result in a tool card.',
175
- minutesAgo: 63,
176
- messageMetadata: JSON.stringify({
177
- executedActions: [
178
- {
179
- tool: 'local_exec',
180
- arguments: { command: 'tool_demo list --limit 5' },
181
- result: { success: true, output: 'Found 5 mock records.' },
182
- },
183
- ],
184
- }),
185
- }),
186
- createMessage({
187
- id: 'msg-tool-user-1',
188
- chatId: 'chat-tool-demo',
189
- role: 'user',
190
- content: 'Show me the recent tool-call records.',
191
- minutesAgo: 64,
192
- }),
193
- ],
194
- },
195
- llmSettings: {
196
- provider: 'ollama',
197
- model: 'browser-preview-model',
198
- baseUrl: 'http://127.0.0.1:11434',
199
- apiKey: '',
200
- temperature: 0.3,
201
- maxTotalTokens: 60_000,
202
- },
203
- skills: [
204
- { name: 'tool-demo', description: 'Simulates query and replay tools.', builtin: true },
205
- { name: 'local-exec', description: 'Simulates local command execution.', builtin: true },
206
- { name: 'anti-deferred', description: 'Simulates the anti-deferral execution policy.', builtin: true },
207
- ],
208
- activeStreams: new Map(),
209
- source: 'fallback',
210
- fixtureMeta: null,
211
- };
212
- }
213
-
214
- const state = createInitialState();
215
-
216
- function createStateFromFixture(fixture: BrowserDevFixture): BrowserMockState | null {
217
- const agents = Array.isArray(fixture.agents) ? fixture.agents : [];
218
- const chats = Array.isArray(fixture.chats) ? fixture.chats : [];
219
- if (agents.length === 0 || chats.length === 0) return null;
220
-
221
- const messagesByChatId = fixture.messagesByChatId ?? {};
222
- return {
223
- agents,
162
+ projects,
224
163
  chats,
225
164
  messagesByChatId,
226
- llmSettings: fixture.llmSettings ?? {
227
- provider: 'ollama',
228
- model: 'browser-preview-model',
229
- baseUrl: 'http://127.0.0.1:11434',
230
- apiKey: '',
231
- temperature: 0.3,
232
- maxTotalTokens: 60_000,
165
+ llmSettings: fixture.llmSettings
166
+ ? { ...fixture.llmSettings }
167
+ : {
168
+ provider: 'openai-compat',
169
+ vendorId: 'openrouter',
170
+ model: 'glm-5.3-flash',
171
+ baseUrl: 'https://openrouter.ai/api/v1',
172
+ apiKey: '',
173
+ temperature: 0.3,
174
+ maxTotalTokens: 60_000,
175
+ },
176
+ webSearchSettings: { provider: 'ddg', apiKey: '' },
177
+ telemetrySettings: { endpoint: '', privacyMode: 'metadata', serviceName: 'steerable-demo' },
178
+ insightsSettings: {
179
+ installId: 'demo-browser-install',
180
+ shareBehavior: false,
181
+ shareConversation: false,
182
+ shareProfile: false,
183
+ promptedAt: '2026-11-17T00:00:00.000Z',
184
+ profile: { displayName: '', email: '', company: '', note: '' },
185
+ stats: { events: 0, turns: 4, profile: 0, pending: 0 },
233
186
  },
234
- skills:
235
- Array.isArray(fixture.skills) && fixture.skills.length > 0
236
- ? fixture.skills
237
- : [
238
- { name: 'tool-demo', description: 'Query and replay tools.', builtin: true },
239
- { name: 'local-exec', description: 'Local command execution.', builtin: true },
240
- ],
187
+ mcpServers: [],
188
+ skills: Array.isArray(fixture.skills) ? structuredClone(fixture.skills) : [],
241
189
  activeStreams: new Map(),
242
- source: 'fixture',
190
+ source: chats.length > 0 ? 'fixture' : 'fallback',
243
191
  fixtureMeta: {
244
192
  exportedAt: fixture.exportedAt ?? null,
245
193
  source: fixture.source ?? null,
@@ -247,6 +195,22 @@ function createStateFromFixture(fixture: BrowserDevFixture): BrowserMockState |
247
195
  };
248
196
  }
249
197
 
198
+ let state = createDefaultState();
199
+
200
+ export function resetBrowserDevMockForTests(): void {
201
+ for (const active of state.activeStreams.values()) {
202
+ active.timers.forEach((timer) => window.clearTimeout(timer));
203
+ }
204
+ state = createDefaultState();
205
+ }
206
+
207
+ function encodeUtf8Base64(text: string): string {
208
+ const bytes = new TextEncoder().encode(text);
209
+ let binary = '';
210
+ for (const b of bytes) binary += String.fromCharCode(b);
211
+ return btoa(binary);
212
+ }
213
+
250
214
  function paginateChats(page: number, limit: number) {
251
215
  const sorted = [...state.chats].sort((a, b) => {
252
216
  if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
@@ -276,17 +240,29 @@ function stripQuery(path: string): string {
276
240
  return queryStart >= 0 ? path.slice(0, queryStart) : path;
277
241
  }
278
242
 
279
- function getChatIdFromPath(path: string, suffix = ''): string | null {
280
- const cleanPath = stripQuery(path);
281
- const match = cleanPath.match(/^\/api\/v2\/chats\/([^/]+)(?:\/.*)?$/);
243
+ function matchChatSubroute(cleanPath: string): { chatId: string; rest: string } | null {
244
+ const match = cleanPath.match(/^\/api\/v2\/chats\/([^/]+)(\/.*)?$/);
282
245
  if (!match) return null;
283
- if (suffix && !cleanPath.endsWith(suffix)) return null;
284
- return decodeURIComponent(match[1]);
246
+ const segment = decodeURIComponent(match[1]);
247
+ if (segment === 'new' || segment === 'prune-empty') return null;
248
+ return { chatId: segment, rest: match[2] ?? '' };
285
249
  }
286
250
 
287
251
  function updateChatTimestamp(chatId: string) {
288
252
  const chat = state.chats.find((item) => item.id === chatId);
289
- if (chat) chat.updatedAt = new Date().toISOString();
253
+ if (!chat) return;
254
+ const nowIso = new Date().toISOString();
255
+ chat.updatedAt = nowIso;
256
+ for (const listener of chatActivityListeners) {
257
+ listener({ chatId, updatedAt: nowIso });
258
+ }
259
+ }
260
+
261
+ function findActiveStreamByChat(chatId: string): ActiveStreamRecord | undefined {
262
+ for (const record of state.activeStreams.values()) {
263
+ if (record.chatId === chatId) return record;
264
+ }
265
+ return undefined;
290
266
  }
291
267
 
292
268
  async function request<T>(input: LocalBackendRequestInput): Promise<T> {
@@ -294,6 +270,7 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
294
270
  const path = input.path;
295
271
  const cleanPath = stripQuery(path);
296
272
 
273
+ // ---- Chats collection ----
297
274
  if (method === 'GET' && cleanPath === '/api/v2/chats') {
298
275
  const query = parseQuery(path);
299
276
  const page = Number(query.get('page') ?? '1');
@@ -301,6 +278,289 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
301
278
  return paginateChats(page, limit) as T;
302
279
  }
303
280
 
281
+ if (method === 'POST' && cleanPath === '/api/v2/chats/new') {
282
+ const body = (input.body ?? {}) as { agentId?: string; projectId?: string | null };
283
+ const agentId = body.agentId || pickDefaultAgentId(state.agents) || null;
284
+ const chatId = `chat-demo-${Date.now()}`;
285
+ const nowIso = new Date().toISOString();
286
+ const chat: MutableChat = {
287
+ id: chatId,
288
+ projectId: body.projectId ?? null,
289
+ userId: 'demo',
290
+ title: 'New chat',
291
+ agentId,
292
+ createdAt: nowIso,
293
+ updatedAt: nowIso,
294
+ isPinned: false,
295
+ systemPrompt: null,
296
+ pinnedRefs: null,
297
+ };
298
+ state.chats.unshift(chat);
299
+ state.messagesByChatId[chatId] = [];
300
+ return {
301
+ success: true,
302
+ chatId,
303
+ projectId: chat.projectId,
304
+ isTemporary: false,
305
+ } as T;
306
+ }
307
+
308
+ if (method === 'POST' && cleanPath === '/api/v2/chats/prune-empty') {
309
+ const body = input.body as { exceptChatId?: string | null } | undefined;
310
+ const except = body?.exceptChatId ?? null;
311
+ const deletedChatIds: string[] = [];
312
+ for (const chat of [...state.chats]) {
313
+ if (except && chat.id === except) continue;
314
+ const messages = state.messagesByChatId[chat.id] ?? [];
315
+ if (messages.length === 0) deletedChatIds.push(chat.id);
316
+ }
317
+ state.chats = state.chats.filter((chat) => !deletedChatIds.includes(chat.id));
318
+ for (const id of deletedChatIds) delete state.messagesByChatId[id];
319
+ return { deletedChatIds } as T;
320
+ }
321
+
322
+ // ---- Per-chat routes ----
323
+ const chatRoute = matchChatSubroute(cleanPath);
324
+ if (chatRoute) {
325
+ const { chatId, rest } = chatRoute;
326
+
327
+ if (method === 'GET' && rest === '') {
328
+ const chat = state.chats.find((c) => c.id === chatId);
329
+ return {
330
+ id: chatId,
331
+ title: chat?.title ?? 'Demo chat',
332
+ forkedFrom: chat?.forkedFrom ?? null,
333
+ } as T;
334
+ }
335
+
336
+ if (method === 'DELETE' && rest === '') {
337
+ const onlyIfEmpty = parseQuery(path).get('onlyIfEmpty') === '1';
338
+ if (onlyIfEmpty) {
339
+ const messages = state.messagesByChatId[chatId] ?? [];
340
+ const exists = state.chats.some((chat) => chat.id === chatId);
341
+ if (!exists || messages.length > 0) {
342
+ return { success: true, deleted: false, chatId } as T;
343
+ }
344
+ }
345
+ state.chats = state.chats.filter((chat) => chat.id !== chatId);
346
+ delete state.messagesByChatId[chatId];
347
+ return { success: true, deleted: true, message: 'deleted in demo', chatId } as T;
348
+ }
349
+
350
+ if (method === 'GET' && rest === '/messages') {
351
+ const messages = state.messagesByChatId[chatId] ?? [];
352
+ return {
353
+ messages: [...messages].sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
354
+ } as T;
355
+ }
356
+
357
+ if (method === 'GET' && rest === '/live-stream') {
358
+ const active = findActiveStreamByChat(chatId);
359
+ return (active ? active.snapshot : { active: false }) as T;
360
+ }
361
+
362
+ if (method === 'POST' && rest === '/cancel') {
363
+ const active = findActiveStreamByChat(chatId);
364
+ if (active) {
365
+ cancelStream(active.streamId);
366
+ return { success: true } as T;
367
+ }
368
+ return { success: false, reason: 'not_running' } as T;
369
+ }
370
+
371
+ if (method === 'PUT' && rest === '/pin') {
372
+ const body = (input.body ?? {}) as { isPinned?: boolean };
373
+ const chat = state.chats.find((c) => c.id === chatId);
374
+ if (chat) chat.isPinned = Boolean(body.isPinned);
375
+ return {
376
+ success: true,
377
+ chatId,
378
+ isPinned: Boolean(chat?.isPinned),
379
+ message: 'updated',
380
+ } as T;
381
+ }
382
+
383
+ if (method === 'PATCH' && rest === '/settings') {
384
+ const body = (input.body ?? {}) as { title?: string; projectId?: string | null };
385
+ const chat = state.chats.find((c) => c.id === chatId);
386
+ if (chat) {
387
+ if (typeof body.title === 'string' && body.title.trim()) {
388
+ chat.title = body.title.trim();
389
+ }
390
+ if ('projectId' in body) {
391
+ chat.projectId = body.projectId ?? null;
392
+ }
393
+ updateChatTimestamp(chatId);
394
+ }
395
+ return {
396
+ id: chatId,
397
+ title: chat?.title ?? 'Demo chat',
398
+ projectId: chat?.projectId ?? null,
399
+ } as T;
400
+ }
401
+
402
+ if (method === 'POST' && rest === '/fork') {
403
+ const orig = state.chats.find((c) => c.id === chatId);
404
+ const newChatId = `chat-fork-${Date.now()}`;
405
+ const nowIso = new Date().toISOString();
406
+ const cloned: MutableChat = {
407
+ id: newChatId,
408
+ projectId: orig?.projectId ?? null,
409
+ userId: 'demo',
410
+ title: orig ? `${orig.title} (fork)` : 'Forked chat',
411
+ agentId: orig?.agentId ?? pickDefaultAgentId(state.agents) ?? null,
412
+ createdAt: nowIso,
413
+ updatedAt: nowIso,
414
+ isPinned: false,
415
+ systemPrompt: orig?.systemPrompt ?? null,
416
+ pinnedRefs: orig?.pinnedRefs ?? null,
417
+ forkedFrom: orig ? { chatId: orig.id, title: orig.title } : null,
418
+ };
419
+ state.chats.unshift(cloned);
420
+ state.messagesByChatId[newChatId] = (state.messagesByChatId[chatId] ?? []).map((m) => ({
421
+ ...m,
422
+ id: `${m.id}-fork-${Date.now()}`,
423
+ chatId: newChatId,
424
+ }));
425
+ return { chatId: newChatId } as T;
426
+ }
427
+
428
+ if (method === 'GET' && rest === '/branches') {
429
+ return { activeRecordId: `rec-${chatId}`, lineage: [], children: [] } as T;
430
+ }
431
+
432
+ if (method === 'GET' && rest === '/branches/tree') {
433
+ return {
434
+ activeRecordId: `rec-${chatId}`,
435
+ tree: null,
436
+ nodeCount: 1,
437
+ truncated: false,
438
+ } as T;
439
+ }
440
+
441
+ if (method === 'POST' && rest === '/branches/activate') {
442
+ const body = (input.body ?? {}) as { recordId?: string };
443
+ return {
444
+ activeRecordId: body.recordId ?? `rec-${chatId}`,
445
+ messageCount: (state.messagesByChatId[chatId] ?? []).length,
446
+ } as T;
447
+ }
448
+
449
+ if (method === 'GET' && rest === '/goal') {
450
+ return { goal: null } as T;
451
+ }
452
+
453
+ if (method === 'POST' && rest === '/goal') {
454
+ return { goal: null } as T;
455
+ }
456
+
457
+ if (method === 'GET' && rest === '/loops') {
458
+ return { loops: [] } as T;
459
+ }
460
+
461
+ if (method === 'DELETE' && rest.startsWith('/loops/')) {
462
+ return { success: true } as T;
463
+ }
464
+
465
+ if (method === 'GET' && rest === '/tasks') {
466
+ return { tasks: [] } as T;
467
+ }
468
+
469
+ if (method === 'GET' && rest === '/project-context') {
470
+ const chat = state.chats.find((c) => c.id === chatId);
471
+ const project = chat?.projectId
472
+ ? state.projects.find((p) => p.id === chat.projectId) ?? null
473
+ : null;
474
+ return {
475
+ project: project
476
+ ? {
477
+ id: project.id,
478
+ name: project.name,
479
+ folderPath: project.folderPath,
480
+ trusted: Boolean(project.trusted),
481
+ }
482
+ : null,
483
+ ruleFileCount: project ? 1 : 0,
484
+ rulesActive: Boolean(project?.trusted),
485
+ } as T;
486
+ }
487
+ }
488
+
489
+ // ---- Projects ----
490
+ if (method === 'GET' && cleanPath === '/api/v2/projects') {
491
+ const projects = [...state.projects].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
492
+ return { projects } as T;
493
+ }
494
+
495
+ if (method === 'POST' && cleanPath === '/api/v2/projects') {
496
+ const body = (input.body ?? {}) as {
497
+ name?: string;
498
+ folderPath?: string;
499
+ sourceFolders?: string[];
500
+ };
501
+ const nowIso = new Date().toISOString();
502
+ const project: LocalProject = {
503
+ id: `proj-${Date.now()}`,
504
+ name: (body.name || 'demo-project').trim(),
505
+ folderPath: body.folderPath || '/workspace/demo-project',
506
+ sourceFolders: body.sourceFolders ?? [],
507
+ trusted: true,
508
+ sortOrder: state.projects.length,
509
+ createdAt: nowIso,
510
+ updatedAt: nowIso,
511
+ };
512
+ state.projects.push(project);
513
+ return { success: true, project } as T;
514
+ }
515
+
516
+ if (method === 'PUT' && cleanPath === '/api/v2/projects/order') {
517
+ const body = (input.body ?? {}) as { orderedIds?: string[] };
518
+ const order = body.orderedIds ?? [];
519
+ state.projects.forEach((p) => {
520
+ const idx = order.indexOf(p.id);
521
+ p.sortOrder = idx >= 0 ? idx : order.length + (p.sortOrder ?? 0);
522
+ });
523
+ return { success: true, projects: [...state.projects] } as T;
524
+ }
525
+
526
+ const projectTrustMatch = cleanPath.match(/^\/api\/v2\/projects\/([^/]+)\/trust$/);
527
+ if (method === 'PUT' && projectTrustMatch) {
528
+ const projectId = decodeURIComponent(projectTrustMatch[1]);
529
+ const body = (input.body ?? {}) as { trusted?: boolean };
530
+ const project = state.projects.find((p) => p.id === projectId);
531
+ if (project) {
532
+ project.trusted = Boolean(body.trusted);
533
+ project.updatedAt = new Date().toISOString();
534
+ }
535
+ return { success: true, project } as T;
536
+ }
537
+
538
+ const projectMatch = cleanPath.match(/^\/api\/v2\/projects\/([^/]+)$/);
539
+ if (projectMatch) {
540
+ const projectId = decodeURIComponent(projectMatch[1]);
541
+ const project = state.projects.find((p) => p.id === projectId);
542
+ if (method === 'PUT' && project) {
543
+ const body = (input.body ?? {}) as Partial<LocalProject>;
544
+ if (typeof body.name === 'string') project.name = body.name;
545
+ if (typeof body.folderPath === 'string') project.folderPath = body.folderPath;
546
+ if (Array.isArray(body.sourceFolders)) project.sourceFolders = body.sourceFolders;
547
+ project.updatedAt = new Date().toISOString();
548
+ return { success: true, project } as T;
549
+ }
550
+ if (method === 'DELETE') {
551
+ state.projects = state.projects.filter((p) => p.id !== projectId);
552
+ let detachedChats = 0;
553
+ for (const c of state.chats) {
554
+ if (c.projectId === projectId) {
555
+ c.projectId = null;
556
+ detachedChats += 1;
557
+ }
558
+ }
559
+ return { success: true, detachedChats } as T;
560
+ }
561
+ }
562
+
563
+ // ---- Chat agents / skills / tools ----
304
564
  if (method === 'GET' && cleanPath === '/api/v2/chat-agents') {
305
565
  const includeArchived = parseQuery(path).get('include_archived') === 'true';
306
566
  const agents = includeArchived
@@ -314,7 +574,7 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
314
574
  const id =
315
575
  typeof crypto !== 'undefined' && 'randomUUID' in crypto
316
576
  ? crypto.randomUUID()
317
- : `agent-browser-${Date.now()}`;
577
+ : `agent-demo-${Date.now()}`;
318
578
  const agent: LocalChatAgent = {
319
579
  id,
320
580
  slug: null,
@@ -351,13 +611,10 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
351
611
  ...current,
352
612
  name: typeof body.name === 'string' ? body.name : current.name,
353
613
  color: body.color === undefined ? current.color : body.color,
354
- description:
355
- body.description === undefined ? current.description : body.description,
356
- rolePrompt:
357
- body.rolePrompt === undefined ? current.rolePrompt : body.rolePrompt,
614
+ description: body.description === undefined ? current.description : body.description,
615
+ rolePrompt: body.rolePrompt === undefined ? current.rolePrompt : body.rolePrompt,
358
616
  skillIds: body.skillIds === undefined ? current.skillIds : body.skillIds,
359
- toolPolicy:
360
- body.toolPolicy === undefined ? current.toolPolicy : body.toolPolicy,
617
+ toolPolicy: body.toolPolicy === undefined ? current.toolPolicy : body.toolPolicy,
361
618
  allowExternalSkills:
362
619
  body.allowExternalSkills === undefined
363
620
  ? current.allowExternalSkills
@@ -376,8 +633,6 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
376
633
  }
377
634
 
378
635
  if (method === 'GET' && cleanPath === '/api/v2/chat-agents/skills') {
379
- // fixture 只存 name/description;智能体的技能勾选还要 id 与 layer,
380
- // 这里按真实接口的字段补齐(内置技能视作常驻层)。
381
636
  return {
382
637
  skills: state.skills.map((skill) => ({
383
638
  ...skill,
@@ -392,19 +647,23 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
392
647
  if (method === 'GET' && cleanPath === '/api/v2/chat-agents/tools') {
393
648
  return {
394
649
  tools: [
395
- { name: 'local_exec_shell', description: 'Run a local shell command.', category: 'local' },
396
- { name: 'local_read_file', description: 'Read a local text file.', category: 'local' },
397
- { name: 'local_write_file', description: 'Write a local file.', category: 'local' },
398
- { name: 'web_search', description: 'Search the web.', category: 'local' },
650
+ { name: 'local_exec_shell', description: 'Run a sandboxed shell command.', category: 'local' },
651
+ { name: 'local_read_file', description: 'Read a file from the workspace.', category: 'local' },
652
+ { name: 'local_write_file', description: 'Write or patch a workspace file.', category: 'local' },
653
+ { name: 'web_search', description: 'Search public documentation.', category: 'local' },
399
654
  ],
400
655
  } as T;
401
656
  }
402
657
 
658
+ if (method === 'GET' && cleanPath === '/api/v2/chat-agents/mcp-tools') {
659
+ return { tools: [] } as T;
660
+ }
661
+
403
662
  if (method === 'POST' && cleanPath === '/api/v2/chat-agents/skills/import') {
404
663
  const body = input.body as { path?: string } | undefined;
405
- const name = body?.path?.split(/[\\/]/).filter(Boolean).pop() || 'browser-skill';
664
+ const name = body?.path?.split(/[\\/]/).filter(Boolean).pop() || 'demo-skill';
406
665
  if (!state.skills.some((skill) => skill.name === name)) {
407
- state.skills.push({ name, description: 'Mock skill imported in the browser preview.' });
666
+ state.skills.push({ name, description: 'Skill imported in the interactive browser demo.' });
408
667
  }
409
668
  return { success: true, name } as T;
410
669
  }
@@ -415,6 +674,20 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
415
674
  return { success: true } as T;
416
675
  }
417
676
 
677
+ // ---- Children / background tasks ----
678
+ if (method === 'GET' && cleanPath === '/api/v2/children') {
679
+ return { children: [] } as T;
680
+ }
681
+
682
+ if (method === 'GET' && cleanPath === '/api/v2/child-process') {
683
+ return { recordId: parseQuery(path).get('recordId') ?? '', timeline: [] } as T;
684
+ }
685
+
686
+ if (method === 'GET' && /^\/api\/v2\/tasks\/[^/]+\/process$/.test(cleanPath)) {
687
+ return { task: null, timeline: [], live: false, stale: false } as T;
688
+ }
689
+
690
+ // ---- LLM settings / catalog / models / diagnostics ----
418
691
  if (method === 'GET' && cleanPath === '/api/v2/local-settings/llm') {
419
692
  return state.llmSettings as T;
420
693
  }
@@ -424,64 +697,74 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
424
697
  return state.llmSettings as T;
425
698
  }
426
699
 
427
- if (method === 'POST' && cleanPath === '/api/v2/chats/prune-empty') {
428
- const body = input.body as { exceptChatId?: string | null } | undefined;
429
- const except = body?.exceptChatId ?? null;
430
- const deletedChatIds: string[] = [];
431
- for (const chat of [...state.chats]) {
432
- if (except && chat.id === except) continue;
433
- const messages = state.messagesByChatId[chat.id] ?? [];
434
- if (messages.length === 0) deletedChatIds.push(chat.id);
435
- }
436
- state.chats = state.chats.filter((chat) => !deletedChatIds.includes(chat.id));
437
- for (const id of deletedChatIds) delete state.messagesByChatId[id];
438
- return { deletedChatIds } as T;
700
+ if (method === 'GET' && cleanPath === '/api/v2/llm/credential') {
701
+ return {
702
+ ok: true,
703
+ source: 'config',
704
+ envNames: [],
705
+ provider: state.llmSettings.provider,
706
+ vendorId: state.llmSettings.vendorId ?? 'openrouter',
707
+ model: state.llmSettings.model,
708
+ } as T;
439
709
  }
440
710
 
441
- if (method === 'POST' && cleanPath === '/api/v2/chats/new') {
442
- const body = input.body as { agentId?: string } | undefined;
443
- const agentId = body?.agentId || pickDefaultAgentId(state.agents) || null;
444
- const chatId = `chat-browser-${Date.now()}`;
445
- const chat = createChatRecord({
446
- id: chatId,
447
- title: 'New chat',
448
- agentId,
449
- minutesAgo: 0,
450
- });
451
- chat.createdAt = new Date().toISOString();
452
- chat.updatedAt = chat.createdAt;
453
- state.chats.unshift(chat);
454
- state.messagesByChatId[chatId] = [];
711
+ if (method === 'GET' && cleanPath === '/api/v2/llm/catalog') {
712
+ return { providers: DEMO_CATALOG_PROVIDERS } as T;
713
+ }
714
+
715
+ if (method === 'GET' && cleanPath === '/api/v2/llm/models') {
455
716
  return {
456
- success: true,
457
- chatId,
458
- projectId: null,
459
- isTemporary: false,
717
+ models: DEMO_MODELS,
718
+ catalogStatus: 'live',
719
+ fetchedAt: Date.now(),
720
+ current: { model: state.llmSettings.model, reasoningEffort: 'high' },
460
721
  } as T;
461
722
  }
462
723
 
463
- const messagesChatId = getChatIdFromPath(path, '/messages');
464
- if (method === 'GET' && messagesChatId) {
465
- const messages = state.messagesByChatId[messagesChatId] ?? [];
466
- return { messages: [...messages].sort((a, b) => b.createdAt.localeCompare(a.createdAt)) } as T;
724
+ if (method === 'GET' && cleanPath === '/api/v2/compat/flags') {
725
+ return {
726
+ flags: [
727
+ {
728
+ key: 'supportsUsageInStreaming',
729
+ field: 'supportsUsageInStreaming',
730
+ kind: 'bool',
731
+ default: true,
732
+ description: 'Include token usage frames at the end of streamed responses.',
733
+ },
734
+ {
735
+ key: 'supportsReasoningEffort',
736
+ field: 'supportsReasoningEffort',
737
+ kind: 'bool',
738
+ default: true,
739
+ description: 'Forward reasoning_effort to gateways that expose thinking levels.',
740
+ },
741
+ ],
742
+ } as T;
467
743
  }
468
744
 
469
- const deleteChatId = getChatIdFromPath(path);
470
- if (method === 'DELETE' && deleteChatId) {
471
- const onlyIfEmpty = parseQuery(path).get('onlyIfEmpty') === '1';
472
- if (onlyIfEmpty) {
473
- const messages = state.messagesByChatId[deleteChatId] ?? [];
474
- const exists = state.chats.some((chat) => chat.id === deleteChatId);
475
- if (!exists || messages.length > 0) {
476
- return { success: true, deleted: false, chatId: deleteChatId } as T;
477
- }
478
- state.chats = state.chats.filter((chat) => chat.id !== deleteChatId);
479
- delete state.messagesByChatId[deleteChatId];
480
- return { success: true, deleted: true, chatId: deleteChatId } as T;
481
- }
482
- state.chats = state.chats.filter((chat) => chat.id !== deleteChatId);
483
- delete state.messagesByChatId[deleteChatId];
484
- return { success: true, message: 'deleted in browser mock', chatId: deleteChatId } as T;
745
+ if (method === 'GET' && cleanPath === '/api/v2/llm/presets') {
746
+ return {
747
+ presets: [
748
+ {
749
+ host: 'openrouter.ai',
750
+ modelPrefix: 'glm-5.3',
751
+ temperature: 0.3,
752
+ topP: null,
753
+ maxTokens: null,
754
+ reasoningEffort: 'high',
755
+ extraBody: null,
756
+ },
757
+ ],
758
+ } as T;
759
+ }
760
+
761
+ if (method === 'GET' && cleanPath === '/api/v2/llm/presets/resolve') {
762
+ return {
763
+ preset: {
764
+ temperature: 0.3,
765
+ reasoningEffort: 'high',
766
+ },
767
+ } as T;
485
768
  }
486
769
 
487
770
  if (method === 'GET' && cleanPath === '/api/v2/llm/account') {
@@ -497,7 +780,147 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
497
780
  } as T;
498
781
  }
499
782
 
500
- throw new Error(`Browser dev mock does not implement ${method} ${path}`);
783
+ if (method === 'POST' && cleanPath === '/api/v2/llm/diagnose') {
784
+ return {
785
+ ok: true,
786
+ steps: [
787
+ { name: 'Gateway DNS & TLS', ok: true, durationMs: 18, detail: 'Playbook endpoint reachable' },
788
+ { name: 'Model catalog check', ok: true, durationMs: 24, detail: `${state.llmSettings.model} listed` },
789
+ ],
790
+ ambientProxies: [],
791
+ hint: 'Interactive browser playbook active (run steerable-cli locally to probe live keys).',
792
+ } as T;
793
+ }
794
+
795
+ // ---- Sandbox, usage, search, telemetry, insights, MCP, portable, local files ----
796
+ if (method === 'GET' && cleanPath === '/api/v2/sidecar/sandbox-posture') {
797
+ return {
798
+ posture: { backend: 'seatbelt', enforcement: 'partial', reason: 'active' },
799
+ egress: { mode: 'per-host-proxy', reason: null },
800
+ } as T;
801
+ }
802
+
803
+ if (method === 'GET' && cleanPath === '/api/v2/usage/summary') {
804
+ const sinceDays = Number(parseQuery(path).get('days') ?? '30');
805
+ return {
806
+ sinceDays,
807
+ byModel: [
808
+ {
809
+ model: 'glm-5.3-flash',
810
+ provider: 'openai-compat',
811
+ turns: 4,
812
+ promptTokens: 23_110,
813
+ completionTokens: 1_660,
814
+ totalTokens: 24_770,
815
+ cachedPromptTokens: 15_000,
816
+ costUsd: 0.0051,
817
+ },
818
+ ],
819
+ totals: {
820
+ turns: 4,
821
+ promptTokens: 23_110,
822
+ completionTokens: 1_660,
823
+ totalTokens: 24_770,
824
+ cachedPromptTokens: 15_000,
825
+ costUsd: 0.0051,
826
+ partialTurns: 0,
827
+ },
828
+ } as T;
829
+ }
830
+
831
+ if (method === 'GET' && cleanPath === '/api/v2/usage/reliability') {
832
+ const sinceDays = Number(parseQuery(path).get('days') ?? '7');
833
+ return {
834
+ sinceDays,
835
+ total: 12,
836
+ failed: 0,
837
+ cancelled: 0,
838
+ recoveredByRetry: 2,
839
+ usedDirect: 10,
840
+ failuresByKind: [],
841
+ } as T;
842
+ }
843
+
844
+ if (method === 'GET' && cleanPath === '/api/v2/local-settings/web-search') {
845
+ return state.webSearchSettings as T;
846
+ }
847
+ if (method === 'POST' && cleanPath === '/api/v2/local-settings/web-search') {
848
+ state.webSearchSettings = {
849
+ ...state.webSearchSettings,
850
+ ...(input.body as Partial<BrowserMockState['webSearchSettings']>),
851
+ };
852
+ return state.webSearchSettings as T;
853
+ }
854
+
855
+ if (method === 'GET' && cleanPath === '/api/v2/local-settings/telemetry') {
856
+ return state.telemetrySettings as T;
857
+ }
858
+ if (method === 'POST' && cleanPath === '/api/v2/local-settings/telemetry') {
859
+ state.telemetrySettings = {
860
+ ...state.telemetrySettings,
861
+ ...(input.body as Partial<BrowserMockState['telemetrySettings']>),
862
+ };
863
+ return state.telemetrySettings as T;
864
+ }
865
+
866
+ if (method === 'GET' && cleanPath === '/api/v2/local-settings/insights') {
867
+ return state.insightsSettings as T;
868
+ }
869
+ if (method === 'POST' && cleanPath === '/api/v2/local-settings/insights') {
870
+ const body = (input.body ?? {}) as Record<string, unknown>;
871
+ state.insightsSettings = {
872
+ ...state.insightsSettings,
873
+ ...(typeof body.shareBehavior === 'boolean' ? { shareBehavior: body.shareBehavior } : {}),
874
+ ...(typeof body.shareConversation === 'boolean'
875
+ ? { shareConversation: body.shareConversation }
876
+ : {}),
877
+ ...(typeof body.shareProfile === 'boolean' ? { shareProfile: body.shareProfile } : {}),
878
+ };
879
+ return state.insightsSettings as T;
880
+ }
881
+ if (method === 'POST' && cleanPath === '/api/v2/insights/events') {
882
+ return { ok: true } as T;
883
+ }
884
+
885
+ if (method === 'GET' && cleanPath === '/api/v2/mcp/servers') {
886
+ return { servers: state.mcpServers } as T;
887
+ }
888
+
889
+ if (method === 'GET' && cleanPath === '/api/v2/portable/config') {
890
+ return {
891
+ version: 1,
892
+ exportedAt: new Date().toISOString(),
893
+ llm: state.llmSettings,
894
+ agents: state.agents,
895
+ } as T;
896
+ }
897
+
898
+ if (method === 'POST' && cleanPath === '/api/v2/local/resolve-paths') {
899
+ return { resolved: [] } as T;
900
+ }
901
+
902
+ if (method === 'POST' && cleanPath === '/api/v2/local/open-path') {
903
+ return { success: true } as T;
904
+ }
905
+
906
+ if (method === 'GET' && cleanPath === '/api/v2/local/download') {
907
+ const targetPath = parseQuery(path).get('path') ?? '';
908
+ const sample = DEMO_SAMPLE_FILES[targetPath];
909
+ const fileName = sample?.fileName ?? (targetPath.split('/').pop() || 'demo-artifact.txt');
910
+ const content =
911
+ sample?.content ??
912
+ `# Demo Artifact\n\nGenerated in browser interactive playbook for path: ${targetPath}\n`;
913
+ return {
914
+ fileName,
915
+ mime: sample?.mime ?? 'text/plain; charset=utf-8',
916
+ size: new TextEncoder().encode(content).byteLength,
917
+ base64: encodeUtf8Base64(content),
918
+ } as T;
919
+ }
920
+
921
+ // Soft fallback for any secondary diagnostic/export endpoint in demo mode
922
+ console.warn(`[browser-dev-host-mock] Unhandled route ${method} ${path}, returning empty object.`);
923
+ return {} as T;
501
924
  }
502
925
 
503
926
  function pushSse(
@@ -510,115 +933,211 @@ function pushSse(
510
933
  onEvent({ type: 'data', chunk: `${prefix}data: ${payload}\n\n` });
511
934
  }
512
935
 
513
- function scheduleStreamTimer(streamId: string, callback: () => void, delay: number) {
936
+ function scheduleStreamTimer(record: ActiveStreamRecord, callback: () => void, delay: number) {
514
937
  const timer = window.setTimeout(callback, delay);
515
- const timers = state.activeStreams.get(streamId) ?? [];
516
- timers.push(timer);
517
- state.activeStreams.set(streamId, timers);
938
+ record.timers.push(timer);
518
939
  }
519
940
 
520
941
  async function startStream(
521
942
  input: LocalBackendRequestInput,
522
943
  onEvent: (payload: LocalBackendStreamEvent) => void,
523
944
  ): Promise<string | null> {
524
- const chatId = getChatIdFromPath(input.path, '/run');
945
+ const cleanPath = stripQuery(input.path);
946
+ const runMatch = cleanPath.match(/^\/api\/v2\/chats\/([^/]+)\/run$/);
947
+ const regenMatch = cleanPath.match(/^\/api\/v2\/chats\/([^/]+)\/messages\/([^/]+)\/regenerate$/);
948
+ const chatId = decodeURIComponent((runMatch?.[1] ?? regenMatch?.[1] ?? '').trim());
949
+
525
950
  if (!chatId) {
526
951
  onEvent({ type: 'error', error: `Invalid mock stream path: ${input.path}` });
527
952
  return null;
528
953
  }
529
954
 
530
- const body = input.body as { message?: string } | undefined;
531
- const message = body?.message?.trim() || 'Please demo a browser mock reply.';
532
- const streamId = `browser-stream-${Date.now()}`;
533
- state.activeStreams.set(streamId, []);
955
+ const body = (input.body ?? {}) as {
956
+ message?: string;
957
+ model?: string;
958
+ reasoningEffort?: string;
959
+ execPolicy?: string;
960
+ mode?: string;
961
+ };
962
+
963
+ let promptText = body.message?.trim() || '';
964
+ if (regenMatch && !promptText) {
965
+ const priorUser = [...(state.messagesByChatId[chatId] ?? [])]
966
+ .reverse()
967
+ .find((m) => m.role === 'user');
968
+ promptText = priorUser?.content || 'Regenerate response';
969
+ }
970
+ if (!promptText) promptText = 'Show Steerable demo playbook';
534
971
 
535
- const userMessage = createMessage({
536
- id: `msg-user-${Date.now()}`,
972
+ const streamId = `demo-stream-${Date.now()}`;
973
+ const record: ActiveStreamRecord = {
974
+ streamId,
537
975
  chatId,
538
- role: 'user',
539
- content: message,
540
- minutesAgo: 0,
541
- });
542
- userMessage.createdAt = new Date().toISOString();
543
- state.messagesByChatId[chatId] = [...(state.messagesByChatId[chatId] ?? []), userMessage];
544
-
545
- const reply =
546
- `This is a streaming reply from the browser dev mock. You wrote: "${message}".` +
547
- ' Use it to debug message bubbles, scrolling, the stop button, tool cards, and later status.';
548
- const chunks = reply.match(/.{1,8}/g) ?? [reply];
549
- const reasoning = 'Call one mock tool, then interleave the reply with that call.';
550
- const mockAction = {
551
- id: 'browser-mock-1',
552
- tool: 'browser_mock',
553
- arguments: { path: input.path },
554
- result: { success: true, output: 'Generated mock stream in browser preview.' },
976
+ timers: [],
977
+ onEvent,
978
+ steerNote: null,
979
+ snapshot: { active: true, status: 'running', content: '', executedActions: [], timeline: [] },
555
980
  };
981
+ state.activeStreams.set(streamId, record);
556
982
 
557
- scheduleStreamTimer(streamId, () => {
558
- pushSse(onEvent, { type: 'reasoning', content: reasoning });
559
- }, 80);
983
+ const isFirstTurn = (state.messagesByChatId[chatId] ?? []).length === 0;
984
+ if (!regenMatch) {
985
+ const userMessage: MutableMessage = {
986
+ id: `msg-user-${Date.now()}`,
987
+ chatId,
988
+ role: 'user',
989
+ content: promptText,
990
+ createdAt: new Date().toISOString(),
991
+ messageMetadata: null,
992
+ };
993
+ state.messagesByChatId[chatId] = [...(state.messagesByChatId[chatId] ?? []), userMessage];
994
+ }
560
995
 
561
- scheduleStreamTimer(streamId, () => {
562
- pushSse(onEvent, {
563
- type: 'executed_actions',
564
- actions: [{ ...mockAction, result: undefined }],
565
- });
566
- }, 160);
996
+ const script = buildPlaybookScript({
997
+ message: promptText,
998
+ model: body.model || state.llmSettings.model,
999
+ reasoningEffort: body.reasoningEffort ?? 'high',
1000
+ execPolicy: body.execPolicy ?? 'workspace',
1001
+ mode: body.mode ?? 'agent',
1002
+ });
567
1003
 
568
- scheduleStreamTimer(streamId, () => {
569
- pushSse(onEvent, {
570
- type: 'executed_actions',
571
- actions: [mockAction],
1004
+ if (isFirstTurn) {
1005
+ const chat = state.chats.find((c) => c.id === chatId);
1006
+ if (chat && (chat.title === 'New chat' || !chat.title)) {
1007
+ chat.title = script.chatTitle;
1008
+ for (const listener of chatTitleListeners) {
1009
+ listener({ chatId, title: script.chatTitle });
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ let delay = 60;
1015
+ const accumulatedActions: unknown[] = [];
1016
+ const persistedTimeline: unknown[] = [];
1017
+
1018
+ script.rounds.forEach((round, roundIndex) => {
1019
+ if (roundIndex > 0) {
1020
+ scheduleStreamTimer(record, () => {
1021
+ pushSse(onEvent, { type: 'completion', status: 'executing' });
1022
+ }, delay);
1023
+ delay += 120;
1024
+ }
1025
+
1026
+ scheduleStreamTimer(record, () => {
1027
+ pushSse(onEvent, { type: 'reasoning', content: round.reasoning });
1028
+ persistedTimeline.push({ type: 'reasoning', content: round.reasoning });
1029
+ record.snapshot.timeline = [...persistedTimeline];
1030
+ }, delay);
1031
+ delay += 140;
1032
+
1033
+ const roundCompletedActions: unknown[] = [];
1034
+ round.actions.forEach((action) => {
1035
+ const runningAction = { ...action, result: undefined };
1036
+ const runningList = [...accumulatedActions, ...roundCompletedActions, runningAction];
1037
+ scheduleStreamTimer(record, () => {
1038
+ pushSse(onEvent, { type: 'executed_actions', actions: runningList });
1039
+ record.snapshot.executedActions = runningList;
1040
+ }, delay);
1041
+ delay += 180;
1042
+
1043
+ roundCompletedActions.push(action);
1044
+ const completedList = [...accumulatedActions, ...roundCompletedActions];
1045
+ scheduleStreamTimer(record, () => {
1046
+ pushSse(onEvent, { type: 'executed_actions', actions: completedList });
1047
+ record.snapshot.executedActions = completedList;
1048
+ }, delay);
1049
+ delay += 120;
572
1050
  });
573
- }, 280);
574
1051
 
575
- chunks.forEach((chunk, index) => {
576
- scheduleStreamTimer(streamId, () => {
1052
+ accumulatedActions.push(...roundCompletedActions);
1053
+ persistedTimeline.push({ type: 'tools', actions: roundCompletedActions });
1054
+ });
1055
+
1056
+ const baseReply = script.reply;
1057
+ const chunks = baseReply.match(/.{1,14}/gs) ?? [baseReply];
1058
+ chunks.forEach((chunk) => {
1059
+ scheduleStreamTimer(record, () => {
577
1060
  pushSse(onEvent, { content: chunk });
578
- }, 360 + index * 80);
1061
+ record.snapshot.content = `${record.snapshot.content ?? ''}${chunk}`;
1062
+ }, delay);
1063
+ delay += 38;
579
1064
  });
580
1065
 
581
- scheduleStreamTimer(streamId, () => {
582
- const assistantMessage = createMessage({
583
- id: `msg-assistant-${Date.now()}`,
1066
+ scheduleStreamTimer(record, () => {
1067
+ let finalReply = baseReply;
1068
+ if (record.steerNote) {
1069
+ const steerSuffix = `\n\n> Steered mid-turn: "${record.steerNote}"`;
1070
+ pushSse(onEvent, { content: steerSuffix });
1071
+ finalReply += steerSuffix;
1072
+ }
1073
+
1074
+ if (script.turnFiles && script.turnFiles.length > 0) {
1075
+ pushSse(onEvent, {
1076
+ type: 'agent',
1077
+ event: 'turn_files',
1078
+ payload: { files: script.turnFiles },
1079
+ });
1080
+ }
1081
+
1082
+ pushSse(onEvent, {
1083
+ type: 'agent',
1084
+ event: 'turn_usage',
1085
+ payload: { usage: script.usage },
1086
+ });
1087
+
1088
+ const assistantId = `msg-assistant-${Date.now()}`;
1089
+ const finalTimeline = [...persistedTimeline, { type: 'text', content: finalReply }];
1090
+ const assistantMessage: MutableMessage = {
1091
+ id: assistantId,
584
1092
  chatId,
585
1093
  role: 'assistant',
586
- content: reply,
587
- minutesAgo: 0,
1094
+ content: finalReply,
1095
+ createdAt: new Date().toISOString(),
588
1096
  messageMetadata: JSON.stringify({
589
- executedActions: [mockAction],
590
- timeline: [
591
- { type: 'reasoning', content: reasoning },
592
- { type: 'tools', actions: [mockAction] },
593
- { type: 'text', content: reply },
594
- ],
595
- durationMs: 1_200,
596
- suggestedReplies: ['Keep improving this result', 'Try another presentation', 'Tell me the next step'],
1097
+ completionStatus: 'completed',
1098
+ executedActions: accumulatedActions,
1099
+ timeline: finalTimeline,
1100
+ ...(script.turnFiles ? { turnFiles: script.turnFiles } : {}),
1101
+ usage: script.usage,
1102
+ durationMs: delay,
1103
+ suggestedReplies: script.suggestedReplies,
597
1104
  }),
598
- });
599
- assistantMessage.createdAt = new Date().toISOString();
600
- state.messagesByChatId[chatId] = [
601
- ...(state.messagesByChatId[chatId] ?? []),
602
- assistantMessage,
603
- ];
1105
+ };
1106
+ state.messagesByChatId[chatId] = [...(state.messagesByChatId[chatId] ?? []), assistantMessage];
604
1107
  updateChatTimestamp(chatId);
605
- pushSse(onEvent, { type: 'message_id', messageId: assistantMessage.id });
1108
+
1109
+ pushSse(onEvent, { type: 'message_id', messageId: assistantId });
606
1110
  pushSse(onEvent, '[DONE]');
607
1111
  onEvent({ type: 'end', status: 200 });
608
1112
  state.activeStreams.delete(streamId);
609
- const suggestions = ['Keep improving this result', 'Try another presentation', 'Tell me the next step'];
1113
+
610
1114
  for (const listener of suggestedReplyListeners) {
611
- listener({ chatId, messageId: assistantMessage.id, suggestions });
1115
+ listener({
1116
+ chatId,
1117
+ messageId: assistantId,
1118
+ suggestions: script.suggestedReplies,
1119
+ });
612
1120
  }
613
- }, 440 + chunks.length * 80);
1121
+ }, delay + 60);
614
1122
 
615
1123
  return streamId;
616
1124
  }
617
1125
 
618
1126
  function cancelStream(streamId: string) {
619
- const timers = state.activeStreams.get(streamId) ?? [];
620
- timers.forEach((timer) => window.clearTimeout(timer));
1127
+ const record = state.activeStreams.get(streamId);
1128
+ if (!record) return;
1129
+ record.timers.forEach((timer) => window.clearTimeout(timer));
621
1130
  state.activeStreams.delete(streamId);
1131
+ pushSse(record.onEvent, { type: 'completion', status: 'cancelled' });
1132
+ pushSse(record.onEvent, '[DONE]');
1133
+ record.onEvent({ type: 'end', status: 200 });
1134
+ }
1135
+
1136
+ async function steerChat(chatId: string, content: string): Promise<boolean> {
1137
+ const active = findActiveStreamByChat(chatId);
1138
+ if (!active) return false;
1139
+ active.steerNote = content.trim();
1140
+ return true;
622
1141
  }
623
1142
 
624
1143
  export function installBrowserDevHostMock() {
@@ -629,29 +1148,45 @@ export function installBrowserDevHostMock() {
629
1148
 
630
1149
  window.steerableHost = {
631
1150
  runtime: 'local',
632
- platform: 'win32',
1151
+ platform: 'darwin',
633
1152
  local: {
634
1153
  selectDirectory: async () => ({
635
1154
  canceled: false,
636
- filePaths: ['C:\\browser-preview\\mock-skill'],
1155
+ filePaths: ['/workspace/steerable-eval-sandbox'],
637
1156
  }),
638
- // 浏览器 dev 模式没有桌面截图和剪贴板,如实返回失败。
639
1157
  captureScreenshot: async () => ({
640
1158
  success: false as const,
641
- error: 'Browser dev mode cannot capture a window screenshot.',
1159
+ error: 'Browser demo mode cannot capture a window screenshot.',
642
1160
  }),
643
1161
  },
644
1162
  localBackend: {
645
1163
  request,
646
1164
  startStream,
647
1165
  cancelStream,
1166
+ steerChat,
648
1167
  },
649
1168
  onMenuNewChat: () => undefined,
650
1169
  offMenuNewChat: () => undefined,
651
1170
  onMenuOpenTerminal: () => undefined,
652
1171
  offMenuOpenTerminal: () => undefined,
653
- onChatTitleUpdated: () => () => undefined,
654
- onChatActivity: () => () => undefined,
1172
+ onChatTitleUpdated: (callback) => {
1173
+ chatTitleListeners.add(callback);
1174
+ return () => {
1175
+ chatTitleListeners.delete(callback);
1176
+ };
1177
+ },
1178
+ onChatCreated: (callback) => {
1179
+ chatCreatedListeners.add(callback);
1180
+ return () => {
1181
+ chatCreatedListeners.delete(callback);
1182
+ };
1183
+ },
1184
+ onChatActivity: (callback) => {
1185
+ chatActivityListeners.add(callback);
1186
+ return () => {
1187
+ chatActivityListeners.delete(callback);
1188
+ };
1189
+ },
655
1190
  onSuggestedReplies: (callback) => {
656
1191
  suggestedReplyListeners.add(callback);
657
1192
  return () => {