返回 DeepSeek-Reasonix
bridge.ts
根目录 / desktop / frontend / src / lib / bridge.ts
1 import { makeLazyPreviousDraftMock } from "./previousDraftBindings";
2 import { makeMockSessionExportBindings, type SessionExportBindings } from "./sessionExportBridge";
3 import type { AttachmentBindings } from "./attachmentBindings";
4 import { makeMockSessionLifecycleBindings, type SessionLifecycleBindings } from "./sessionLifecycleBindings";
5 import { makeMockModelSettingsBindings, type ModelSettingsBindings } from "./modelSettingsBridge";
6 import { mockProviderTemplate, mockPreset, mockBundlePreset, mockKimiAPIModels, mockLongCatModels, mockTokenRhythmModels, mockTokenRhythmModelOverrides, mockMiMoDefaults, mockMiniMaxModels, mockGLMAPIModels, mockGLMCodingModels, mockGLMAnthropicModels, mockQwenAPIModels, mockQwenPlanModels, mockQwenPlanVisionModels, mockStepFunModels, mockOpenCodeGoModels, mockNovitaModels, mockGMIModels, mockVercelModels, mockOllamaCloudModels } from "./mockProviderTemplates";
7 // The Electron host and the browser mock share this React-to-Go contract.
8 import type {
9 CancelReceipt,
10 ChatFileReferenceRequest,
11 ChatFileReferenceResult,
12 DesktopCommandName,
13 HistoryWindowPage,
14 HistoryWindowRequest,
15 LegacyEmptySessionCleanupStatus,
16 FileBrowserPreviewRequest,
17 FileBrowserPreviewResult,
18 MarkdownSVGView,
19 MessageFieldPage,
20 MessageHistoryPage,
21 MessageLocation,
22 Ref as SessionContentRef,
23 SearchHistoryPage,
24 SessionArchitectureDiagnostics,
25 SessionCreationResult,
26 SessionDraftContextView,
27 SessionDraftSaveRequest,
28 SessionDraftSaveResult,
29 SessionDraftSubmissionRequest,
30 SessionDraftSubmissionView,
31 SessionDraftSummary,
32 SessionDraftView,
33 SessionHistoryContentChunk,
34 SessionMutationResult,
35 SessionRef,
36 SessionSelector,
37 ComposerTarget,
38 WorkspaceSessionPage,
39 WorkspaceSnapshot,
40 } from "../generated/desktopContract.generated";
41 export type { FileBrowserPreviewRequest, FileBrowserPreviewResult } from "../generated/desktopContract.generated";
42 import type { ExactInteractionBindings } from "./exactInteractionBindings";
43 import type { InvocationRequest } from "./invocationDisplay";
44 import type { FollowupBindings } from "./pendingFollowup";
45 import type { InboxQueueBindings } from "./inboxQueueCommands";
46 import { addBreadcrumb } from "./breadcrumbs";
47 import { maybeShare } from "./queryCoalesce";
48 import { makeMockSessionCatalogBindings } from "./sessionCatalogBridge";
49 import { makeMockHistoryCatalogBindings, type HistoryCatalogBindings } from "./historyCatalogBridge";
50 import { makeMockTaskCatalogBindings, type TaskCatalogBindings } from "./taskCatalogBridge";
51 import { makeMockBlankProjectBindings, type BlankProjectBindings } from "./blankProjectBridge";
52 import { makeMockQualityFloorBindings, type QualityFloorBindings } from "./deliveryFloorBridge";
53 import { t } from "./i18n";
54 import { makeMockForkBindings, withMockHistoryIds } from "./mockForkWorktree";
55 import { makeMockWorktreeMergeBindings } from "./worktreeMergeMock";
56 import { providerIsConfigured, providerRequiresKey, removeProviderAccessesForMock } from "./providerModels";
57 import { DEFAULT_STATUS_BAR_ITEMS } from "./statusBarItems";
58 import { registerTrustedThemeBackgroundURLs } from "./themePack";
59 import { modeHasAutoApproveTools, modeWithAutoApproveTools, modeWithPlan, normalizeCollaborationMode, normalizeMode, normalizeToolApprovalMode } from "./types";
60 import { makeMockProjectTreeOrganizationBindings, subscribeMockProjectTreeChanged, notifyMockProjectTreeChanged } from "./mockProjectTreeOrganization";
61 import { decisionSurfaceMockFromInput, isLongDecisionOptionsMockInput } from "./decisionSurfaceMock";
62 import { mockWorkspaceFile } from "./mockWorkspaceFile";
63 import { mockAIRenameTarget, mockSessionTitleTarget, type SessionTitleBindings } from "./mockSessionTitle";
64 import { sessionTitleTarget } from "./sessionTitleOperation";
65 import { mockHistoryContentField, mockHistorySlice, mockTopicHistory as topicHistoryFixture } from "./bridgeHistoryFixtures";
66 import { createMockModelScopePreset, type MockProviderPresetTemplate } from "./mockModelScopePreset";
67 import { createMockRemoteProjects } from "./mockRemoteProjects";
68 import { createBrowserMockInteractionIdentity, mockSessionMeta, withMockSessionIdentity } from "./browserMockInteractionIdentity";
69 import { mockRemoteHostView } from "./mockRemoteHosts";
70 import type { RemoteProjectBindings } from "./remoteProjectBridge";
71 import type { ForkTargetsBindings } from "./forkTargets";
72 import type { ToolRecoveryBindings } from "./toolRecovery";
73 import type { ScrollDiagnosticBindings } from "./scrollDiagnosticBridge";
74 import type { TranscriptProtocolBindings } from "./transcriptProtocol";
75 import { makeMockSessionReaderBindings, publishMockTranscriptEvent, type SessionReaderBindings } from "./sessionReaderBridge";
76 import { makeMockMCPAppBindings, type MCPAppBindings } from "./mcpAppBridge";
77 import { makeMockPinnedContextBindings, type PinnedContextBindings } from "./pinnedContextBridge";
78 import { createDesktopPreferencesMock } from "./desktopPreferencesMock";
79 import type {
80 TurnChanges,
81 TurnFileChange,
82 RemoteHostView,
83 RemoteHostInput,
84 RemoteConnectionStatus,
85 RemoteDirEntry,
86 RemoteFilePreview,
87 RemoteWriteResult,
88 RemoteForwardInput,
89 RemoteForwardView,
90 RemoteServerView,
91 RemoteForwardsEvent,
92 RemoteLegacyWorkbenchData,
93 BalanceInfo,
94 UsageStatsRange,
95 UsageStatsRequest,
96 BotConnectionDiagnostic,
97 BotInstallPollResult,
98 BotInstallStartResult,
99 BotRuntimeStatusView,
100 BotSettingsView,
101 CapabilitiesView,
102 CapabilityDiagnosticsReport,
103 CredentialDiagnosticReport,
104 RuntimeDoctorReport,
105 CheckpointMeta,
106 CommandInfo,
107 ControlResult,
108 ContextInfo,
109 ContextPanelInfo,
110 DirEntry,
111 DesktopStartupSettingsView,
112 DeliveryWorktreeAvailability,
113 DeliveryWorktreeOpenResult,
114 WorktreeMergeInspection,
115 WorktreeMergeRequest,
116 WorktreeMergeResult,
117 WorktreeCleanupRequest,
118 WorktreeCleanupResult,
119 CloseMergedWorktreeTabRequest,
120 CloseMergedWorktreeTabResult,
121 DroppedItem,
122 EffortInfo,
123 ExtensionActionView,
124 FilePreview,
125 ExternalOpenersView,
126 HistoryMessage,
127 HistoryPage,
128 HistorySearchPage,
129 HistoryContentChunk,
130 HistoryContentRef,
131 HistorySlice,
132 HistorySliceRequest,
133 TabMetaRefreshEvent,
134 TopicActivationEvent,
135 TopicActivationRequest,
136 TopicActivationTicket,
137 HookConfigView,
138 HooksSettingsView,
139 JobView,
140 ActiveWorkView,
141 BackgroundRuntimeView,
142 JobCancelBatchView,
143 WorkspaceConflictView,
144 MCPMarketplaceEntry,
145 MCPServerInput,
146 MCPInstallResult,
147 MCPMarketplaceView,
148 MCPToolView,
149 MemoryFact,
150 MemorySuggestion,
151 MemorySuggestionsView,
152 MemoryView,
153 Meta,
154 Mode,
155 ModelInfo,
156 NetworkView,
157 PluginInstallOptions,
158 PluginView,
159 PermissionSnapshot,
160 ProjectNode,
161 ProjectTreeOrganizationBindings,
162 RecoveryLineageView,
163 RecoveryCleanupRequest,
164 RecoveryCleanupResult,
165 SessionCatalogBindings,
166 PromptHistoryEntry,
167 PromptHistoryResult,
168 ProviderModelCapabilityView,
169 ProviderModelCatalogUpdate,
170 ProviderPresetView,
171 ProviderView,
172 QuestionAnswer,
173 ServerView,
174 SessionMeta,
175 SessionRecoveryFailedEvent,
176 SessionRecoveryEvent,
177 SettingsView,
178 ShellInstallResult,
179 SkillsSettingsView,
180 SkillRootView,
181 SkillSuggestion,
182 SkillView,
183 TaskEvent,
184 TaskSnapshot,
185 SlashArgsResult,
186 SubagentProfileInput,
187 TabMeta,
188 TerminalSessionView,
189 TerminalWorkspaceView,
190 TopicMeta,
191 ToolApprovalMode,
192 TurnEventReplayView,
193 UpdateInfo,
194 UpdateProgress,
195 WireEvent,
196 WorkspaceChangeDetailView,
197 WorkspaceChangesView,
198 WorkspaceRevisions,
199 GitCommitView,
200 GitCommitDetailView,
201 WorkspaceView,
202 SessionClearResult,
203 } from "./types";
204 import { editMockGoalTab } from "./mockGoalLifecycle";
205 import { browserPreviewShellSupport, reloadBrowserPreviewShell } from "./shellSupportPreview";
206 import { desktopHost } from "./desktopHost";
207 export * from "./remoteTabEvents";
208 export const COMPACT_RATIO_MIN_PERCENT = 30, COMPACT_RATIO_MAX_PERCENT = 85;
209
210 export interface DesktopShellStatusView {
211 trayState: "probing" | "ready" | "unavailable";
212 backgroundCloseAvailable: boolean;
213 reason?: string;
214 }
215 import type { MarkdownImageView } from "./markdownImage";
216 const GLOBAL_PROJECT_ORDER_KEY = "__global__";
217
218 function stripLegacyGoalBudgetFlags(arg: string): string {
219 const parts = arg.trim().split(/\s+/).filter(Boolean);
220 while (parts.length > 0) {
221 const flag = parts[0].toLowerCase();
222 if (flag !== "--research" && flag !== "--auto-research" && flag !== "--deep" && flag !== "--simple" && flag !== "--no-research") break;
223 parts.shift();
224 }
225 return parts.join(" ");
226 }
227
228 // AppBindings is checked against the generated desktop host contract (see
229 // src/generated/desktopContract.generated.ts), so the compiler catches drift
230 // between the Go binding surface and the frontend mock. After adding or
231 // renaming a bound method on App, run `cd desktop && go run . -emit-contract
232 // frontend/src/generated`, then `pnpm typecheck` to verify the mock still
233 // satisfies the contract.
234 //
235 // Types for native-feel bindings, used only by AppBindings and the dev mock.
236 interface NativeConfirmRequest {
237 title: string;
238 message: string;
239 detail: string;
240 confirmLabel: string;
241 cancelLabel: string;
242 destructive: boolean;
243 }
244 interface DesktopWindowState {
245 width: number;
246 height: number;
247 x: number;
248 y: number;
249 maximised: boolean;
250 }
251 import { makeLazySessionUIMock, type SessionUIBindings } from "./sessionUIBindings";
252
253 export interface AppBindings extends SessionUIBindings {}
254 // AppBindings is the hand-written React-to-Go contract. _CheckGeneratedBindings
255 // catches generated methods missing here; update this interface and typecheck.
256 export interface AppBindings extends AttachmentBindings, SessionExportBindings, SessionLifecycleBindings, ForkTargetsBindings, ToolRecoveryBindings, ModelSettingsBindings, SessionCatalogBindings, ProjectTreeOrganizationBindings, HistoryCatalogBindings, TaskCatalogBindings, BlankProjectBindings, QualityFloorBindings, SessionTitleBindings, ScrollDiagnosticBindings, RemoteProjectBindings, MCPAppBindings, PinnedContextBindings, FollowupBindings, InboxQueueBindings, TranscriptProtocolBindings, SessionReaderBindings, ExactInteractionBindings {
257 GetLegacyEmptySessionCleanupStatus(): Promise<LegacyEmptySessionCleanupStatus>;
258 RetryLegacyEmptySessionCleanup(): Promise<LegacyEmptySessionCleanupStatus>;
259 OpenSessionDraft(workspaceId: string): Promise<SessionDraftView>;
260 OpenSessionDraftForTarget(scope: string, workspaceRoot: string): Promise<SessionDraftView>;
261 RestoreSessionDraft(): Promise<SessionDraftView | null>;
262 SaveSessionDraft(request: SessionDraftSaveRequest): Promise<SessionDraftSaveResult>;
263 ListSessionDraftSummaries(): Promise<SessionDraftSummary[]>;
264 DiscardSessionDraft(draftId: string, revision: number): Promise<void>;
265 DismissSessionDraft(draftId: string): Promise<void>;
266 SetSessionDraftRestoreTarget(draftId: string): Promise<void>;
267 GetSessionDraft(draftId: string): Promise<SessionDraftView>;
268 GetSessionDraftState(draftId: string): Promise<import("../generated/desktopContract.generated").SessionDraftState>;
269 ResumeDraftSubmission(operationId: string, revision: number): Promise<SessionDraftSubmissionView>;
270 GetDraftContext(draftId: string): Promise<SessionDraftContextView>;
271 BeginDraftSubmission(request: SessionDraftSubmissionRequest): Promise<SessionDraftSubmissionView>;
272 GetDraftSubmission(operationId: string): Promise<SessionDraftSubmissionView>;
273 CancelDraftSubmission(operationId: string): Promise<SessionDraftSubmissionView>;
274 SavePastedImageForComposerTarget(target: ComposerTarget, dataUrl: string): Promise<string>;
275 SavePastedFileForComposerTarget(target: ComposerTarget, name: string, dataUrl: string): Promise<string>;
276 SaveClipboardImageForComposerTarget(target: ComposerTarget): Promise<string>;
277 AttachDroppedForComposerTarget(target: ComposerTarget, path: string): Promise<DroppedItem>;
278 ListDirForTarget(target: ComposerTarget, rel: string): Promise<DirEntry[]>;
279 SearchFileRefsForTarget(target: ComposerTarget, query: string): Promise<DirEntry[]>;
280 AttachmentDataURLForComposerTarget(target: ComposerTarget, path: string): Promise<string>;
281 GetSessionActivityBaseline(selector: SessionSelector): Promise<import("../generated/desktopContract.generated").SessionActivityBaseline>;
282 GetWorkspaceSnapshot(): Promise<WorkspaceSnapshot>;
283 CreateSession(workspaceId: string): Promise<SessionRef>;
284 ForkSession(ref: SessionRef, turnBoundary: string): Promise<SessionRef>;
285 ForkSessionTarget(selector: SessionSelector, turnBoundary: string): Promise<SessionRef>;
286 CopySessionTarget(selector: SessionSelector, operationId: string): Promise<SessionCreationResult>;
287 HistorySliceForTarget(selector: SessionSelector, request: HistorySliceRequest): Promise<HistorySlice>;
288 HistoryContentForTarget(selector: SessionSelector, ref: HistoryContentRef, chunkIndex: number): Promise<HistoryContentChunk>;
289 SearchHistoryContentForTarget(selector: SessionSelector, query: string, cursor: string, limit: number): Promise<HistorySearchPage>;
290 SessionHistoryPageForTarget(selector: SessionSelector, cursor: string, limit: number): Promise<MessageHistoryPage>;
291 SessionHistoryContentForTarget(selector: SessionSelector, ref: SessionContentRef, offset: number): Promise<SessionHistoryContentChunk>;
292 LocateSessionMessageForTarget(selector: SessionSelector, messageId: string, snapshot: number): Promise<MessageLocation>;
293 SessionMessageFieldForTarget(selector: SessionSelector, messageId: string, version: number, field: string, offset: number, length: number): Promise<MessageFieldPage>;
294 SearchSessionHistoryForTarget(selector: SessionSelector, query: string, cursor: string, limit: number): Promise<SearchHistoryPage>;
295 SessionHistoryWindowForTarget(selector: SessionSelector, request: HistoryWindowRequest): Promise<HistoryWindowPage>;
296 ListWorkspaceSessions(workspaceId: string, query: string, cursor: string, limit: number, includeArchived: boolean): Promise<WorkspaceSessionPage>;
297 OpenSession(ref: SessionRef): Promise<HistoryPage>;
298 ReadSessionHistory(ref: SessionRef, cursor: string, limit: number): Promise<HistoryPage>;
299 RenameCanonicalSession(ref: SessionRef, title: string): Promise<void>;
300 SetSessionPinned(selector: SessionSelector, pinned: boolean): Promise<void>;
301 ArchiveCanonicalSession(ref: SessionRef): Promise<void>;
302 ArchiveSessionTarget(selector: SessionSelector): Promise<SessionMutationResult>;
303 RestoreCanonicalSession(ref: SessionRef): Promise<void>;
304 RestoreSessionTarget(selector: SessionSelector): Promise<SessionMutationResult>;
305 DeleteSessionTarget(selector: SessionSelector): Promise<SessionMutationResult>;
306 MoveWorkspaceSession(workspaceId: string, sessionId: string, beforeSessionId: string): Promise<void>;
307 MoveSessionTarget(selector: SessionSelector, workspaceId: string, beforeSessionId: string): Promise<SessionMutationResult>;
308 RenameWorkspace(workspaceId: string, title: string): Promise<void>;
309 SetWorkspaceVisible(workspaceId: string, visible: boolean): Promise<void>;
310 MoveWorkspace(workspaceId: string, beforeWorkspaceId: string): Promise<void>;
311 GetSessionArchitectureDiagnostics(): Promise<SessionArchitectureDiagnostics>;
312 Platform(): Promise<string>;
313 MinimiseMainWindow(): Promise<void>;
314 ToggleMaximiseMainWindow(): Promise<void>;
315 IsMainWindowMaximised(): Promise<boolean>;
316 CloseMainWindow(): Promise<void>;
317 // ── Heartbeat ──
318 HeartbeatListTasks(): Promise<unknown>;
319 HeartbeatReloadTasks(): Promise<unknown>;
320 HeartbeatSaveTasks(tasks: unknown): Promise<void>;
321 HeartbeatReloadConfig(): Promise<unknown>;
322 HeartbeatSaveConfig(update: unknown): Promise<unknown>;
323 HeartbeatTriggerNow(id: string): Promise<void>;
324 HeartbeatGenerateID(): Promise<string>;
325 Submit(input: string): Promise<void>;
326 SubmitToTab(tabID: string, input: string): Promise<void>;
327 SubmitToTabWithID(tabID: string, input: string, submissionID: string): Promise<void>;
328 StartTurnForTab?(tabID: string, input: string, submissionID: string): Promise<{ turnId: string; status: string; disposition?: "turn_started" | "management_handled"; operationId?: string; runtimeEpoch?: string; submissionId?: string }>;
329 SubmitDisplay(display: string, input: string): Promise<void>;
330 SubmitDisplayToTab(tabID: string, display: string, input: string): Promise<void>;
331 SubmitDisplayToTabWithID(tabID: string, display: string, input: string, submissionID: string): Promise<void>;
332 SubmitDeliveryRecoveryToTab(tabID: string, display: string, input: string): Promise<void>;
333 SubmitDeliveryRecoveryToTabWithID(tabID: string, display: string, input: string, submissionID: string): Promise<void>;
334 SubmitInvocationsToTab(tabID: string, display: string, input: string, invocations: InvocationRequest[]): Promise<void>;
335 SubmitInvocationsToTabWithID(tabID: string, display: string, input: string, invocations: InvocationRequest[], submissionID: string): Promise<void>;
336 SubmitInitialGoalToTab(
337 tabID: string,
338 goal: string,
339 display: string,
340 input: string,
341 invocations: InvocationRequest[],
342 collaborationMode: string,
343 toolApprovalMode: string,
344 ): Promise<string[]>;
345 SubmitInitialGoalToTabWithID(tabID: string, goal: string, display: string, input: string, invocations: InvocationRequest[], collaborationMode: string, toolApprovalMode: string, submissionID: string): Promise<string[]>;
346 SubmitEditedDisplayToTab(tabID: string, display: string, input: string, original: string): Promise<void>;
347 SubmitEditedDisplayToTabWithID(tabID: string, display: string, input: string, original: string, submissionID: string): Promise<void>;
348 RunShellForTab(tabID: string, command: string): Promise<void>;
349 Steer(text: string): Promise<void>;
350 SteerForTab(tabID: string, text: string): Promise<void>;
351 InboxSnapshot(tabID: string): Promise<{
352 revision: number;
353 paused: boolean;
354 recovered: boolean;
355 recoveredCount?: number; sessionPath?: string;
356 items: Array<{
357 id: string;
358 intent: string;
359 state: string;
360 preview: string;
361 byteSize: number;
362 source?: string;
363 position: number;
364 blockReason?: string;
365 }>;
366 itemsCount: number;
367 bytes: number;
368 maxItems: number;
369 maxBytes: number;
370 }>;
371 EnqueueInboxSteer(tabID: string, display: string, submit: string, idempotency: string): Promise<{ itemId: string; disposition: string; position: number; paused: boolean; idempotent?: boolean; error?: string }>;
372 EnqueueInboxSteerForTurn?(tabID: string, turnID: string, display: string, submit: string, idempotency: string): Promise<{ itemId: string; disposition: string; position: number; paused: boolean; idempotent?: boolean; error?: string }>;
373 SteerInboxItem(tabID: string, itemID: string): Promise<{
374 itemId: string; disposition: string; position: number; paused: boolean; idempotent?: boolean; error?: string;
375 }>;
376 SteerInboxItemForTurn?(tabID: string, turnID: string, itemID: string): Promise<{
377 itemId: string; disposition: string; position: number; paused: boolean; idempotent?: boolean; error?: string;
378 }>;
379 ReadInboxItem(tabID: string, id: string): Promise<{ id: string; displayText: string; rawText: string; submitText: string }>;
380 UpdateInboxItem(tabID: string, id: string, display: string, submit: string): Promise<void>;
381 DeleteInboxItem(tabID: string, id: string): Promise<void>;
382 MoveInboxItem(tabID: string, id: string, toIndex: number): Promise<void>;
383 SetInboxPaused(tabID: string, paused: boolean): Promise<void>;
384 RetryInboxItem(tabID: string, id: string): Promise<void>;
385 RefreshInboxItem(tabID: string, id: string): Promise<void>;
386 InboxHasItems(tabID: string): Promise<boolean>;
387 Cancel(): Promise<void>;
388 CancelTab(tabID: string): Promise<void>;
389 CancelSessionForTab?(tabID: string): Promise<CancelReceipt>;
390 CancelTabWithInboxItems(tabID: string, itemIDs: string[]): Promise<void>;
391 CancelTabWithInboxItemsResult?(tabID: string, itemIDs: string[]): Promise<{ discardedItemIds: string[]; warning?: string }>;
392 InterruptTurnForTab?(tabID: string, turnID: string): Promise<void>;
393 InterruptTurnWithInboxItemsForTab?(tabID: string, turnID: string, itemIDs: string[]): Promise<{ discardedItemIds: string[]; warning?: string }>;
394 TurnEventsForTab?(tabID: string, afterSeq: number): Promise<TurnEventReplayView>;
395 Approve(id: string, allow: boolean, session: boolean, persist: boolean): Promise<void>;
396 ApproveTab(tabID: string, id: string, allow: boolean, session: boolean, persist: boolean): Promise<void>;
397 ApproveTabForTurn?(tabID: string, turnID: string, runtimeEpoch: string, id: string, allow: boolean, session: boolean, persist: boolean): Promise<void>;
398 ResolvePlanDecision(id: string, action: "start_execution" | "revise_plan" | "exit_plan"): Promise<void>;
399 ResolvePlanDecisionTab(tabID: string, id: string, action: "start_execution" | "revise_plan" | "exit_plan"): Promise<void>;
400 ResolvePlanDecisionTabForTurn?(tabID: string, turnID: string, runtimeEpoch: string, id: string, action: "start_execution" | "revise_plan" | "exit_plan"): Promise<void>;
401 ResolveRecovery(id: string, action: string, feedback: string): Promise<void>;
402 ResolveRecoveryTab(tabID: string, id: string, action: string, feedback: string): Promise<void>;
403 ResolveRecoveryTabForTurn?(tabID: string, turnID: string, runtimeEpoch: string, id: string, action: string, feedback: string): Promise<void>;
404 SetRecoveryCheckpointEnabled(enabled: boolean): Promise<void>;
405 SetRecoveryCheckpointEnabledTab(tabID: string, enabled: boolean): Promise<void>;
406 RecoveryCheckpointEnabled(): Promise<boolean>;
407 RecoveryCheckpointEnabledTab(tabID: string): Promise<boolean>;
408 AnswerQuestion(id: string, answers: QuestionAnswer[]): Promise<void>;
409 AnswerQuestionForTab(tabID: string, id: string, answers: QuestionAnswer[]): Promise<void>;
410 AnswerMCPInteractionForTab(
411 tabID: string,
412 id: string,
413 action: "accept" | "decline" | "cancel",
414 content: Record<string, unknown> | null,
415 ): Promise<void>;
416 AnswerMCPInteractionForTurn?(tabID: string, turnID: string, runtimeEpoch: string, id: string, action: "accept" | "decline" | "cancel", content: Record<string, unknown> | null): Promise<void>;
417 AnswerPromptForTab?(tabID: string, turnID: string, id: string, answers: QuestionAnswer[]): Promise<void>;
418 ResolvePromptForTab?(tabID: string, promptID: string, turnID: string, runtimeEpoch: string, kind: string, answer: {
419 questions?: QuestionAnswer[]; allow?: boolean; session?: boolean; persist?: boolean;
420 action?: string; feedback?: string; content?: Record<string, unknown> | null;
421 generation?: number; permissionRevision?: number;
422 }): Promise<void>;
423 PendingPromptIdentitiesForTab?(tabID: string): Promise<Array<{ promptId: string; turnId: string; runtimeEpoch?: string; kind: string }>>;
424 ReplayPendingPromptIdentitiesForTab?(tabID: string): Promise<Array<{ promptId: string; turnId: string; runtimeEpoch?: string; kind: string }>>;
425 ReplayPendingPrompts(): Promise<void>;
426 ReplayPendingPromptsForTab(tabID: string): Promise<void>;
427 SetPlanMode(on: boolean): Promise<void>;
428 SetMode(mode: string): Promise<void>;
429 // Returns auto-allowed prompt ids; unlisted prompts remain pending (#6432).
430 SetModeForTab(tabID: string, mode: string): Promise<string[] | void>;
431 SetAutoApproveTools(on: boolean): Promise<void>;
432 SetCollaborationModeForTab(tabID: string, mode: string): Promise<void>;
433 SetToolApprovalMode(mode: string): Promise<void>;
434 // Same drained-prompt-id contract as SetModeForTab.
435 SetToolApprovalModeForTab(tabID: string, mode: string): Promise<string[] | void>;
436 PermissionSnapshotForTab(tabID: string): Promise<PermissionSnapshot>;
437 SetPermissionPresetForTab(tabID: string, expectedSessionID: string, preset: string, expectedRevision: number): Promise<PermissionSnapshot>;
438 RevokePermissionGrantForTab(tabID: string, scope: string, target: string, expectedRevision: number): Promise<PermissionSnapshot>;
439 // Atomically applies the controller-facing composer profile and reports any
440 // approval prompts drained by the resulting tool-approval posture.
441 SetComposerProfileForTab(tabID: string, collaborationMode: string, toolApprovalMode: string, goal: string): Promise<string[] | void>;
442 SetGoal(goal: string): Promise<void>;
443 SetGoalForTab(tabID: string, goal: string): Promise<void>;
444 EditGoalForTab(tabID: string, objective: string, maxGoalRounds: number | null): Promise<void>;
445 ResumeGoalForTab(tabID: string): Promise<boolean>;
446 PauseGoalForTab(tabID: string): Promise<boolean>;
447 ClearGoalForTab(tabID: string): Promise<void>;
448 Compact(): Promise<void>;
449 CompactForTab(tabID: string): Promise<void>;
450 NewSession(): Promise<void>;
451 NewSessionForTab(tabID: string): Promise<void>;
452 ClearSession(): Promise<SessionClearResult>;
453 ClearSessionForTab(tabID: string): Promise<SessionClearResult>;
454 History(): Promise<HistoryMessage[]>;
455 HistoryForTab(tabID: string): Promise<HistoryMessage[]>;
456 HistoryPage(beforeTurn: number, limit: number): Promise<HistoryPage>;
457 HistoryPageForTab(tabID: string, beforeTurn: number, limit: number): Promise<HistoryPage>;
458 // Windowed history paging (supersedes HistoryPageForTab for tab history).
459 HistorySliceForTab(tabID: string, req: HistorySliceRequest): Promise<HistorySlice>;
460 HistoryContentForTab(tabID: string, ref: HistoryContentRef, chunkIndex: number): Promise<HistoryContentChunk>;
461 HistoryCheckpointTurnsForTab(tabID: string): Promise<number[]>;
462 Checkpoints(): Promise<CheckpointMeta[]>;
463 CheckpointsForTab(tabID: string): Promise<CheckpointMeta[]>;
464 Rewind(turn: number, scope: string): Promise<void>;
465 RewindForTab(tabID: string, turn: number, scope: string): Promise<void>;
466 PreviewRewindForTab(tabID: string, turn: number, scope: string): Promise<import("./types").RewindPlanView>;
467 CommitRewindForTab(tabID: string, planID: string, turn: number, scope: string): Promise<import("./types").RewindResultView>;
468 UndoRewindForTab(tabID: string, transactionID: string): Promise<import("./types").RewindResultView>;
469 PreviewWorkspaceFileRevertForTab(tabID: string, path: string): Promise<import("./types").RewindPlanView>;
470 CommitWorkspaceFileRevertForTab(tabID: string, planID: string, resolution: string): Promise<import("./types").RewindResultView>;
471 Fork(turn: number): Promise<TabMeta>;
472 ForkForTab(tabID: string, turn: number): Promise<TabMeta>;
473 ForkWorktreeForTab(tabID: string, turn: number): Promise<import("./forkWorktree").ForkWorktreeResultView>;
474 SummarizeFrom(turn: number): Promise<void>;
475 SummarizeFromForTab(tabID: string, turn: number): Promise<void>;
476 SummarizeUpTo(turn: number): Promise<void>;
477 SummarizeUpToForTab(tabID: string, turn: number): Promise<void>;
478 ListSessions(): Promise<SessionMeta[]>;
479 ListSessionsForTab(tabID: string): Promise<SessionMeta[]>;
480 ListTrashedSessions(): Promise<SessionMeta[]>;
481 ResumeSession(path: string): Promise<HistoryMessage[]>;
482 ResumeSessionForTab(tabID: string, path: string): Promise<HistoryMessage[]>;
483 ResumeSessionPage(path: string, limit: number): Promise<HistoryPage>;
484 ResumeSessionPageForTab(tabID: string, path: string, limit: number): Promise<HistoryPage>;
485 OpenChannelSessionForTab(tabID: string, path: string): Promise<HistoryMessage[]>;
486 OpenChannelSessionPageForTab(tabID: string, path: string, limit: number): Promise<HistoryPage>;
487 PreviewSession(path: string): Promise<HistoryMessage[]>;
488 QuerySessionTakeover(tabId: string): Promise<import("./types").SessionTakeoverView | null>;
489 TakeoverSession(tabId: string, mode: "wait" | "interrupt"): Promise<void>;
490 DeleteSession(path: string): Promise<void>;
491 DeleteRecoveryCopy(path: string): Promise<void>;
492 GetRecoveryLineage(key: { scope: string; workspaceRoot?: string; topicId: string; path?: string; recordClassification?: boolean }): Promise<RecoveryLineageView>;
493 GetSessionVersionState(key: { scope: string; workspaceRoot?: string; topicId: string; path?: string; recordClassification?: boolean }): Promise<import("./types").SessionVersionStateView>;
494 SetActiveSessionVersion(request: import("./types").RecoveryPreferenceRequest): Promise<void>;
495 RetrySessionRecovery(request: import("./types").RecoveryPreferenceRequest): Promise<void>;
496 ReconcileRecoveryVersions(key: { scope: string; workspaceRoot?: string; topicId: string; path?: string }): Promise<void>;
497 ChooseRecoveryBranch(request: import("./types").RecoveryPreferenceRequest): Promise<void>;
498 CleanRecoveryLineage(request: RecoveryCleanupRequest): Promise<RecoveryCleanupResult>;
499 RestoreSession(path: string): Promise<void>;
500 PurgeTrashedSession(path: string): Promise<void>;
501 PurgeRecoveryCopy(path: string): Promise<void>;
502 RenameSession(path: string, title: string): Promise<void>;
503 RenameSessionHead(path: string, headId: string, name: string): Promise<void>;
504 ScanPromptHistory(nonce: string): Promise<PromptHistoryResult>;
505 ListWorkspaces(): Promise<WorkspaceView[]>;
506 PickWorkspace(): Promise<string>;
507 SwitchWorkspace(path: string): Promise<string>;
508 RemoveWorkspace(path: string): Promise<void>;
509 ContextUsageForTab(tabID: string): Promise<ContextInfo>;
510 Balance(): Promise<BalanceInfo>;
511 BalanceForTab(tabID: string): Promise<BalanceInfo>;
512 UsageStats(req: UsageStatsRequest): Promise<UsageStatsRange>;
513 Jobs(): Promise<JobView[]>;
514 ListTasks(): Promise<TaskSnapshot[]>;
515 CurrentTaskSessionID(): Promise<string>;
516 ListTasksForSession(sessionID: string): Promise<TaskSnapshot[]>;
517 GetTask(taskID: string): Promise<TaskSnapshot | null>;
518 StopTask(taskID: string, expectedVersion: number, reason: string, idemKey: string): Promise<ControlResult>;
519 CancelTask(taskID: string, expectedVersion: number, reason: string, idemKey: string): Promise<ControlResult>;
520 ListTasksForTab(tabID: string): Promise<TaskSnapshot[]>;
521 ListTaskEventsForTab(tabID: string, taskID: string, afterSequence: number): Promise<TaskEvent[]>;
522 StopTaskForTab(tabID: string, taskID: string, expectedVersion: number, reason: string, idemKey: string): Promise<ControlResult>;
523 CancelTaskForTab(tabID: string, taskID: string, expectedVersion: number, reason: string, idemKey: string): Promise<ControlResult>;
524 RequeueTaskForTab(tabID: string, taskID: string, expectedVersion: number, idemKey: string): Promise<ControlResult>;
525 OpenTaskSessionForTab(tabID: string, taskID: string): Promise<ControlResult>;
526 JobsForTab(tabID: string): Promise<JobView[]>;
527 CancelJob(jobID: string): Promise<boolean>;
528 CancelJobForTab(tabID: string, jobID: string): Promise<boolean>;
529 CancelJobsForTab(tabID: string, jobIDs: string[]): Promise<JobCancelBatchView>;
530 ActiveWorkForTab(tabID: string): Promise<ActiveWorkView>;
531 BackgroundRuntimes(): Promise<BackgroundRuntimeView[]>;
532 RevealBackgroundRuntime(tabID: string): Promise<TabMeta>;
533 WorkspaceConflictForTab(tabID: string): Promise<WorkspaceConflictView>;
534 RevealWorkspaceWriterForTab(tabID: string): Promise<TabMeta>;
535 CloseTabWithPolicy(tabID: string, policy: "keep_running" | "stop_and_close"): Promise<void>;
536 ToolResultForTab(tabID: string, toolID: string): Promise<{ name?: string; args: string; output: string; execution?: import("./types").WireShellExecution; mcpApp?: import("./types").MCPAppPresentation; presentedFiles?: import("./types").PresentedFile[] } | null>;
537 Meta(): Promise<Meta>;
538 MetaForTab(tabID: string): Promise<Meta>;
539 Commands(): Promise<CommandInfo[]>;
540 Capabilities(): Promise<CapabilitiesView>;
541 MCPServers(): Promise<ServerView[]>;
542 MCPCapabilityMatrix(): Promise<{
543 views: Array<{ id: string; layer: string; state: string; negotiated: boolean; detail: string }>;
544 hostProfile: string;
545 }>;
546 MCPMarketplace(query: string): Promise<MCPMarketplaceView>;
547 MCPMarketplaceResolve(registryName: string): Promise<MCPMarketplaceEntry>;
548 SkillsSettings(): Promise<SkillsSettingsView>;
549 CapabilityDiagnostics(includeSessionRuntime: boolean): Promise<CapabilityDiagnosticsReport>;
550 CredentialDiagnostics(probe: boolean): Promise<CredentialDiagnosticReport>;
551 RepairCredentials(dryRun: boolean): Promise<CredentialDiagnosticReport>;
552 RetryAuthenticationForTab(tabId: string): Promise<NonNullable<TabMeta["authentication"]>>;
553 RuntimeDoctor(): Promise<RuntimeDoctorReport>;
554 Plugins(): Promise<PluginView[]>;
555 PlanPluginInstall(source: string, options: PluginInstallOptions): Promise<string>;
556 InstallPlugin(source: string, options: PluginInstallOptions): Promise<string>;
557 RemovePlugin(name: string): Promise<void>;
558 SetPluginEnabled(name: string, enabled: boolean): Promise<void>;
559 UpdatePlugin(name: string): Promise<string>;
560 PluginDoctor(name: string): Promise<PluginView>;
561 // Extension UI (stage 8b2): enumerate handshake-declared extension actions
562 // for the command palette, invoke one, and deliver a form surface's values
563 // (or {cancelled: true} on dismissal) back to the owning sidecar.
564 ExtensionActions(tabID: string): Promise<ExtensionActionView[]>;
565 InvokeExtensionAction(tabID: string, name: string, args: Record<string, string>): Promise<string>;
566 SubmitExtensionForm(tabID: string, pluginID: string, surfaceID: string, values: Record<string, unknown>): Promise<void>;
567 AddMCPServer(input: MCPServerInput): Promise<number>;
568 InstallMCPServer(input: MCPServerInput): Promise<MCPInstallResult>;
569 UpdateMCPServer(name: string, input: MCPServerInput): Promise<void>;
570 RemoveMCPServer(name: string): Promise<void>;
571 AuthorizeAndConnectMCPServer(name: string): Promise<void>;
572 AuthenticateMCPServer(name: string): Promise<void>;
573 ReconnectMCPServer(name: string): Promise<void>;
574 ClearMCPServerAuthentication(name: string): Promise<void>;
575 PickSkillFolder(): Promise<string>;
576 PickPluginFolder(): Promise<string>;
577 AddSkillPath(path: string): Promise<void>;
578 RemoveSkillPath(path: string): Promise<void>;
579 SetSkillPathEnabled(path: string, enabled: boolean): Promise<void>;
580 RefreshSkills(): Promise<void>;
581 ReloadCommands(): Promise<void>;
582 SetSkillEnabled(name: string, enabled: boolean): Promise<void>;
583 SetSkillImplicitInvocation(enabled: boolean): Promise<void>;
584 AvailableSubagentTools(): Promise<MCPToolView[]>;
585 CreateSubagentProfile(input: SubagentProfileInput): Promise<string>;
586 UpdateSubagentProfile(name: string, scope: string, input: SubagentProfileInput): Promise<void>;
587 DeleteSubagentProfile(name: string, scope: string): Promise<void>;
588 SetSubagentProfileModel(name: string, ref: string): Promise<void>;
589 SetSubagentProfileEffort(name: string, level: string): Promise<void>;
590 TrySubagentProfile(input: SubagentProfileInput, task: string): Promise<string>;
591 CancelTrySubagentProfile(): Promise<void>;
592 SetMCPServerEnabled(name: string, enabled: boolean): Promise<void>;
593 SetMCPServerTier(name: string, tier: string): Promise<void>;
594 SlashArgs(input: string): Promise<SlashArgsResult>;
595 ListDir(rel: string): Promise<DirEntry[]>;
596 ListDirForTab(tabID: string, rel: string): Promise<DirEntry[]>;
597 SearchFileRefs(query: string): Promise<DirEntry[]>;
598 SearchFileRefsForTab(tabID: string, query: string): Promise<DirEntry[]>;
599 ReadFile(rel: string): Promise<FilePreview>;
600 ReadFileForTab(tabID: string, rel: string): Promise<FilePreview>;
601 ReadPresentedFileForTab(tabID: string, toolCallID: string, path: string): Promise<FilePreview>;
602 ReadPresentedFileSourceForTab(tabID: string, toolCallID: string, path: string): Promise<FilePreview>;
603 ReadPresentedTextPageForTab(tabID: string, toolCallID: string, path: string, offset: number, expectedVersion: string): Promise<import("./types").PresentedTextPage>;
604 ResolveChatFileReferencesForTab(tabID: string, turnKey: string, candidates: ChatFileReferenceRequest[]): Promise<ChatFileReferenceResult>;
605 ReadReferenceFileForTab(tabID: string, path: string): Promise<FilePreview>;
606 ReadReferenceFileSourceForTab(tabID: string, path: string): Promise<FilePreview>;
607 SanitizeMarkdownSVG(content: string): Promise<MarkdownSVGView>;
608 CreateWorkspaceBrowserPreviewForTab(tabID: string, rel: string): Promise<string>;
609 CreatePresentedBrowserPreviewForTab(tabID: string, toolCallID: string, path: string): Promise<string>;
610 OpenFileBrowserPreviewForTab?(tabID: string, request: FileBrowserPreviewRequest): Promise<FileBrowserPreviewResult>;
611 RevokeWorkspaceBrowserPreview(url: string): Promise<void>;
612 RevokeWorkspaceMediaPreview(url: string): Promise<void>;
613 ResolveMarkdownImageForTab(tabID: string, source: string): Promise<MarkdownImageView>;
614 WorkspaceRevisionForTab(tabID: string): Promise<{ revisions: WorkspaceRevisions; watchState: "active" | "degraded" | "unavailable" }>;
615 WorkspaceChanges(tabID: string): Promise<WorkspaceChangesView>;
616 WorkspaceChangeDetail(tabID: string, path: string): Promise<WorkspaceChangeDetailView>;
617 WorkspaceTurnChanges(tabID: string, sessionPath: string, turn: number, resultID: string): Promise<TurnChanges>;
618 WorkspaceTurnChangeDetail(tabID: string, sessionPath: string, turn: number, resultID: string, path: string): Promise<TurnFileChange | null>;
619 TurnCheckLog(tabID: string, sessionPath: string, toolID: string, resultID: string): Promise<{ output: string; truncated: boolean } | null>;
620 GitBranches(): Promise<string[]>;
621 GitCheckout(branch: string): Promise<void>;
622 GitCreateBranch(name: string): Promise<void>;
623 GitBranchesForTab(tabID: string, workspaceRoot: string): Promise<string[]>;
624 GitCheckoutForTab(tabID: string, workspaceRoot: string, branch: string): Promise<void>;
625 GitCreateBranchForTab(tabID: string, workspaceRoot: string, name: string): Promise<void>;
626 WorkspaceGitStatsForTab(tabID: string, workspaceRoot: string): Promise<WorkspaceChangesView>;
627 WorkspaceGitHistory(tabID: string, path: string): Promise<GitCommitView[]>;
628 WorkspaceGitCommitDetail(tabID: string, hash: string, path: string): Promise<GitCommitDetailView>;
629 OpenWorkspacePathForTab(tabID: string, rel: string): Promise<void>;
630 OpenPresentedPathForTab(tabID: string, toolCallID: string, path: string): Promise<void>;
631 OpenReferencePathForTab(tabID: string, path: string): Promise<void>;
632 ResolvePresentedPathForTab(tabID: string, toolCallID: string, path: string): Promise<string>;
633 ResolveReferencePathForTab(tabID: string, path: string): Promise<string>;
634 ResolveWorkspacePathForTab(tabID: string, rel: string): Promise<string>;
635 ExternalOpeners(): Promise<ExternalOpenersView>; ExternalOpenersForTab(tabID: string): Promise<ExternalOpenersView>;
636 SetPreferredExternalOpener(id: string): Promise<void>;
637 OpenWorkspaceInExternalOpenerForTab(tabID: string, id: string): Promise<void>; OpenLocalPathInExternalOpener(path: string, id: string): Promise<void>; SaveLocalPathAs(path: string): Promise<string>;
638 RevealWorkspacePathForTab(tabID: string, rel: string): Promise<void>;
639 RevealPresentedPathForTab(tabID: string, toolCallID: string, path: string): Promise<void>;
640 RevealReferencePathForTab(tabID: string, path: string): Promise<void>;
641 SaveWorkspacePathAsForTab(tabID: string, rel: string): Promise<string>;
642 SavePresentedPathAsForTab(tabID: string, toolCallID: string, path: string): Promise<string>;
643 SaveReferencePathAsForTab(tabID: string, path: string): Promise<string>;
644 SaveRemoteFileAs(hostID: string, remotePath: string): Promise<string>;
645 SaveRemotePresentedFileAs(tabID: string, hostID: string, toolCallID: string, remotePath: string): Promise<string>;
646 ResolveRemotePresentedPathForTab(tabID: string, hostID: string, toolCallID: string, remotePath: string): Promise<string>;
647 ResolveRemoteWorkspacePathForTab(tabID: string, hostID: string, toolCallID: string, remotePath: string): Promise<string>;
648 RevealPath(path: string): Promise<void>;
649 OpenLocalPath(path: string): Promise<void>;
650 SavePastedImage(dataUrl: string): Promise<string>;
651 SaveClipboardImage(): Promise<string>;
652 SavePastedFile(name: string, dataUrl: string): Promise<string>;
653 PickExportFile(defaultFilename: string, mimeType: string): Promise<string>;
654 ExportGoalDiagnostics(): Promise<string>;
655 ExportManualCreationDiagnostics(): Promise<string>;
656 SaveExportFile(path: string, payload: string, base64Encoded: boolean): Promise<void>;
657 SaveSessionMarkdownForTab(tabID: string, path: string, title: string): Promise<void>;
658 SaveExportImageFiles(path: string, payloads: string[]): Promise<void>;
659 AttachDropped(path: string): Promise<DroppedItem>;
660 AttachmentDataURL(path: string): Promise<string>;
661 Models(): Promise<ModelInfo[]>;
662 SetModel(name: string): Promise<void>;
663 ModelsForTab(tabID: string): Promise<ModelInfo[]>;
664 ModelsForDraft(draftID: string): Promise<ModelInfo[]>;
665 SetModelForTab(tabID: string, name: string): Promise<void>;
666 Effort(): Promise<EffortInfo>;
667 SetEffort(level: string): Promise<void>;
668 EffortForTab(tabID: string): Promise<EffortInfo>;
669 SetEffortForTab(tabID: string, level: string): Promise<void>;
670 // ReloadRuntime rebuilds the tab's agent runtime in place (tools, skills,
671 // commands, hooks, providers, MCP servers) via boot.Rebuild, keeping the
672 // session. Busy tabs queue one reload for when they go idle.
673 ReloadRuntime(tabID: string): Promise<void>;
674 Memory(): Promise<MemoryView>;
675 MemorySuggestions(): Promise<MemorySuggestionsView>;
676 AcceptMemorySuggestion(suggestion: MemorySuggestion): Promise<string>;
677 AcceptSkillSuggestion(suggestion: SkillSuggestion): Promise<string>;
678 MemoryForTab(tabID: string): Promise<MemoryView>;
679 MemoryRevisions(ref: string): Promise<MemoryFact[]>;
680 MemoryRevisionsForTab(tabID: string, ref: string): Promise<MemoryFact[]>;
681 RestoreMemoryRevision(ref: string, revision: number): Promise<MemoryFact>;
682 RestoreMemoryRevisionForTab(tabID: string, ref: string, revision: number): Promise<MemoryFact>;
683 MemorySuggestionsForTab(tabID: string): Promise<MemorySuggestionsView>;
684 AcceptMemorySuggestionForTab(tabID: string, suggestion: MemorySuggestion): Promise<string>;
685 AcceptSkillSuggestionForTab(tabID: string, suggestion: SkillSuggestion): Promise<string>;
686 Remember(scope: string, note: string): Promise<string>;
687 RememberForTab(tabID: string, scope: string, note: string): Promise<string>;
688 Forget(name: string): Promise<void>;
689 ForgetForTab(tabID: string, name: string): Promise<void>;
690 RestoreArchivedMemory(archivePath: string): Promise<MemoryFact>;
691 RestoreArchivedMemoryForTab(tabID: string, archivePath: string): Promise<MemoryFact>;
692 SaveDoc(path: string, body: string): Promise<string>;
693 SaveDocForTab(tabID: string, path: string, body: string): Promise<string>;
694 DesktopStartupSettings(): Promise<DesktopStartupSettingsView>;
695 HooksSettings(scope: string): Promise<HooksSettingsView>;
696 SaveHooksSettings(scope: string, hooks: HookConfigView[]): Promise<void>;
697 SaveHooksSettingsForRoot(scope: string, projectRoot: string, hooks: HookConfigView[]): Promise<void>;
698 TrustProjectHooks(): Promise<void>;
699 TrustProjectHooksForRoot(projectRoot: string): Promise<void>;
700 SetDefaultModel(ref: string): Promise<void>;
701 SetPlannerModel(ref: string): Promise<void>;
702 SetVisionModel(ref: string): Promise<void>;
703 SetWebSearchModel(ref: string): Promise<void>;
704 SetSubagentModel(ref: string): Promise<void>;
705 SetSubagentEffort(level: string): Promise<void>;
706 SetMaxSubagentDepth(depth: number): Promise<void>;
707 SetMaxSubagentConcurrency(n: number): Promise<void>;
708 SetMaxParallelWriters(n: number): Promise<void>;
709 SetAutoPlan(mode: string): Promise<void>;
710 SetDefaultToolApprovalMode(mode: string): Promise<void>;
711 SetDefaultAutoRecoveryCheckpoint(enabled: boolean): Promise<void>;
712 RenameProviderConnections(names: string[], displayName: string): Promise<void>;
713 SaveProvider(p: ProviderView): Promise<void>;
714 SetProviderWebSearch(names: string[], enabled: boolean): Promise<void>;
715 SaveProviderModelCatalogs(updates: ProviderModelCatalogUpdate[]): Promise<string[]>;
716 SaveProviderWithKey(p: ProviderView, key: string): Promise<string>;
717 AddOfficialProviderAccess(kind: string, key: string): Promise<string>;
718 UpgradeDeepSeekProviderAccess(name: string): Promise<string>;
719 AddProviderPresetAccess(id: string, key: string): Promise<string>;
720 ResetProviderPresetAccess(id: string): Promise<void>;
721 FetchProviderModels(p: ProviderView): Promise<string[]>;
722 FetchProviderModelCatalog(p: ProviderView): Promise<ProviderModelCapabilityView[]>;
723 FetchProviderModelCatalogDraft(p: ProviderView, key: string): Promise<ProviderModelCapabilityView[]>;
724 TestProviderModel(p: ProviderView, model: string, key: string): Promise<void>;
725 FetchAllProviderModelCatalogs(providers: ProviderView[]): Promise<Record<string, ProviderModelCapabilityView[]>>;
726 FetchAllProviderModels(providers: ProviderView[]): Promise<Record<string, string[]>>;
727 DeleteProvider(name: string): Promise<void>;
728 RemoveProviderAccess(name: string): Promise<void>;
729 RemoveProviderAccesses(names: string[]): Promise<void>;
730 SaveProviderKey(apiKeyEnv: string, value: string): Promise<string>;
731 SetConnectionKey(name: string, value: string): Promise<string>;
732 AddProviderConnectionWithOptions(presetID: string, sourceName: string, key: string, baseURL: string, kind: string): Promise<string>;
733 AddProviderConnectionWithURL(presetID: string, sourceName: string, key: string, baseURL: string): Promise<string>;
734 AddProviderConnection(presetID: string, sourceName: string, key: string): Promise<string>;
735 SetProviderKey(apiKeyEnv: string, value: string): Promise<string>;
736 ClearProviderKey(apiKeyEnv: string): Promise<void>;
737 SetPermissionMode(mode: string): Promise<void>;
738 AddPermissionRule(list: string, rule: string): Promise<void>;
739 RemovePermissionRule(list: string, rule: string): Promise<void>;
740 ReloadSettings(): Promise<void>;
741 SetShellPreference(prefer: string): Promise<void>;
742 InstallShellSupport(id: string): Promise<ShellInstallResult>;
743 CancelShellInstall(): Promise<void>;
744 SetSandbox(bash: string, network: boolean, workspaceRoot: string, allowWrite: string[], shell: string): Promise<void>;
745 SetNetwork(n: NetworkView): Promise<void>;
746 SetBotSettings(b: BotSettingsView): Promise<void>;
747 SetBotConnectionToolApprovalMode(connID: string, mode: string): Promise<void>;
748 SetBotDingtalkToolApprovalMode(mode: string): Promise<void>;
749 SetBotSecret(envName: string, value: string): Promise<void>;
750 ClearBotSecret(envName: string): Promise<void>;
751 StartBotConnectionInstall(provider: string, domain: string): Promise<BotInstallStartResult>;
752 PollBotConnectionInstall(installID: string): Promise<BotInstallPollResult>;
753 BotRuntimeStatus(): Promise<BotRuntimeStatusView>;
754 DiagnoseBotConnection(id: string): Promise<BotConnectionDiagnostic>;
755 TestBotConnection(id: string, target?: string): Promise<BotConnectionDiagnostic>;
756 TestDingtalkBot(): Promise<BotConnectionDiagnostic>;
757 SetCloseBehavior(mode: string): Promise<void>;
758 SetSessionExperience(mode: "standard" | "deep"): Promise<void>;
759 SetDisplayMode(mode: string): Promise<void>;
760 SetStatusBarStyle(style: string): Promise<void>;
761 SetStatusBarItems(items: string[]): Promise<void>; SetReasoningDisplayMode(mode: "hidden" | "summary" | "auto" | "expanded"): Promise<void>;
762 SetDesktopLanguage(lang: string): Promise<void>;
763 SetDesktopCurrency(currency: string): Promise<void>;
764 SetDesktopAppearance(theme: string, style: string): Promise<void>;
765 SetDesktopTerminalTheme(theme: string): Promise<void>;
766 ListThemePacks(): Promise<import("./themePack").ThemePackView[]>;
767 GetActiveThemePack(): Promise<import("./themePack").ThemeActiveView>;
768 GetThemeExperience(): Promise<import("./themeExperience").ThemeExperienceView>;
769 ActivateThemePack(id: string): Promise<void>;
770 ActivateBaseStyle(style: string): Promise<void>;
771 DisableThemePack(): Promise<void>;
772 RestoreGraphiteAppearance(): Promise<void>;
773 ResetThemePack(): Promise<void>;
774 SaveThemePack(input: import("./themePack").ThemeSaveInput): Promise<import("./themePack").ThemePackView>;
775 DeleteThemePack(id: string): Promise<void>;
776 CopyThemePack(sourceID: string, newID: string, newName: string): Promise<import("./themePack").ThemePackView>;
777 ImportThemePack(sourcePath: string, replace: boolean): Promise<import("./themePack").ThemeImportResult>;
778 ExportThemePack(id: string, destPath: string): Promise<string>;
779 PickThemeBackground(): Promise<string>;
780 SetDesktopLayoutStyle(style: string): Promise<void>;
781 SetDesktopZoomFactor(factor: number): Promise<void>;
782 GetDesktopZoomFactor(): Promise<number>;
783 RestartApplication(): Promise<void>;
784 ReportDesktopWebViewReady(): Promise<void>;
785 GetDesktopShellStatus(): Promise<DesktopShellStatusView>;
786 SetDesktopCheckUpdates(enabled: boolean): Promise<void>;
787 SetDesktopUpdateChannel(channel: string): Promise<void>;
788 SetDesktopTelemetry(enabled: boolean): Promise<void>;
789 SetDesktopMetrics(enabled: boolean): Promise<void>;
790 SetExpandThinking(on: boolean): Promise<void>;
791 SetDesktopConversationWidth(width: string): Promise<void>;
792 MigrateDesktopPreferences(language: string, theme: string, style: string): Promise<void>;
793 SetAgentParams(temperature: number, maxSteps: number, plannerMaxSteps: number, systemPrompt: string): Promise<void>;
794 SetCompactRatio(ratio: number): Promise<void>;
795 SetReasoningLanguage(lang: string): Promise<void>;
796 SetTrayLocale(locale: "en" | "zh" | "zh-TW"): Promise<void>;
797 // SetBypass is the legacy desktop name for YOLO/full-access tool auto-approval
798 // (ask questions and plan approvals still wait; deny rules still apply).
799 // Runtime-only.
800 SetBypass(on: boolean): Promise<void>;
801 Version(): Promise<string>;
802 CheckUpdate(channel: string): Promise<UpdateInfo | null>;
803 /** v1.20+ single-action update: download, verify, install, relaunch. */
804 ApplyUpdateRequest(channel: string, expectedVersion: string, requestId: string): Promise<void>;
805 /** Discard a stuck previous update transaction so the next install can proceed. */
806 AbandonPendingUpdate?(): Promise<void>;
807 OpenDownloadPage(): Promise<void>;
808 OpenUserConfigPath?(): Promise<void>;
809 ReloadUserConfig?(): Promise<{ configWarnings?: string[]; configWarningsRevision?: number; configPath?: string } | null>;
810 StorageSettings(): Promise<{ defaultWorkspace: string; statePath: string; cachePath: string; extensionsPath: string }>;
811 NeedsOnboarding(): Promise<boolean>;
812 ConnectKey(apiKey: string): Promise<string>;
813 // Crash overlay "Send report" (desktop/crash_app.go): scrubs user paths, attaches
814 // version/os/arch, POSTs to the collection endpoint. Only ever sent on user click.
815 ReportCrash(kind: string, detail: string): Promise<void>;
816 RecordUIPerf(signals: Record<string, string>): Promise<void>;
817 ListTabs(): Promise<TabMeta[]>;
818 OpenProjectTab(workspaceRoot: string, topicID: string): Promise<TabMeta>;
819 IsolatedWorktreeAvailability(workspaceRoot: string): Promise<DeliveryWorktreeAvailability>;
820 CreateIsolatedWorktree(workspaceRoot: string): Promise<DeliveryWorktreeOpenResult>;
821 InspectWorktreeMerge(tabID: string): Promise<WorktreeMergeInspection>;
822 GetWorktreeStatus(tabID: string): Promise<WorktreeMergeInspection>;
823 PrepareWorktreeMerge(tabID: string): Promise<WorktreeMergeInspection>;
824 MergeWorktreeBack(request: WorktreeMergeRequest): Promise<WorktreeMergeResult>;
825 RegisterNavigationIntent(token: string): Promise<void>;
826 CloseMergedWorktreeTab(request: CloseMergedWorktreeTabRequest): Promise<CloseMergedWorktreeTabResult>;
827 FinalizeWorktreeMerge(request: WorktreeCleanupRequest): Promise<WorktreeCleanupResult>;
828 // Deprecated one-version aliases kept bound for older desktop clients.
829 DeliveryWorktreeAvailability(workspaceRoot: string): Promise<DeliveryWorktreeAvailability>;
830 CreateDeliveryWorktree(workspaceRoot: string): Promise<DeliveryWorktreeOpenResult>;
831 SetAgentPreset(preset: string): Promise<void>;
832 SetAgentPresetForTab(tabID: string, preset: string): Promise<void>;
833 SetTokenMode(mode: string): Promise<void>;
834 SetTokenModeForTab(tabID: string, mode: string): Promise<void>;
835 OpenGlobalTab(topicID: string): Promise<TabMeta>;
836 OpenTopicSession(scope: string, workspaceRoot: string, topicID: string, sessionPath: string): Promise<TabMeta>;
837 EnsureBlankTab(scope: string, workspaceRoot: string): Promise<TabMeta>;
838 ActivateTopic(scope: string, workspaceRoot: string, topicID: string, sessionPath: string): Promise<TabMeta>;
839 // Two-phase ticketed topic activation (supersedes ActivateTopic for topic
840 // navigation): returns a ticket after the surface switch; completion lands
841 // on the "topic:activation" channel.
842 StartTopicActivation(req: TopicActivationRequest): Promise<TopicActivationTicket>;
843 EnsureBlankSurface(scope: string, workspaceRoot: string): Promise<TabMeta>;
844 SetActiveTab(tabID: string): Promise<void>;
845 ReorderTabs(tabIDs: string[]): Promise<void>;
846 CloseTab(tabID: string): Promise<void>;
847 TerminalWorkspaceForTab(tabID: string): Promise<TerminalWorkspaceView>;
848 TerminalOutputForTab(tabID: string, sessionID: string): Promise<string>;
849 CreateTerminalForTab(tabID: string, relativePath: string, shellID: string): Promise<TerminalSessionView>;
850 WriteTerminalForTab(tabID: string, sessionID: string, data: string): Promise<void>;
851 ResizeTerminalForTab(tabID: string, sessionID: string, cols: number, rows: number): Promise<void>;
852 CloseTerminalForTab(tabID: string, sessionID: string): Promise<void>;
853 RenameTerminalForTab(tabID: string, sessionID: string, title: string): Promise<void>;
854 ListProjectTree(): Promise<ProjectNode[]>;
855 RenameProject(workspaceRoot: string, title: string): Promise<void>;
856 SetProjectColor(workspaceRoot: string, color: string): Promise<void>;
857 SetProjectPinned(workspaceRoot: string, pinned: boolean): Promise<void>;
858 ReorderProjects(workspaceRoots: string[]): Promise<void>;
859 CreateTopic(scope: string, workspaceRoot: string, title: string): Promise<TopicMeta>;
860 RenameTopic(topicID: string, title: string): Promise<void>;
861 DeleteTopic(topicID: string): Promise<void>;
862 TrashTopic(topicID: string): Promise<void>;
863 InspectTopicRemoval(target: import("../generated/desktopContract.generated").TopicRemovalTarget): Promise<import("../generated/desktopContract.generated").TopicRemovalInspection>;
864 RemoveTopic(request: import("../generated/desktopContract.generated").TopicRemovalRequest): Promise<import("../generated/desktopContract.generated").TopicRemovalResult>;
865 SetTopicPinned(topicID: string, pinned: boolean): Promise<void>;
866 ContextPanel(tabID: string): Promise<ContextPanelInfo>;
867 // New native-feel bindings (added with the desktop native-feel plan).
868 ConfirmAction(req: NativeConfirmRequest): Promise<boolean>;
869 SaveWindowState(state: DesktopWindowState): Promise<void>;
870 // ── Remote (SSH) ──
871 RemoteHosts(): Promise<RemoteHostView[]>;
872 AddRemoteHost(input: RemoteHostInput): Promise<RemoteHostView>;
873 UpdateRemoteHost(id: string, input: RemoteHostInput): Promise<RemoteHostView>;
874 RemoveRemoteHost(id: string): Promise<void>;
875 ScanSSHConfig(): Promise<RemoteHostInput[]>;
876 ConnectRemoteHost(id: string): Promise<void>;
877 DisconnectRemoteHost(id: string): Promise<void>;
878 RemoteConnectionStatuses(): Promise<RemoteConnectionStatus[]>;
879 ConfirmRemoteHostKey(hostId: string, accept: boolean): Promise<void>;
880 ConfirmRemoteSecret(hostId: string, promptId: string, secret: string, accept: boolean): Promise<void>;
881 ListRemoteDir(hostId: string, path: string): Promise<RemoteDirEntry[]>;
882 ReadRemoteFile(hostId: string, path: string): Promise<RemoteFilePreview>;
883 WriteRemoteFile(hostId: string, path: string, body: string, expectMtimeUnix: number): Promise<RemoteWriteResult>;
884 MkdirRemote(hostId: string, path: string): Promise<void>;
885 RenameRemotePath(hostId: string, oldPath: string, newPath: string): Promise<void>;
886 DeleteRemotePath(hostId: string, path: string, recursive: boolean): Promise<void>;
887 RemoteForwards(hostId: string): Promise<RemoteForwardView[]>;
888 AddRemoteForward(hostId: string, input: RemoteForwardInput): Promise<RemoteForwardView>;
889 RemoveRemoteForward(hostId: string, forwardId: string): Promise<void>;
890 OpenRemoteWorkspace(hostId: string, workspace: string): Promise<void>;
891 PickRemoteIdentityFile(): Promise<string>;
892 CheckRemotePlatform(hostId: string): Promise<void>;
893 StopRemoteServer(hostId: string, workspace: string): Promise<void>;
894 RemoteServerStatus(hostId: string, workspace: string): Promise<RemoteServerView>;
895 RemoteServerLogs(hostId: string, workspace: string, tailLines: number): Promise<string>;
896 RemoteLastWorkspace(hostId: string): Promise<string>;
897 ScanRemoteLegacyWorkbenchData(): Promise<RemoteLegacyWorkbenchData>;
898 CleanRemoteLegacyWorkbenchData(target: "mirrors" | "trust"): Promise<void>;
899 }
900 // Compile-time drift check. Exclude<A, B> extracts keys in A that are missing
901 // from B. If that set is non-empty, AssertNever<non-never> fails with
902 // "Type 'X' does not satisfy the constraint 'never'".
903 // _CheckGenToApp errors mean a generated Go method has no TS counterpart.
904 // This compares method *names* only: the generated contract uses positional
905 // arg0/arg1 parameters and its own DTO interfaces, so full signature
906 // assignability would false-positive. Parameter drift is caught at the call
907 // sites by tsc when components invoke app.<method>(...).
908 type AssertNever<T extends never> = T;
909 export type _CheckGenToApp = AssertNever<Exclude<DesktopCommandName, keyof AppBindings>>;
910 // Must match desktop/app.go's eventChannel constant.
911 const EVENT_CHANNEL = "agent:event";
912
913 function hostEvents(name: string, cb: (...args: unknown[]) => void): (() => void) | null {
914 const host = desktopHost();
915 return host.kind === "none" ? null : host.events.on(name, cb);
916 }
917 type LazyMockAttachmentCommand = keyof AttachmentBindings
918 | "SavePastedImage"
919 | "SavePastedImageForComposerTarget"
920 | "SaveClipboardImage"
921 | "SaveClipboardImageForComposerTarget"
922 | "SavePastedFile"
923 | "SavePastedFileForComposerTarget"
924 | "AttachDropped"
925 | "AttachDroppedForComposerTarget"
926 | "AttachmentDataURL"
927 | "AttachmentDataURLForComposerTarget";
928 type MockAppBindings = Omit<AppBindings, LazyMockAttachmentCommand>;
929
930 let mockSingleton: AppBindings | null = null;
931 function getMock(): AppBindings {
932 if (!mockSingleton) mockSingleton = makeMockApp() as AppBindings;
933 return mockSingleton;
934 }
935
936 // onEvent subscribes to the agent's typed event stream; returns an unsubscribe.
937 export function onEvent(cb: (e: WireEvent) => void): () => void {
938 return hostEvents(EVENT_CHANNEL, (payload) => cb(payload as WireEvent)) ?? mockSubscribe(cb);
939 }
940
941 export interface TerminalOutputEvent {
942 id: string;
943 data: string;
944 }
945
946 export interface TerminalExitEvent {
947 id: string;
948 exitCode: number;
949 removed?: boolean;
950 }
951
952 function terminalEventPayload<T>(payload: unknown): T | null {
953 if (!payload || typeof payload !== "object") return null;
954 return payload as T;
955 }
956
957 export function onTerminalOutput(cb: (event: TerminalOutputEvent) => void): () => void {
958 const off = hostEvents("terminal:output", (payload) => {
959 const event = terminalEventPayload<TerminalOutputEvent>(payload);
960 if (event?.id && typeof event.data === "string") cb(event);
961 });
962 if (off) return off;
963 mockTerminalOutputListeners.add(cb);
964 return () => mockTerminalOutputListeners.delete(cb);
965 }
966
967 export function onTerminalExit(cb: (event: TerminalExitEvent) => void): () => void {
968 const off = hostEvents("terminal:exit", (payload) => {
969 const event = terminalEventPayload<TerminalExitEvent>(payload);
970 if (event?.id && typeof event.exitCode === "number") cb(event);
971 });
972 if (off) return off;
973 mockTerminalExitListeners.add(cb);
974 return () => mockTerminalExitListeners.delete(cb);
975 }
976
977 const mockTerminalOutputListeners = new Set<(event: TerminalOutputEvent) => void>();
978 const mockTerminalExitListeners = new Set<(event: TerminalExitEvent) => void>();
979
980 export function __emitMockTerminalOutput(event: TerminalOutputEvent): void {
981 mockTerminalOutputListeners.forEach((listener) => listener(event));
982 }
983
984 export function __emitMockTerminalExit(event: TerminalExitEvent): void {
985 mockTerminalExitListeners.forEach((listener) => listener(event));
986 }
987
988 // onUpdaterProgress subscribes to the auto-updater's progress events (a separate
989 // channel from the agent stream); returns an unsubscribe. Must match the event
990 // name emitted in desktop/updater_app.go.
991 export function onUpdaterProgress(cb: (p: UpdateProgress) => void): () => void {
992 const off = hostEvents("updater:progress", (p) => cb(p as UpdateProgress));
993 if (off) return off;
994 updaterListeners.add(cb);
995 return () => {
996 updaterListeners.delete(cb);
997 };
998 }
999
1000 // onFilesDropped subscribes to native OS file drops landing on the composer's
1001 // drop target; the callback gets the dropped files' absolute paths. No-op in
1002 // the browser dev mock.
1003 export function onFilesDropped(cb: (paths: string[]) => void): () => void {
1004 return desktopHost().native.onFilesDropped(cb);
1005 }
1006
1007 // onReady subscribes to the agent:ready event fired when boot.Build completes.
1008 // The frontend re-fetches Meta/Context/History when this lands.
1009 // onRuntimeRebuilt fires when a tab's controller is replaced in place
1010 // (model/effort/token-mode switch, clear-while-running). The rebuilt
1011 // controller restarts prompt ids, so per-tab id-keyed state must reset.
1012 export function onRuntimeRebuilt(cb: (tabId?: string, runtimeEpoch?: string) => void): () => void {
1013 return hostEvents("runtime:rebuilt", (tabId?: unknown, runtimeEpoch?: unknown) =>
1014 cb(
1015 typeof tabId === "string" ? tabId : undefined,
1016 typeof runtimeEpoch === "string" ? runtimeEpoch : undefined,
1017 )
1018 ) ?? (() => {});
1019 }
1020
1021 export function onReady(cb: (tabId?: string) => void): () => void {
1022 const off = hostEvents("agent:ready", (tabId?: unknown) => cb(typeof tabId === "string" ? tabId : undefined));
1023 if (off) return off;
1024 // The browser mock has no native event bridge, but SessionRef navigation
1025 // still needs the same reload semantics as the desktop host.
1026 mockReadyListeners.add(cb);
1027 cb();
1028 return () => mockReadyListeners.delete(cb);
1029 }
1030
1031 export function onProjectTreeChanged(cb: () => void): () => void {
1032 return hostEvents("project-tree:changed", (payload?: unknown) => (payload as { reason?: unknown } | undefined)?.reason !== "runtime" && (payload as { reason?: unknown } | undefined)?.reason !== "catalog-v2" && cb()) ?? subscribeMockProjectTreeChanged(cb);
1033 }
1034
1035 export function onLegacyEmptySessionCleanupChanged(cb: (status: LegacyEmptySessionCleanupStatus) => void): () => void {
1036 return hostEvents("legacy-empty-session-cleanup:changed", (payload?: unknown) => {
1037 if (payload && typeof payload === "object") cb(payload as LegacyEmptySessionCleanupStatus);
1038 }) ?? (() => {});
1039 }
1040
1041 // onTopicActivation subscribes to the "topic:activation" channel carrying the
1042 // lifecycle of ticketed StartTopicActivation requests (starting/ready/failed/
1043 // cancelled). Returns an unsubscribe.
1044 export function onTopicActivation(cb: (event: TopicActivationEvent) => void): () => void {
1045 const off = hostEvents("topic:activation", (payload?: unknown) => {
1046 if (payload && typeof payload === "object") cb(payload as TopicActivationEvent);
1047 });
1048 if (off) return off;
1049 mockTopicActivationListeners.add(cb);
1050 return () => mockTopicActivationListeners.delete(cb);
1051 }
1052
1053 // onTabMeta subscribes to the "tab:meta" channel: a full refreshed Meta pushed
1054 // after the backend recomputes the expensive MetaForTab fields (git branch,
1055 // image-input capability) in the background.
1056 export function onTabMeta(cb: (event: TabMetaRefreshEvent) => void): () => void {
1057 const off = hostEvents("tab:meta", (payload?: unknown) => {
1058 if (payload && typeof payload === "object") cb(payload as TabMetaRefreshEvent);
1059 });
1060 if (off) return off;
1061 mockTabMetaListeners.add(cb);
1062 return () => mockTabMetaListeners.delete(cb);
1063 }
1064
1065 const mockTopicActivationListeners = new Set<(event: TopicActivationEvent) => void>();
1066 const mockTabMetaListeners = new Set<(event: TabMetaRefreshEvent) => void>();
1067 const mockReadyListeners = new Set<(tabId?: string) => void>();
1068
1069 function emitMockReady(tabId?: string): void {
1070 mockReadyListeners.forEach((listener) => listener(tabId));
1071 }
1072
1073 export function __emitMockTopicActivation(event: TopicActivationEvent): void {
1074 mockTopicActivationListeners.forEach((listener) => listener(event));
1075 }
1076
1077 export function __emitMockTabMeta(event: TabMetaRefreshEvent): void {
1078 mockTabMetaListeners.forEach((listener) => listener(event));
1079 }
1080
1081 export function onSessionRecovered(cb: (payload: SessionRecoveryEvent) => void): () => void {
1082 return hostEvents("session:recovered", (payload?: unknown) => cb((payload ?? {}) as SessionRecoveryEvent)) ?? (() => {});
1083 }
1084
1085 export function onSessionActiveVersionChanged(cb: (payload: SessionRecoveryEvent) => void): () => void {
1086 return hostEvents("session:active-version-changed", (payload?: unknown) => cb((payload ?? {}) as SessionRecoveryEvent)) ?? (() => {});
1087 }
1088
1089 export function onSessionRecoveryFailed(cb: (payload: SessionRecoveryFailedEvent) => void): () => void {
1090 return hostEvents("session:recovery-failed", (payload?: unknown) => cb((payload ?? {}) as SessionRecoveryFailedEvent)) ?? (() => {});
1091 }
1092
1093 export function onRemoteStatus(cb: (s: RemoteConnectionStatus) => void): () => void {
1094 return hostEvents("remote:status", (payload?: unknown) => cb((payload ?? {}) as RemoteConnectionStatus))
1095 ?? registerMockRemoteListener("status", cb as (v: unknown) => void);
1096 }
1097
1098 export function onRemoteForwards(cb: (e: RemoteForwardsEvent) => void): () => void {
1099 return hostEvents("remote:forwards", (payload?: unknown) => cb((payload ?? {}) as RemoteForwardsEvent))
1100 ?? registerMockRemoteListener("forwards", cb as (v: unknown) => void);
1101 }
1102
1103 export function onRemoteServer(cb: (s: RemoteServerView) => void): () => void {
1104 return hostEvents("remote:server", (payload?: unknown) => cb((payload ?? {}) as RemoteServerView))
1105 ?? registerMockRemoteListener("server", cb as (v: unknown) => void);
1106 }
1107
1108 // Mock event fan-out so browser-dev and tsx tests can drive remote:* events
1109 // without a shell runtime.
1110 type MockRemoteChannel = "status" | "forwards" | "server";
1111 const mockRemoteListeners: Record<MockRemoteChannel, Set<(v: unknown) => void>> = {
1112 status: new Set(),
1113 forwards: new Set(),
1114 server: new Set(),
1115 };
1116 function registerMockRemoteListener(ch: MockRemoteChannel, cb: (v: unknown) => void): () => void {
1117 mockRemoteListeners[ch].add(cb);
1118 return () => mockRemoteListeners[ch].delete(cb);
1119 }
1120 export function __emitMockRemote(ch: MockRemoteChannel, payload: unknown): void {
1121 for (const cb of mockRemoteListeners[ch]) cb(payload);
1122 }
1123
1124 // app proxies each call to the live binding (or the dev mock only when truly
1125 // outside the shell), resolving the host at call time so a shell that attaches
1126 // late is picked up transparently.
1127 function bridgeBreadcrumb(method: string): string {
1128 if (method === "ReportCrash" || method === "RecordUIPerf") return "";
1129 if (/^(Submit|SubmitDisplay|RunShell|Steer|Cancel|Approve|AnswerQuestion|ReplayPendingPrompts)/.test(method))
1130 return `turn ${method}`;
1131 if (/^(SetModel|SetEffort|SetDefaultModel|SetPlannerModel|SetVisionModel|SetWebSearchModel|SetSubagentModel|SetSubagentEffort|SetMaxSubagentDepth|SetMaxSubagentConcurrency|SetMaxParallelWriters)/.test(method))
1132 return `model ${method}`;
1133 if (/^(SetDesktop|SetCloseBehavior|SetDisplayMode|SetStatusBar|SetReasoningDisplayMode|SetExpandThinking|SetAutoPlan|SetDefaultToolApprovalMode|SetCompactRatio|SetReasoningLanguage)/.test(method))
1134 return `settings ${method}`;
1135 if (/^(SetConnectionKey|AddProviderConnection|RenameProviderConnections|SaveProvider|SetProviderWebSearch|SaveProviderModelCatalogs|AddOfficialProviderAccess|UpgradeDeepSeekProviderAccess|AddProviderPresetAccess|ResetProviderPresetAccess|RemoveProviderAccess|RemoveProviderAccesses|DeleteProvider|SaveProviderKey|SetProviderKey|ClearProviderKey|TestProviderModel|FetchProviderModelCatalog|FetchAllProviderModelCatalogs|FetchProviderModels|FetchAllProviderModels|ConnectKey)/.test(method))
1136 return `provider ${method}`;
1137 if (/^(CheckUpdate|ApplyUpdateRequest|OpenDownloadPage|OpenUserConfigPath|ReloadUserConfig)/.test(method)) return `update ${method}`;
1138 if (/^(AddMCPServer|InstallMCPServer|UpdateMCPServer|RemoveMCPServer|AuthorizeAndConnectMCPServer|AuthenticateMCPServer|ReconnectMCPServer|ClearMCPServerAuthentication|SetMCPServer)/.test(method))
1139 return `mcp ${method}`;
1140 if (/^(AddSkillPath|RemoveSkillPath|SetSkillPathEnabled|RefreshSkills|SetSkillEnabled|SetSkillImplicitInvocation|AcceptSkillSuggestion|AvailableSubagentTools|CreateSubagentProfile|UpdateSubagentProfile|DeleteSubagentProfile|SetSubagentProfileModel|SetSubagentProfileEffort|TrySubagentProfile|CancelTrySubagentProfile)/.test(method))
1141 return `skill ${method}`;
1142 if (/^(MinimiseMainWindow|ToggleMaximiseMainWindow|IsMainWindowMaximised|CloseMainWindow)$/.test(method)) return `window ${method}`;
1143 if (/^(OpenProjectTab|OpenGlobalTab|OpenTopicSession|EnsureBlankTab|ActivateTopic|StartTopicActivation|EnsureBlankSurface|SetActiveTab|CloseTab|RegisterNavigationIntent|CloseMergedWorktreeTab|ReorderTabs|CreateTopic|RenameTopic|DeleteTopic|TrashTopic|RenameProject|RemoveWorkspace|SwitchWorkspace|PickWorkspace|IsolatedWorktreeAvailability|CreateIsolatedWorktree|InspectWorktreeMerge|GetWorktreeStatus|PrepareWorktreeMerge|ReconcileRecoveryVersions|MergeWorktreeBack|FinalizeWorktreeMerge|DeliveryWorktreeAvailability|CreateDeliveryWorktree)/.test(method))
1144 return `nav ${method}`;
1145 return "";
1146 }
1147
1148 function elapsedMs(startedAt: number): number {
1149 const now = typeof performance !== "undefined" ? performance.now() : Date.now();
1150 return Math.max(0, Math.round(now - startedAt));
1151 }
1152
1153 // The draft owner registers receipts when loaded; purge needs no eager owner.
1154 export const sessionPurgeHandlers: Record<string, ((args: unknown[], result: unknown) => void) | undefined> = Object.create(null);
1155 export const app: AppBindings = new Proxy({} as AppBindings, {
1156 get(_t, prop) {
1157 const host = desktopHost().app, target = host ?? getMock();
1158 let v = (target as unknown as Record<string, unknown>)[String(prop)];
1159 // Inbox commands are optional. A synthesized attachment fallback would
1160 // make ordinary browser mocks claim support for absent queue methods.
1161 if (!host && v === undefined && typeof prop === "string" &&
1162 !prop.includes("Inbox")) v = (...args: unknown[]) => import("./attachmentBindings").then(
1163 module => module.callMockAttachment(target, prop as keyof AttachmentBindings, args));
1164 if (typeof v !== "function") return v;
1165 return (...args: unknown[]) => {
1166 const method = String(prop), crumb = bridgeBreadcrumb(method);
1167 const startedAt = crumb ? (typeof performance !== "undefined" ? performance.now() : Date.now()) : 0;
1168 if (crumb) addBreadcrumb("bridge", crumb);
1169 try {
1170 const result = maybeShare(method, args, () => (v as (...a: unknown[]) => unknown).apply(target, args));
1171 if (result && typeof (result as Promise<unknown>).then === "function") {
1172 return (result as Promise<unknown>).then(
1173 (value) => {
1174 sessionPurgeHandlers[method]?.(args, value);
1175 if (crumb) addBreadcrumb("bridge", `${crumb} done ms=${elapsedMs(startedAt)}`);
1176 return value;
1177 },
1178 (err) => {
1179 if (crumb) addBreadcrumb("bridge.error", `${method} ms=${elapsedMs(startedAt)}`);
1180 throw err;
1181 },
1182 );
1183 }
1184 if (crumb) addBreadcrumb("bridge", `${crumb} done ms=${elapsedMs(startedAt)}`);
1185 return result;
1186 } catch (err) {
1187 if (crumb) addBreadcrumb("bridge.error", `${method} ms=${elapsedMs(startedAt)}`);
1188 throw err;
1189 }
1190 };
1191 },
1192 });
1193
1194 // openExternal opens a URL in the system browser (so links in rendered markdown
1195 // don't navigate the webview away from the app). Falls back to window.open in the
1196 // browser dev mock.
1197 export function openExternal(url: string): void {
1198 desktopHost().native.openExternal(url);
1199 }
1200
1201 // --- browser dev mock --------------------------------------------------------
1202
1203 const listeners = new Set<(e: WireEvent) => void>();
1204 let mockScopedTabId: string | undefined;
1205 let mockPendingTopicActivation: { requestId: string; tabId: string } | undefined;
1206 let mockTopicActivationCounter = 0;
1207
1208 function mockSubscribe(cb: (e: WireEvent) => void): () => void {
1209 listeners.add(cb);
1210 return () => {
1211 listeners.delete(cb);
1212 };
1213 }
1214
1215 function emit(e: WireEvent) {
1216 const event = mockScopedTabId && !e.tabId ? { ...e, tabId: mockScopedTabId } : e;
1217 publishMockTranscriptEvent(event);
1218 listeners.forEach((l) => l(event));
1219 }
1220
1221 export function mockToolApprovalModeAfterModeChange(current: string | undefined, nextMode: Mode): ToolApprovalMode {
1222 if (modeHasAutoApproveTools(nextMode)) return "workspace-write";
1223 return normalizeToolApprovalMode(current);
1224 }
1225
1226 async function withMockTabScope<T>(tabId: string, fn: () => Promise<T>): Promise<T> {
1227 const previous = mockScopedTabId;
1228 mockScopedTabId = tabId || previous;
1229 try {
1230 return await fn();
1231 } finally {
1232 mockScopedTabId = previous;
1233 }
1234 }
1235
1236 // Updater progress has its own listener set so the browser dev mock can stream a
1237 // fake download/install flow through onUpdaterProgress.
1238 const updaterListeners = new Set<(p: UpdateProgress) => void>();
1239
1240 function emitUpdater(p: UpdateProgress) {
1241 updaterListeners.forEach((l) => l(p));
1242 }
1243
1244 // Test seam for the browser-dev updater state machine. The desktop shell
1245 // receives the same payloads through the host event stream.
1246 export function __emitMockUpdater(p: UpdateProgress): void {
1247 emitUpdater(p);
1248 }
1249
1250 function delay(ms: number): Promise<void> {
1251 return new Promise((r) => setTimeout(r, ms));
1252 }
1253
1254 function baseName(path: string): string {
1255 return path.replace(/[/\\]+$/, "").split(/[/\\]/).filter(Boolean).pop() ?? path;
1256 }
1257
1258 function browserPlatformOverride(): "darwin" | "windows" | "linux" | "" {
1259 if (typeof window === "undefined" || desktopHost().kind !== "none") return "";
1260 const value = new URLSearchParams(window.location.search).get("platform");
1261 return value === "darwin" || value === "windows" || value === "linux" ? value : "";
1262 }
1263
1264 function browserPreviewBashSandboxMode(): "enforce" | "off" {
1265 return browserPlatformOverride() === "windows" ? "off" : "enforce";
1266 }
1267
1268 function browserPreviewEffectiveShell(prefer = "auto"): "bash" | "git-bash" | "powershell" | "pwsh" {
1269 const normalized = prefer.trim().toLowerCase();
1270 if (normalized === "powershell" || normalized === "pwsh") return normalized;
1271 return browserPlatformOverride() === "windows" ? (normalized === "bash" ? "git-bash" : "pwsh") : "bash";
1272 }
1273
1274 function mockScenario(): "demo" | "fresh" | "running" | "guidance" | "recovery" | "sandbox_escape" | "notice" | "deepseek_upgrade" | "bench" {
1275 if (typeof window === "undefined") return "demo";
1276 const value = new URLSearchParams(window.location.search).get("mock")?.trim().toLowerCase();
1277 if (value === "fresh" || value === "empty" || value === "first-run") return "fresh";
1278 if (typeof import.meta.env !== "undefined" && import.meta.env.DEV && (value === "recovery" || value === "inbox-recovery")) return "recovery"; if (value === "guidance" || value === "guide" || value === "steer") return "guidance";
1279 if (value === "running" || value === "busy" || value === "streaming") return "running";
1280 if (value === "sandbox_escape" || value === "sandbox-escape" || value === "sandboxescape") return "sandbox_escape";
1281 if (value === "notice" || value === "notices" || value === "notice-preview") return "notice";
1282 if (value === "deepseek_upgrade" || value === "deepseek-upgrade") return "deepseek_upgrade";
1283 if (value === "bench" || value === "benchmark" || value === "perf") return "bench";
1284 return "demo";
1285 }
1286
1287 const mockProviderPresetTemplates: MockProviderPresetTemplate[] = [
1288 mockBundlePreset(
1289 "opencode-go-recommended",
1290 "OpenCode Go (Recommended)",
1291 "One key, three safe routes: Chat, Anthropic Messages, and Responses. Defaults use a low-cost effort and a 32K output cap.",
1292 "OPENCODE_GO_API_KEY",
1293 [
1294 mockProviderTemplate({ name: "opencode-go", kind: "openai", baseUrl: "https://opencode.ai/zen/go/v1", models: mockOpenCodeGoModels, visionModels: ["kimi-k3"], default: "glm-5.3", apiKeyEnv: "OPENCODE_GO_API_KEY", contextWindow: 128000, modelOverrides: [{ model: "glm-5.3", reasoningProtocol: "openai", supportedEfforts: ["low", "high", "max"], defaultEffort: "low", maxOutputTokens: 32768 }, { model: "kimi-k3", reasoningProtocol: "openai", supportedEfforts: ["high", "max"], defaultEffort: "max", contextWindow: 1048576, maxOutputTokens: 32768 }] }),
1295 mockProviderTemplate({ name: "opencode-go-anthropic", kind: "anthropic", baseUrl: "https://opencode.ai/zen/go", models: ["qwen3.8-max", "qwen3.7-plus", "qwen3.7-max", "qwen3.6-plus", "minimax-m3", "minimax-m2.7", "minimax-m2.5"], visionModels: ["qwen3.8-max", "qwen3.7-plus", "qwen3.6-plus"], default: "qwen3.7-plus", apiKeyEnv: "OPENCODE_GO_API_KEY", thinking: "adaptive", contextWindow: 262144 }),
1296 mockProviderTemplate({ name: "opencode-go-responses", kind: "responses", baseUrl: "https://opencode.ai/zen/go/v1", models: ["grok-4.5", "gpt-5.6-luna", "muse-spark-1.2-contributor"], visionModels: ["grok-4.5", "gpt-5.6-luna", "muse-spark-1.2-contributor"], default: "grok-4.5", apiKeyEnv: "OPENCODE_GO_API_KEY", contextWindow: 500000, supportedEfforts: ["low", "medium", "high"], defaultEffort: "low" }),
1297 ],
1298 { recommended: true, billingMode: "subscription_equivalent", displayGroup: "opencode", displaySection: "go", displayTier: "primary", routeKind: "bundle", displayOrder: 0 },
1299 ),
1300 mockPreset("deepseek-responses", "DeepSeek Official Responses API", "Official stateless DeepSeek Responses API for Flash and Pro with server-side web search.", "DEEPSEEK_API_KEY", mockProviderTemplate({ name: "deepseek-responses", kind: "responses", baseUrl: "https://api.deepseek.com", models: ["deepseek-flash", "deepseek-v4-pro"], default: "deepseek-flash", apiKeyEnv: "DEEPSEEK_API_KEY", balanceUrl: "https://api.deepseek.com/user/balance", webSearch: true, serverWebSearchCapability: true, contextWindow: 1000000, modelOverrides: [{ model: "deepseek-flash", reasoningProtocol: "", supportedEfforts: ["disabled", "low", "high", "max"], defaultEffort: "high" }, { model: "deepseek-v4-pro", reasoningProtocol: "", supportedEfforts: ["disabled", "high", "max"], defaultEffort: "high" }] })),
1301 mockPreset("longcat-openai", "LongCat OpenAI", "LongCat Platform OpenAI-compatible endpoint for LongCat-2.0.", "LONGCAT_API_KEY", mockProviderTemplate({ name: "longcat-openai", kind: "openai", baseUrl: "https://api.longcat.chat/openai/v1", modelsUrl: "https://api.longcat.chat/openai/v1/models", models: mockLongCatModels, default: "LongCat-2.0", apiKeyEnv: "LONGCAT_API_KEY", contextWindow: 131072, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1302 mockPreset("longcat-anthropic", "LongCat Anthropic", "LongCat Platform Anthropic-compatible Messages endpoint for LongCat-2.0.", "LONGCAT_API_KEY", mockProviderTemplate({ name: "longcat-anthropic", kind: "anthropic", baseUrl: "https://api.longcat.chat/anthropic", modelsUrl: "https://api.longcat.chat/anthropic/v1/models", models: mockLongCatModels, default: "LongCat-2.0", apiKeyEnv: "LONGCAT_API_KEY", authHeader: true, contextWindow: 131072, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1303 mockPreset("token-rhythm", "Token Rhythm", "Token Rhythm (基元律动) multi-model OpenAI-compatible gateway.", "TOKEN_RHYTHM_API_KEY", mockProviderTemplate({ name: "token-rhythm", kind: "openai", baseUrl: "https://tokenrhythm.studio/v1", modelsUrl: "https://tokenrhythm.studio/v1/models", models: mockTokenRhythmModels, visionModels: ["kimi-k2.5", "kimi-k2.6", "kimi-k2.7-code"], default: "deepseek-v4-flash", apiKeyEnv: "TOKEN_RHYTHM_API_KEY", contextWindow: 1000000, modelOverrides: mockTokenRhythmModelOverrides })),
1304 mockPreset("kimi-cn", "Kimi CN API", "Moonshot Kimi China OpenAI-compatible API.", "KIMI_API_KEY", mockProviderTemplate({ name: "kimi-cn", kind: "openai", baseUrl: "https://api.moonshot.cn/v1", models: mockKimiAPIModels, visionModels: mockKimiAPIModels, default: "kimi-k2.7-code", apiKeyEnv: "KIMI_API_KEY", balanceUrl: "https://api.moonshot.cn/v1/users/me/balance", contextWindow: 262144, reasoningProtocol: "none", modelOverrides: [{ model: "kimi-k3", reasoningProtocol: "openai", supportedEfforts: ["low", "high", "max"], defaultEffort: "max", contextWindow: 1048576 }] })),
1305 mockPreset("kimi-global", "Kimi Global API", "Moonshot Kimi international OpenAI-compatible API.", "MOONSHOT_API_KEY", mockProviderTemplate({ name: "kimi-global", kind: "openai", baseUrl: "https://api.moonshot.ai/v1", models: mockKimiAPIModels, visionModels: mockKimiAPIModels, default: "kimi-k2.7-code", apiKeyEnv: "MOONSHOT_API_KEY", balanceUrl: "https://api.moonshot.ai/v1/users/me/balance", contextWindow: 262144, reasoningProtocol: "none", modelOverrides: [{ model: "kimi-k3", reasoningProtocol: "openai", supportedEfforts: ["low", "high", "max"], defaultEffort: "max", contextWindow: 1048576 }] })),
1306 mockPreset("kimi-coding-plan", "Kimi Coding Plan", "Kimi Coding Plan via its dedicated Anthropic-compatible endpoint.", "KIMI_CODING_API_KEY", mockProviderTemplate({ name: "kimi-coding-plan", kind: "anthropic", baseUrl: "https://api.kimi.com/coding/", models: ["kimi-for-coding"], visionModels: ["kimi-for-coding"], default: "kimi-for-coding", apiKeyEnv: "KIMI_CODING_API_KEY", headers: { "User-Agent": "claude-code/0.1.0" }, thinking: "adaptive", contextWindow: 262144 })),
1307 mockPreset("mimo-api", "MiMo API", "Xiaomi MiMo direct API with text and vision-capable models.", "MIMO_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-api", kind: "openai", baseUrl: "https://api.xiaomimimo.com/v1", apiKeyEnv: "MIMO_API_KEY" })),
1308 mockPreset("mimo-anthropic", "MiMo Anthropic", "Xiaomi MiMo direct Anthropic-compatible endpoint.", "MIMO_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-anthropic", kind: "anthropic", baseUrl: "https://api.xiaomimimo.com/anthropic", apiKeyEnv: "MIMO_API_KEY", thinking: "adaptive" })),
1309 mockPreset("mimo-token-plan-cn", "MiMo Token Plan CN", "Xiaomi MiMo token-plan China endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-cn", kind: "openai", baseUrl: "https://token-plan-cn.xiaomimimo.com/v1", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY" })),
1310 mockPreset("mimo-token-plan-cn-anthropic", "MiMo Token Plan CN Anthropic", "Xiaomi MiMo token-plan China Anthropic-compatible endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-cn-anthropic", kind: "anthropic", baseUrl: "https://token-plan-cn.xiaomimimo.com/anthropic", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY", thinking: "adaptive" })),
1311 mockPreset("mimo-token-plan-sgp", "MiMo Token Plan SGP", "Xiaomi MiMo token-plan Singapore endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-sgp", kind: "openai", baseUrl: "https://token-plan-sgp.xiaomimimo.com/v1", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY" })),
1312 mockPreset("mimo-token-plan-sgp-anthropic", "MiMo Token Plan SGP Anthropic", "Xiaomi MiMo token-plan Singapore Anthropic-compatible endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-sgp-anthropic", kind: "anthropic", baseUrl: "https://token-plan-sgp.xiaomimimo.com/anthropic", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY", thinking: "adaptive" })),
1313 mockPreset("mimo-token-plan-ams", "MiMo Token Plan AMS", "Xiaomi MiMo token-plan Amsterdam endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-ams", kind: "openai", baseUrl: "https://token-plan-ams.xiaomimimo.com/v1", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY" })),
1314 mockPreset("mimo-token-plan-ams-anthropic", "MiMo Token Plan AMS Anthropic", "Xiaomi MiMo token-plan Amsterdam Anthropic-compatible endpoint.", "MIMO_TOKEN_PLAN_API_KEY", mockProviderTemplate({ ...mockMiMoDefaults, name: "mimo-token-plan-ams-anthropic", kind: "anthropic", baseUrl: "https://token-plan-ams.xiaomimimo.com/anthropic", apiKeyEnv: "MIMO_TOKEN_PLAN_API_KEY", thinking: "adaptive" })),
1315 mockPreset("minimax-cn-api", "MiniMax CN API", "MiniMax China OpenAI-compatible M-series API endpoint.", "MINIMAX_API_KEY", mockProviderTemplate({ name: "minimax-cn-api", kind: "openai", baseUrl: "https://api.minimaxi.com/v1", models: mockMiniMaxModels, visionModels: ["MiniMax-M3"], default: "MiniMax-M3", apiKeyEnv: "MINIMAX_API_KEY", extraBody: { reasoning_split: true }, contextWindow: 1048576, thinking: "adaptive", supportedEfforts: ["disabled", "adaptive"], defaultEffort: "adaptive" })),
1316 mockPreset("minimax-global-api", "MiniMax Global API", "MiniMax international OpenAI-compatible M-series API endpoint.", "MINIMAX_API_KEY", mockProviderTemplate({ name: "minimax-global-api", kind: "openai", baseUrl: "https://api.minimax.io/v1", models: mockMiniMaxModels, visionModels: ["MiniMax-M3"], default: "MiniMax-M3", apiKeyEnv: "MINIMAX_API_KEY", extraBody: { reasoning_split: true }, contextWindow: 1048576, thinking: "adaptive", supportedEfforts: ["disabled", "adaptive"], defaultEffort: "adaptive" })),
1317 mockPreset("minimax-cn-anthropic", "MiniMax CN Anthropic", "MiniMax China Anthropic-compatible M-series endpoint.", "MINIMAX_PLAN_API_KEY", mockProviderTemplate({ name: "minimax-cn-anthropic", kind: "anthropic", baseUrl: "https://api.minimaxi.com/anthropic", models: mockMiniMaxModels, visionModels: ["MiniMax-M3"], default: "MiniMax-M3", apiKeyEnv: "MINIMAX_PLAN_API_KEY", authHeader: true, contextWindow: 1048576, thinking: "adaptive", supportedEfforts: ["disabled", "adaptive"], defaultEffort: "adaptive" })),
1318 mockPreset("minimax-global-anthropic", "MiniMax Global Anthropic", "MiniMax international Anthropic-compatible endpoint with Bearer auth.", "MINIMAX_API_KEY", mockProviderTemplate({ name: "minimax-global-anthropic", kind: "anthropic", baseUrl: "https://api.minimax.io/anthropic", models: mockMiniMaxModels, visionModels: ["MiniMax-M3"], default: "MiniMax-M3", apiKeyEnv: "MINIMAX_API_KEY", authHeader: true, contextWindow: 1048576, thinking: "adaptive", supportedEfforts: ["disabled", "adaptive"], defaultEffort: "adaptive" })),
1319 mockPreset("glm-cn", "GLM CN API", "Zhipu GLM China OpenAI-compatible API with thinking controls.", "GLM_API_KEY", mockProviderTemplate({ name: "glm-cn", kind: "openai", baseUrl: "https://open.bigmodel.cn/api/paas/v4", models: mockGLMAPIModels, visionModels: ["glm-5v-turbo"], default: "glm-5.2", apiKeyEnv: "GLM_API_KEY", contextWindow: 1000000, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1320 mockPreset("zai-global", "Z.AI Global API", "Z.AI international OpenAI-compatible GLM API.", "ZAI_API_KEY", mockProviderTemplate({ name: "zai-global", kind: "openai", baseUrl: "https://api.z.ai/api/paas/v4", models: mockGLMAPIModels, visionModels: ["glm-5v-turbo"], default: "glm-5.2", apiKeyEnv: "ZAI_API_KEY", contextWindow: 1000000, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1321 mockPreset("glm-coding-plan-cn", "GLM Coding Plan CN", "Zhipu GLM China coding-plan endpoint.", "GLM_PLAN_API_KEY", mockProviderTemplate({ name: "glm-coding-plan-cn", kind: "openai", baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4", models: mockGLMCodingModels, default: "glm-5.2", apiKeyEnv: "GLM_PLAN_API_KEY", contextWindow: 1000000, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1322 mockPreset("glm-coding-plan-cn-anthropic", "GLM Coding Plan CN Anthropic", "Zhipu GLM China coding-plan Anthropic-compatible endpoint.", "GLM_PLAN_API_KEY", mockProviderTemplate({ name: "glm-coding-plan-cn-anthropic", kind: "anthropic", baseUrl: "https://open.bigmodel.cn/api/anthropic", models: mockGLMAnthropicModels, default: "glm-5.2", apiKeyEnv: "GLM_PLAN_API_KEY", authHeader: true, thinking: "adaptive", contextWindow: 1000000 })),
1323 mockPreset("zai-coding-plan-global", "Z.AI Coding Plan Global", "Z.AI international coding-plan endpoint.", "ZAI_CODING_API_KEY", mockProviderTemplate({ name: "zai-coding-plan-global", kind: "openai", baseUrl: "https://api.z.ai/api/coding/paas/v4", models: mockGLMCodingModels, default: "glm-5.2", apiKeyEnv: "ZAI_CODING_API_KEY", contextWindow: 1000000, thinking: "enabled", supportedEfforts: ["enabled", "disabled"], defaultEffort: "enabled" })),
1324 mockPreset("zai-coding-plan-global-anthropic", "Z.AI Coding Plan Global Anthropic", "Z.AI international coding-plan Anthropic-compatible endpoint.", "ZAI_CODING_API_KEY", mockProviderTemplate({ name: "zai-coding-plan-global-anthropic", kind: "anthropic", baseUrl: "https://api.z.ai/api/anthropic", models: mockGLMAnthropicModels, default: "glm-5.2", apiKeyEnv: "ZAI_CODING_API_KEY", authHeader: true, thinking: "adaptive", contextWindow: 1000000 })),
1325 mockPreset("opencode-go", "OpenCode Go", "OpenCode Go relay with per-model capability overrides.", "OPENCODE_GO_API_KEY", mockProviderTemplate({ name: "opencode-go", kind: "openai", baseUrl: "https://opencode.ai/zen/go/v1", models: mockOpenCodeGoModels, visionModels: ["kimi-k3"], default: "glm-5.2", apiKeyEnv: "OPENCODE_GO_API_KEY", contextWindow: 128000, modelOverrides: [{ model: "glm-5.3", reasoningProtocol: "openai", supportedEfforts: ["low", "high", "max"], defaultEffort: "high" }, { model: "glm-5.2", reasoningProtocol: "openai", supportedEfforts: ["high", "max"], defaultEffort: "high" }, { model: "kimi-k3", reasoningProtocol: "openai", supportedEfforts: ["high", "max"], defaultEffort: "max", contextWindow: 1048576 }, { model: "hy3", reasoningProtocol: "openai", supportedEfforts: ["none", "low", "high"], defaultEffort: "high" }] }), { displayGroup: "opencode", displaySection: "go", displayTier: "compatibility", routeKind: "chat", displayOrder: 90 }),
1326 mockPreset("opencode-go-anthropic", "OpenCode Go Anthropic", "OpenCode Go subscription Anthropic-compatible route for Qwen and MiniMax.", "OPENCODE_GO_API_KEY", mockProviderTemplate({ name: "opencode-go-anthropic", kind: "anthropic", baseUrl: "https://opencode.ai/zen/go", models: ["qwen3.8-max", "qwen3.7-plus", "qwen3.7-max", "qwen3.6-plus", "minimax-m3", "minimax-m2.7", "minimax-m2.5"], visionModels: ["qwen3.8-max", "qwen3.7-plus", "qwen3.6-plus"], default: "qwen3.7-plus", apiKeyEnv: "OPENCODE_GO_API_KEY", thinking: "adaptive", contextWindow: 262144 }), { displayGroup: "opencode", displaySection: "go", displayTier: "advanced", routeKind: "anthropic", displayOrder: 20 }),
1327 mockPreset("opencode-go-responses", "OpenCode Go Responses", "OpenCode Go Responses API route for Grok 4.5, GPT 5.6 Luna, and Muse Spark.", "OPENCODE_GO_API_KEY", mockProviderTemplate({ name: "opencode-go-responses", kind: "responses", baseUrl: "https://opencode.ai/zen/go/v1", models: ["grok-4.5", "gpt-5.6-luna", "muse-spark-1.2-contributor"], visionModels: ["grok-4.5", "gpt-5.6-luna", "muse-spark-1.2-contributor"], default: "grok-4.5", apiKeyEnv: "OPENCODE_GO_API_KEY", contextWindow: 500000, supportedEfforts: ["low", "medium", "high"], defaultEffort: "high", modelOverrides: [{ model: "grok-4.5", reasoningProtocol: "", supportedEfforts: ["low", "medium", "high"], defaultEffort: "high", contextWindow: 500000 }, { model: "gpt-5.6-luna", reasoningProtocol: "", supportedEfforts: ["none", "low", "medium", "high", "xhigh", "max"], defaultEffort: "high", contextWindow: 1050000 }, { model: "muse-spark-1.2-contributor", reasoningProtocol: "", supportedEfforts: ["minimal", "low", "medium", "high", "xhigh"], defaultEffort: "high", contextWindow: 1048576 }] }), { displayGroup: "opencode", displaySection: "go", displayTier: "advanced", routeKind: "responses", displayOrder: 30 }),
1328 mockPreset("opencode-go-deepseek-anthropic", "OpenCode Go DeepSeek Anthropic", "OpenCode Go Anthropic Messages route for DeepSeek Flash with server-side web search.", "OPENCODE_GO_API_KEY", mockProviderTemplate({ name: "opencode-go-deepseek-anthropic", kind: "anthropic", baseUrl: "https://opencode.ai/zen/go", models: ["deepseek-v4-flash"], default: "deepseek-v4-flash", apiKeyEnv: "OPENCODE_GO_API_KEY", thinking: "adaptive", webSearch: true, serverWebSearchCapability: true, contextWindow: 262144, supportedEfforts: ["disabled", "high", "max"], defaultEffort: "high" }), { displayGroup: "opencode", displaySection: "go", displayTier: "advanced", routeKind: "search-anthropic", optional: true, displayOrder: 40 }),
1329 mockPreset("opencode-go-deepseek-responses", "OpenCode Go DeepSeek Responses", "OpenCode Go stateless Responses API route for DeepSeek Flash with server-side web search.", "OPENCODE_GO_API_KEY", mockProviderTemplate({ name: "opencode-go-deepseek-responses", kind: "responses", baseUrl: "https://opencode.ai/zen/go/v1", models: ["deepseek-v4-flash"], default: "deepseek-v4-flash", apiKeyEnv: "OPENCODE_GO_API_KEY", webSearch: true, serverWebSearchCapability: true, contextWindow: 1000000, supportedEfforts: ["disabled", "high", "max"], defaultEffort: "high" }), { displayGroup: "opencode", displaySection: "go", displayTier: "advanced", routeKind: "search-responses", optional: true, displayOrder: 50 }),
1330 mockPreset("opencode-zen-anthropic", "OpenCode Zen Anthropic", "OpenCode Zen Anthropic-compatible route for Claude and Qwen models.", "OPENCODE_API_KEY", mockProviderTemplate({ name: "opencode-zen-anthropic", kind: "anthropic", baseUrl: "https://opencode.ai/zen", models: ["claude-sonnet-4-6", "claude-opus-4-8", "claude-haiku-4-5", "qwen3.6-plus", "qwen3.5-plus", "qwen3.6-plus-free"], visionModels: ["claude-sonnet-4-6", "claude-opus-4-8", "claude-haiku-4-5"], default: "claude-sonnet-4-6", apiKeyEnv: "OPENCODE_API_KEY", contextWindow: 262144 }), { displayGroup: "opencode", displaySection: "zen", displayTier: "primary", routeKind: "zen-anthropic", displayOrder: 100 }),
1331 mockPreset("qwen-cn", "Qwen CN API", "Alibaba DashScope China standard OpenAI-compatible endpoint.", "QWEN_API_KEY", mockProviderTemplate({ name: "qwen-cn", kind: "openai", baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1", models: mockQwenAPIModels, visionModels: ["qwen3.7-plus", "qwen3.6-plus", "qwen3.5-plus", "kimi-k2.5"], default: "qwen3.7-plus", apiKeyEnv: "QWEN_API_KEY" })),
1332 mockPreset("qwen-global", "Qwen Global API", "Alibaba DashScope international standard OpenAI-compatible endpoint.", "QWEN_API_KEY", mockProviderTemplate({ name: "qwen-global", kind: "openai", baseUrl: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", models: mockQwenAPIModels, visionModels: ["qwen3.7-plus", "qwen3.6-plus", "qwen3.5-plus", "kimi-k2.5"], default: "qwen3.7-plus", apiKeyEnv: "QWEN_API_KEY" })),
1333 mockPreset("qwen-coding-plan-cn", "Qwen Coding Plan CN", "Alibaba Cloud Qwen Coding Plan China endpoint.", "QWEN_CODING_API_KEY", mockProviderTemplate({ name: "qwen-coding-plan-cn", kind: "openai", baseUrl: "https://coding.dashscope.aliyuncs.com/v1", models: mockQwenPlanModels, visionModels: mockQwenPlanVisionModels, default: "qwen3.7-plus", apiKeyEnv: "QWEN_CODING_API_KEY" })),
1334 mockPreset("qwen-coding-plan-cn-anthropic", "Qwen Coding Plan CN Anthropic", "Alibaba Cloud Qwen Coding Plan China Anthropic-compatible endpoint.", "QWEN_CODING_API_KEY", mockProviderTemplate({ name: "qwen-coding-plan-cn-anthropic", kind: "anthropic", baseUrl: "https://coding.dashscope.aliyuncs.com/apps/anthropic", models: mockQwenPlanModels, visionModels: mockQwenPlanVisionModels, default: "qwen3.7-plus", apiKeyEnv: "QWEN_CODING_API_KEY", thinking: "adaptive" })),
1335 mockPreset("qwen-coding-plan-global", "Qwen Coding Plan Global", "Alibaba Cloud Qwen Coding Plan international endpoint.", "QWEN_CODING_API_KEY", mockProviderTemplate({ name: "qwen-coding-plan-global", kind: "openai", baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1", models: mockQwenPlanModels, visionModels: mockQwenPlanVisionModels, default: "qwen3.7-plus", apiKeyEnv: "QWEN_CODING_API_KEY" })),
1336 mockPreset("qwen-coding-plan-global-anthropic", "Qwen Coding Plan Global Anthropic", "Alibaba Cloud Qwen Coding Plan international Anthropic-compatible endpoint.", "QWEN_CODING_API_KEY", mockProviderTemplate({ name: "qwen-coding-plan-global-anthropic", kind: "anthropic", baseUrl: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic", models: mockQwenPlanModels, visionModels: mockQwenPlanVisionModels, default: "qwen3.7-plus", apiKeyEnv: "QWEN_CODING_API_KEY", thinking: "adaptive" })),
1337 mockPreset("stepfun", "StepFun", "StepFun coding-plan OpenAI-compatible endpoint.", "STEPFUN_API_KEY", mockProviderTemplate({ name: "stepfun", kind: "openai", baseUrl: "https://api.stepfun.com/step_plan/v1", models: mockStepFunModels, default: "step-3.7-flash", apiKeyEnv: "STEPFUN_API_KEY", supportedEfforts: ["low", "medium", "high"], defaultEffort: "medium" })),
1338 mockPreset("stepfun-anthropic", "StepFun Anthropic", "StepFun coding-plan Anthropic-compatible endpoint.", "STEPFUN_API_KEY", mockProviderTemplate({ name: "stepfun-anthropic", kind: "anthropic", baseUrl: "https://api.stepfun.com/step_plan", models: mockStepFunModels, default: "step-3.7-flash", apiKeyEnv: "STEPFUN_API_KEY", thinking: "adaptive", supportedEfforts: ["low", "medium", "high"], defaultEffort: "medium" })),
1339 mockPreset("stepfun-responses", "StepFun Responses API", "StepFun Responses API endpoint with reasoning effort and tool calls (step-3.7-flash).", "STEPFUN_API_KEY", mockProviderTemplate({ name: "stepfun-responses", kind: "responses", baseUrl: "https://api.stepfun.com/v1", models: ["step-3.7-flash"], default: "step-3.7-flash", apiKeyEnv: "STEPFUN_API_KEY", supportedEfforts: ["low", "medium", "high"], defaultEffort: "medium" })),
1340 mockPreset("stepfun-api", "StepFun API Pay-as-you-go", "StepFun pay-as-you-go OpenAI-compatible API with vision on step-3.7-flash.", "STEPFUN_API_KEY", mockProviderTemplate({ name: "stepfun-api", kind: "openai", baseUrl: "https://api.stepfun.com/v1", models: mockStepFunModels, visionModels: ["step-3.7-flash"], default: "step-3.7-flash", apiKeyEnv: "STEPFUN_API_KEY", supportedEfforts: ["low", "medium", "high"], defaultEffort: "medium" })),
1341 mockPreset("stepfun-api-anthropic", "StepFun API Anthropic Pay-as-you-go", "StepFun pay-as-you-go Anthropic-compatible Messages API with automatic prefix caching.", "STEPFUN_API_KEY", mockProviderTemplate({ name: "stepfun-api-anthropic", kind: "anthropic", baseUrl: "https://api.stepfun.com", models: mockStepFunModels, default: "step-3.7-flash", apiKeyEnv: "STEPFUN_API_KEY", thinking: "adaptive", supportedEfforts: ["low", "medium", "high"], defaultEffort: "medium" })),
1342 mockPreset("novita", "NovitaAI", "NovitaAI OpenAI-compatible multi-model gateway.", "NOVITA_API_KEY", mockProviderTemplate({ name: "novita", kind: "openai", baseUrl: "https://api.novita.ai/openai/v1", models: mockNovitaModels, default: "zai-org/glm-5.2", apiKeyEnv: "NOVITA_API_KEY" })),
1343 mockPreset("gmi", "GMI Cloud", "GMI Cloud direct multi-model OpenAI-compatible gateway.", "GMI_API_KEY", mockProviderTemplate({ name: "gmi", kind: "openai", baseUrl: "https://api.gmi-serving.com/v1", models: mockGMIModels, default: "zai-org/GLM-5.2-FP8", apiKeyEnv: "GMI_API_KEY", headers: { "User-Agent": "Reasonix" } })),
1344 mockPreset("vercel-ai-gateway", "Vercel AI Gateway", "Vercel AI Gateway via Anthropic-compatible Messages API.", "AI_GATEWAY_API_KEY", mockProviderTemplate({ name: "vercel-ai-gateway", kind: "anthropic", baseUrl: "https://ai-gateway.vercel.sh", models: mockVercelModels, visionModels: ["anthropic/claude-sonnet-4.6", "anthropic/claude-opus-4.8", "openai/gpt-5.4", "openai/gpt-5.4-pro", "moonshotai/kimi-k2.7-code"], default: "anthropic/claude-sonnet-4.6", apiKeyEnv: "AI_GATEWAY_API_KEY", authHeader: true, contextWindow: 1000000 })),
1345 mockPreset("huggingface", "HuggingFace Router", "HuggingFace Inference Router OpenAI-compatible endpoint.", "HF_TOKEN", mockProviderTemplate({ name: "huggingface", kind: "openai", baseUrl: "https://router.huggingface.co/v1", models: ["zai-org/GLM-5.2", "deepseek-ai/DeepSeek-V3.2", "Qwen/Qwen3.5-72B-Instruct"], default: "zai-org/GLM-5.2", apiKeyEnv: "HF_TOKEN" })),
1346 mockPreset("nvidia", "NVIDIA NIM", "NVIDIA NIM OpenAI-compatible accelerated inference endpoint.", "NVIDIA_API_KEY", mockProviderTemplate({ name: "nvidia", kind: "openai", baseUrl: "https://integrate.api.nvidia.com/v1", models: ["nvidia/nemotron-3-nano-30b-a3b", "nvidia/nemotron-3-super-120b-a12b", "nvidia/nemotron-3-ultra-550b-a55b", "deepseek-ai/deepseek-v4-pro", "qwen/qwen3.5-397b-a17b"], default: "nvidia/nemotron-3-nano-30b-a3b", apiKeyEnv: "NVIDIA_API_KEY" })),
1347 mockPreset("kilocode", "KiloCode", "Kilo Code gateway OpenAI-compatible endpoint.", "KILOCODE_API_KEY", mockProviderTemplate({ name: "kilocode", kind: "openai", baseUrl: "https://api.kilo.ai/api/gateway", models: ["kilo/auto"], default: "kilo/auto", apiKeyEnv: "KILOCODE_API_KEY" })),
1348 createMockModelScopePreset(mockProviderTemplate, mockPreset),
1349 mockPreset("ollama-cloud", "Ollama Cloud", "Hosted Ollama Cloud OpenAI-compatible endpoint with max reasoning effort.", "OLLAMA_API_KEY", mockProviderTemplate({ name: "ollama-cloud", kind: "openai", baseUrl: "https://ollama.com/v1", models: mockOllamaCloudModels, default: "glm-5.2", apiKeyEnv: "OLLAMA_API_KEY" })),
1350 mockPreset("scnet", "SCNet", "SCNet (National Supercomputing Internet) OpenAI-compatible token-plan API.", "SCNET_API_KEY", mockProviderTemplate({ name: "scnet", kind: "openai", baseUrl: "https://api.scnet.cn/api/llm/v1", modelsUrl: "https://api.scnet.cn/api/llm/v1/models", models: ["GLM-5.2", "GLM-5", "GLM-5.1", "Kimi-K3", "Kimi-K2.7-Code", "Kimi-K2.6", "Kimi-K2.5", "DeepSeek-V4-Flash", "DeepSeek-V3.2", "MiniMax-M3", "MiniMax-M2.7", "MiniMax-M2.5", "MiMo-V2.5-Pro"], visionModels: ["Kimi-K2.6", "Kimi-K2.5"], default: "MiniMax-M2.5", apiKeyEnv: "SCNET_API_KEY", modelOverrides: [{ model: "DeepSeek-V4-Flash", reasoningProtocol: "openai", supportedEfforts: ["high", "max"], defaultEffort: "high" }] })),
1351 mockPreset("scnet-anthropic", "SCNet Anthropic", "SCNet (National Supercomputing Internet) Anthropic-compatible token-plan endpoint with Bearer auth.", "SCNET_API_KEY", mockProviderTemplate({ name: "scnet-anthropic", kind: "anthropic", baseUrl: "https://api.scnet.cn/api/llm/anthropic", models: ["GLM-5.2", "GLM-5", "GLM-5.1", "Kimi-K3", "Kimi-K2.7-Code", "Kimi-K2.6", "Kimi-K2.5", "DeepSeek-V4-Flash", "DeepSeek-V3.2", "MiniMax-M3", "MiniMax-M2.7", "MiniMax-M2.5", "MiMo-V2.5-Pro"], visionModels: ["Kimi-K2.6", "Kimi-K2.5"], default: "MiniMax-M2.5", apiKeyEnv: "SCNET_API_KEY", authHeader: true })),
1352 ];
1353
1354 let mockCatalogLoad: Promise<void> | undefined;
1355 let mockCatalogs: Record<string, NonNullable<ProviderPresetView["catalog"]>> = {};
1356 function loadMockProviderCatalog(): Promise<void> {
1357 return mockCatalogLoad ??= import("./providerCatalog.generated.json").then(({default: data}) => {
1358 mockCatalogs = data.catalogs;
1359 for (const template of data.templates) {
1360 if (!mockProviderPresetTemplates.some(p => p.id === template.id)) {
1361 mockProviderPresetTemplates.push(mockPreset(template.id, template.label, template.description, template.keyEnv, mockProviderTemplate(template.provider)));
1362 }
1363 }
1364 });
1365 }
1366
1367 function mockProviderPresetViews(): ProviderPresetView[] {
1368 return [...mockProviderPresetTemplates].sort((a, b) => mockProviderPresetDisplayRank(a.id) - mockProviderPresetDisplayRank(b.id)).map((template) => ({
1369 catalog: mockCatalogs[template.id],
1370 id: template.id,
1371 label: template.label,
1372 description: template.description,
1373 keyEnv: template.keyEnv,
1374 recommended: Boolean(template.recommended),
1375 billingMode: template.billingMode,
1376 displayGroup: template.displayGroup,
1377 displaySection: template.displaySection,
1378 displayTier: template.displayTier,
1379 routeKind: template.routeKind,
1380 optional: Boolean(template.optional),
1381 displayOrder: template.displayOrder,
1382 providerNames: [...(template.providers ?? [template.provider]).map((provider) => provider.name)],
1383 models: [...(template.providers ?? [template.provider]).flatMap((provider) => provider.models)],
1384 added: false,
1385 status: "available",
1386 statusProviderNames: [],
1387 keySet: false,
1388 requiresKey: true,
1389 configured: false,
1390 }));
1391 }
1392
1393 function mockProviderPresetDisplayRank(id: string): number {
1394 if (id === "opencode-go-recommended") return -3;
1395 if (id === "deepseek-responses") return -2;
1396 if (id === "glm-cn" || id === "zai-global" || id.startsWith("glm-coding-plan-") || id.startsWith("zai-coding-plan-")) return 0;
1397 if (id.startsWith("longcat-")) return 1;
1398 if (id === "token-rhythm") return 1;
1399 if (id.startsWith("kimi-")) return 2;
1400 if (id.startsWith("minimax-")) return 3;
1401 return 4;
1402 }
1403
1404 function cloneMockProviderTemplates(id: string, key: string): ProviderView[] | undefined {
1405 const template = mockProviderPresetTemplates.find((candidate) => candidate.id === id);
1406 if (!template) return undefined;
1407 return (template.providers ?? [template.provider]).map((provider) => ({
1408 ...JSON.parse(JSON.stringify(provider)) as ProviderView,
1409 keySet: Boolean(key.trim()),
1410 }));
1411 }
1412
1413 function mockExternalOpenerIconDataURL(color: string, label: string): string {
1414 const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${color}"/><text x="32" y="40" text-anchor="middle" font-family="system-ui" font-size="25" font-weight="700" fill="white">${label}</text></svg>`;
1415 return `data:image/svg+xml,${encodeURIComponent(svg)}`;
1416 }
1417 function makeMockApp(): MockAppBindings {
1418 const credentialDiagnostics = (actions: string[] = []): CredentialDiagnosticReport => ({
1419 home: "/mock/.reasonix",
1420 credentialPath: "/mock/.reasonix/.env",
1421 pendingTransactions: 0,
1422 checks: [],
1423 actions,
1424 });
1425 const scenario = mockScenario();
1426 // Both bridge families publish into the same catalog, as ListTabs does in
1427 // the desktop backend. A remote event is not a second source of tab state.
1428 const remoteProjects = createMockRemoteProjects({
1429 get: id => { const tab = mockTabs.find(item => item.id === id); return tab && { ...tab }; },
1430 publish: tab => {
1431 const existing = mockTabs.some(item => item.id === tab.id);
1432 mockTabs = mockTabs.map(item => item.id === tab.id ? { ...tab } : tab.active ? { ...item, active: false } : item);
1433 if (!existing) mockTabs.push({ ...tab });
1434 },
1435 remove: id => {
1436 if (!mockTabs.some(tab => tab.id === id)) return;
1437 if (mockTabs.length === 1) throw new Error("cannot close the last tab");
1438 const index = mockTabs.findIndex(tab => tab.id === id), active = mockTabs[index].active;
1439 mockTabs = mockTabs.filter(tab => tab.id !== id);
1440 if (active) setMockActiveTab(mockTabs[Math.min(index, mockTabs.length - 1)].id);
1441 },
1442 });
1443 const freshMock = scenario === "fresh";
1444 const devPreview = typeof import.meta.env !== "undefined" && import.meta.env.DEV;
1445 const guidanceMock = scenario === "guidance", recoveryMock = devPreview && scenario === "recovery";
1446 const inboxQueuePreview = devPreview && guidanceMock ? import("./inboxQueuePreview").then(module => module.createInboxQueuePreviewBindings()) : undefined;
1447 const runningMock = scenario === "running" || guidanceMock;
1448 const sandboxEscapeMock = scenario === "sandbox_escape";
1449 const noticePreviewMock = scenario === "notice";
1450 const deepSeekUpgradeMock = scenario === "deepseek_upgrade";
1451 const benchMock = scenario === "bench";
1452 let cancelled = false;
1453 let pendingAskPreview = false, pendingApprovalPreview = false;
1454 // Mirrors the last emitted approval preview so mode switches can mirror the
1455 // backend drain contract: only non-fresh tools auto-allow; plan/sandbox
1456 // escape prompts stay pending and visible.
1457 let pendingApprovalPreviewPrompt: { id: string; tool: string } | undefined;
1458 const globalWorkspaceRoot = "~/Library/Application Support/reasonix/global-workspace";
1459 let cwd = freshMock ? globalWorkspaceRoot : browserPlatformOverride() === "windows" ? "C:\\Projects\\joyquant-db" : "~/projects/joyquant-db"; // mutable so PickWorkspace is visible in dev
1460 let workspaces = freshMock ? [] : ["~/projects/joyquant-db", "~/projects/joyquant-sys", "~/projects/reasonix", "~/projects/blade"];
1461 let mockEffort = "auto";
1462 let mockDesktopZoomFactor = 1.0;
1463 let mockActiveThemeId = "";
1464 let mockBaseStyle = "graphite";
1465 let mockThemeMode: "auto" | "light" | "dark" = "dark";
1466 let mockHeartbeatRevision = 0;
1467 let mockHeartbeatTasks: unknown[] = [];
1468 // Vite rewrites these literal asset URLs in both dev and production builds.
1469 // Keeping them on the browser mock makes local visual acceptance match the
1470 // desktop bridge, whose ListThemePacks response carries the same two URLs.
1471 const mockOfficialThemeAssets = {
1472 "official-rose-dawn": {
1473 previewUrl: new URL("../../../themes/official/official-rose-dawn/preview.webp", import.meta.url).href,
1474 backgroundUrl: new URL("../../../themes/official/official-rose-dawn/background.webp", import.meta.url).href,
1475 },
1476 "official-fortune-forge": {
1477 previewUrl: new URL("../../../themes/official/official-fortune-forge/preview.webp", import.meta.url).href,
1478 backgroundUrl: new URL("../../../themes/official/official-fortune-forge/background.webp", import.meta.url).href,
1479 },
1480 "official-crimson-horizon": {
1481 previewUrl: new URL("../../../themes/official/official-crimson-horizon/preview.webp", import.meta.url).href,
1482 backgroundUrl: new URL("../../../themes/official/official-crimson-horizon/background.webp", import.meta.url).href,
1483 },
1484 "official-sage-breeze": {
1485 previewUrl: new URL("../../../themes/official/official-sage-breeze/preview.webp", import.meta.url).href,
1486 backgroundUrl: new URL("../../../themes/official/official-sage-breeze/background.webp", import.meta.url).href,
1487 },
1488 "official-spark-notebook": {
1489 previewUrl: new URL("../../../themes/official/official-spark-notebook/preview.webp", import.meta.url).href,
1490 backgroundUrl: new URL("../../../themes/official/official-spark-notebook/background.webp", import.meta.url).href,
1491 },
1492 "official-violet-starlight": {
1493 previewUrl: new URL("../../../themes/official/official-violet-starlight/preview.webp", import.meta.url).href,
1494 backgroundUrl: new URL("../../../themes/official/official-violet-starlight/background.webp", import.meta.url).href,
1495 },
1496 "official-cyan-stage": {
1497 previewUrl: new URL("../../../themes/official/official-cyan-stage/preview.webp", import.meta.url).href,
1498 backgroundUrl: new URL("../../../themes/official/official-cyan-stage/background.webp", import.meta.url).href,
1499 },
1500 "official-noir-gold": {
1501 previewUrl: new URL("../../../themes/official/official-noir-gold/preview.webp", import.meta.url).href,
1502 backgroundUrl: new URL("../../../themes/official/official-noir-gold/background.webp", import.meta.url).href,
1503 },
1504 } as const;
1505 registerTrustedThemeBackgroundURLs(Object.values(mockOfficialThemeAssets).map((asset) => asset.backgroundUrl));
1506 let mockThemePacks: import("./themePack").ThemePackView[] = [
1507 { id: "graphite", name: "Graphite", author: "Reasonix", baseStyle: "graphite", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1508 { id: "aurora", name: "Aurora", author: "Reasonix", baseStyle: "aurora", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1509 { id: "slate", name: "Slate", author: "Reasonix", baseStyle: "slate", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1510 { id: "carbon", name: "Carbon", author: "Reasonix", baseStyle: "carbon", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1511 { id: "nocturne", name: "Nocturne", author: "Reasonix", baseStyle: "nocturne", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1512 { id: "amber", name: "Amber", author: "Reasonix", baseStyle: "amber", builtin: true, kind: "base", active: false, hasBackground: false, tokens: {}, recipes: { density: "comfortable", corners: "soft" } },
1513 { ...mockOfficialThemeAssets["official-rose-dawn"], id: "official-rose-dawn", name: "Rose Dawn", author: "Reasonix Contributors", license: "MIT", baseStyle: "graphite", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-rose-dawn.name", descriptionKey: "settings.themes.official.official-rose-dawn.description", tokens: { light: { bg: "#FFF7F8", fg: "#3A252C", accent: "#B43F65" }, dark: { bg: "#1E1419", fg: "#FFF3F6", accent: "#E26D91" } }, recipes: { density: "comfortable", corners: "round" }, background: { focusX: 0.72, focusY: 0.43, safeArea: "left", homeOpacity: 1, taskOpacity: 0.2, overlayStrength: 0.68, paneOpacity: 0.50 } },
1514 { ...mockOfficialThemeAssets["official-fortune-forge"], id: "official-fortune-forge", name: "Fortune Forge", author: "Reasonix Contributors", license: "MIT", baseStyle: "amber", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-fortune-forge.name", descriptionKey: "settings.themes.official.official-fortune-forge.description", tokens: { light: { bg: "#FFF8E8", fg: "#382116", accent: "#A92D22" }, dark: { bg: "#1D140D", fg: "#FFF2D1", accent: "#E8AD38" } }, recipes: { density: "comfortable", corners: "soft" }, background: { focusX: 0.74, focusY: 0.44, safeArea: "left", homeOpacity: 1, taskOpacity: 0.2, overlayStrength: 0.7, paneOpacity: 0.50 } },
1515 { ...mockOfficialThemeAssets["official-crimson-horizon"], id: "official-crimson-horizon", name: "Crimson Horizon", author: "Reasonix Contributors", license: "MIT", baseStyle: "graphite", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-crimson-horizon.name", descriptionKey: "settings.themes.official.official-crimson-horizon.description", tokens: { light: { bg: "#FFF8F7", fg: "#301D1D", accent: "#B92B38" }, dark: { bg: "#190D11", fg: "#FFF1F2", accent: "#FF6772" } }, recipes: { density: "comfortable", corners: "soft" }, background: { focusX: 0.75, focusY: 0.45, safeArea: "left", homeOpacity: 0.98, taskOpacity: 0.22, overlayStrength: 0.66, paneOpacity: 0.50 } },
1516 { ...mockOfficialThemeAssets["official-sage-breeze"], id: "official-sage-breeze", name: "Sage Breeze", author: "Reasonix Contributors", license: "MIT", baseStyle: "slate", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-sage-breeze.name", descriptionKey: "settings.themes.official.official-sage-breeze.description", tokens: { light: { bg: "#F7F7EF", fg: "#26332D", accent: "#47735F" }, dark: { bg: "#101814", fg: "#EEF6F0", accent: "#84CBA7" } }, recipes: { density: "comfortable", corners: "soft" }, background: { focusX: 0.73, focusY: 0.44, safeArea: "left", homeOpacity: 1, taskOpacity: 0.2, overlayStrength: 0.68, paneOpacity: 0.50 } },
1517 { ...mockOfficialThemeAssets["official-spark-notebook"], id: "official-spark-notebook", name: "Spark Notebook", author: "Reasonix Contributors", license: "MIT", baseStyle: "aurora", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-spark-notebook.name", descriptionKey: "settings.themes.official.official-spark-notebook.description", tokens: { light: { bg: "#FFF9ED", fg: "#2B2F35", accent: "#007B78" }, dark: { bg: "#14171A", fg: "#F8F5E9", accent: "#42D1C6" } }, recipes: { density: "comfortable", corners: "round" }, background: { focusX: 0.74, focusY: 0.46, safeArea: "left", homeOpacity: 0.98, taskOpacity: 0.2, overlayStrength: 0.68, paneOpacity: 0.50 } },
1518 { ...mockOfficialThemeAssets["official-violet-starlight"], id: "official-violet-starlight", name: "Violet Starlight", author: "Reasonix Contributors", license: "MIT", baseStyle: "nocturne", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-violet-starlight.name", descriptionKey: "settings.themes.official.official-violet-starlight.description", tokens: { light: { bg: "#F7F4FF", fg: "#251F3C", accent: "#6242C7" }, dark: { bg: "#0C1022", fg: "#F4F2FF", accent: "#9B86FF" } }, recipes: { density: "comfortable", corners: "round" }, background: { focusX: 0.73, focusY: 0.44, safeArea: "left", homeOpacity: 0.96, taskOpacity: 0.18, overlayStrength: 0.72, paneOpacity: 0.50 } },
1519 { ...mockOfficialThemeAssets["official-cyan-stage"], id: "official-cyan-stage", name: "Cyan Stage", author: "Reasonix Contributors", license: "MIT", baseStyle: "carbon", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-cyan-stage.name", descriptionKey: "settings.themes.official.official-cyan-stage.description", tokens: { light: { bg: "#F1FCFD", fg: "#173238", accent: "#007C92" }, dark: { bg: "#07181D", fg: "#E9FCFF", accent: "#37D7E4" } }, recipes: { density: "comfortable", corners: "round" }, background: { focusX: 0.74, focusY: 0.45, safeArea: "left", homeOpacity: 0.96, taskOpacity: 0.18, overlayStrength: 0.72, paneOpacity: 0.50 } },
1520 { ...mockOfficialThemeAssets["official-noir-gold"], id: "official-noir-gold", name: "Noir Gold", author: "Reasonix Contributors", license: "MIT", baseStyle: "carbon", builtin: true, kind: "official", active: false, hasBackground: true, nameKey: "settings.themes.official.official-noir-gold.name", descriptionKey: "settings.themes.official.official-noir-gold.description", tokens: { light: { bg: "#FCF8EE", fg: "#2A241B", accent: "#7A5A16" }, dark: { bg: "#0D0B09", fg: "#F8F1DF", accent: "#D9B45B" } }, recipes: { density: "comfortable", corners: "soft" }, background: { focusX: 0.73, focusY: 0.43, safeArea: "left", homeOpacity: 0.94, taskOpacity: 0.18, overlayStrength: 0.74, paneOpacity: 0.50 } },
1521 ];
1522 const day = 86_400_000;
1523 const t0 = Date.now();
1524 // Mutable so MCP add/remove/retry are observable in browser dev.
1525 let capServers: ServerView[] = [
1526 {
1527 name: "project-knowledge",
1528 transport: "http",
1529 status: "connected",
1530 configured: true,
1531 autoStart: true,
1532 tier: "background",
1533 source: "project",
1534 configSource: "reasonix.toml",
1535 url: "https://mcp.example.test/project",
1536 tools: 3,
1537 prompts: 0,
1538 resources: 1,
1539 toolList: [
1540 { name: "search_knowledge", description: "Search the project knowledge base.", readOnlyHint: true },
1541 { name: "get_document", description: "Read a knowledge-base document.", readOnlyHint: true },
1542 { name: "list_topics", description: "List available knowledge topics.", readOnlyHint: true },
1543 ],
1544 },
1545 {
1546 name: "github",
1547 transport: "stdio",
1548 status: "connected",
1549 configured: true,
1550 autoStart: true,
1551 tier: "background",
1552 command: "npx",
1553 args: ["-y", "@modelcontextprotocol/server-github"],
1554 tools: 4,
1555 prompts: 2,
1556 resources: 0,
1557 toolList: [
1558 { name: "issue_read", description: "Read GitHub issue details and comments.", readOnlyHint: true },
1559 { name: "pull_request_read", description: "Read pull request metadata, files, and review threads.", readOnlyHint: true },
1560 { name: "search_issues", description: "Search issues and pull requests.", readOnlyHint: true },
1561 { name: "issue_write", description: "Create or update GitHub issues." },
1562 ],
1563 },
1564 {
1565 name: "linear",
1566 transport: "http",
1567 status: "initializing",
1568 configured: true,
1569 autoStart: true,
1570 tier: "background",
1571 url: "https://mcp.linear.app/mcp",
1572 authStatus: "possible",
1573 authUrl: "https://mcp.linear.app/mcp",
1574 tools: 8,
1575 prompts: 0,
1576 resources: 0,
1577 toolList: [
1578 { name: "list_issues", description: "List and filter Linear issues." },
1579 { name: "get_issue", description: "Fetch a Linear issue by id or key." },
1580 { name: "create_issue", description: "Create a Linear issue." },
1581 { name: "update_issue", description: "Update status, assignee, priority, or labels." },
1582 { name: "list_projects", description: "List Linear projects." },
1583 { name: "get_project", description: "Fetch project details." },
1584 { name: "list_teams", description: "List Linear teams." },
1585 { name: "search", description: "Search Linear workspace objects." },
1586 ],
1587 },
1588 { name: "figma", transport: "http", status: "failed", configured: true, autoStart: true, tier: "background", url: "https://mcp.figma.com/mcp", authStatus: "required", authUrl: "https://mcp.figma.com/mcp", tools: 0, prompts: 0, resources: 0, error: "connect: 401 unauthorized" },
1589 ];
1590 const capSkills: SkillView[] = [
1591 {
1592 name: "explore", description: "Investigate the codebase in an isolated subagent", scope: "builtin", runAs: "subagent", enabled: true,
1593 allowedTools: ["read_file", "ls", "glob", "grep", "code_index"], invocation: "/explore", invocationMode: "auto",
1594 configuredModel: "deepseek/deepseek-v4-pro", configuredEffort: "high",
1595 },
1596 { name: "research", description: "Combine web_fetch + code reading in an isolated subagent", scope: "builtin", runAs: "subagent", enabled: true, allowedTools: ["read_file", "ls", "glob", "grep", "code_index", "web_fetch"], invocation: "/research", invocationMode: "auto" },
1597 { name: "review", description: "Review the staged diff", scope: "project", sourceDir: "~/projects/reasonix/.reasonix/skills", runAs: "inline", enabled: false, invocation: "/review" },
1598 { name: "init", description: "Scaffold a REASONIX.md for this repo", scope: "builtin", runAs: "inline", enabled: true, invocation: "/init" },
1599 {
1600 name: "my-formatter", description: "Formats code the way I like it", scope: "global", sourceDir: "~/.reasonix/skills", runAs: "subagent", enabled: true,
1601 model: "deepseek-pro", effort: "high", allowedTools: ["read_file", "edit_file"], color: "amber", invocation: "/my-formatter", invocationMode: "manual",
1602 body: "You are a code formatting assistant. Reformat the given file to match project style without changing behavior.",
1603 },
1604 ];
1605 let capSkillRoots: SkillRootView[] = [
1606 { dir: "~/projects/reasonix/.reasonix/skills", scope: "project", priority: 1, status: "missing", enabled: true, configured: false, removable: true, skills: 0 },
1607 {
1608 dir: "~/my-skills",
1609 scope: "custom",
1610 priority: 5,
1611 status: "ok",
1612 enabled: true,
1613 configured: true,
1614 removable: true,
1615 skills: 1,
1616 skillItems: [{ name: "review", description: "Review the staged diff", scope: "custom", runAs: "inline" }],
1617 },
1618 {
1619 dir: "~/.reasonix/skills",
1620 scope: "global",
1621 priority: 6,
1622 status: "ok",
1623 enabled: true,
1624 configured: false,
1625 removable: true,
1626 skills: 2,
1627 skillItems: [
1628 { name: "explore", description: "Investigate the codebase in an isolated subagent", scope: "global", runAs: "subagent" },
1629 { name: "init", description: "Scaffold a REASONIX.md for this repo", scope: "global", runAs: "inline" },
1630 ],
1631 },
1632 ];
1633 let capPlugins: PluginView[] = [];
1634 const mockSwitchWorkspace = async (path: string) => {
1635 cwd = path || "~";
1636 workspaces = [cwd, ...workspaces.filter((p) => p !== cwd)].slice(0, 12);
1637 if (!mockProjectTree.some((node) => node.kind === "project" && node.root === cwd)) {
1638 mockProjectTree.unshift({
1639 key: `project_${cwd}`,
1640 kind: "project",
1641 label: baseName(cwd),
1642 root: cwd,
1643 children: [],
1644 });
1645 }
1646 return cwd;
1647 };
1648 // Mutable so delete/rename are observable in browser dev.
1649 const sessions: SessionMeta[] = [
1650 { path: "/mock/sessions/a.jsonl", preview: "fix the login bug in auth.go", turns: 12, createdAt: t0 - 2 * day, lastActivityAt: t0 - 3_600_000, modTime: t0 - 3_600_000, current: true, open: true },
1651 { path: "/mock/sessions/b-recovery-0123456789abcdef.jsonl", preview: "refactor the payment module", turns: 5, createdAt: t0 - 3 * day, lastActivityAt: t0 - 6 * 3_600_000, modTime: t0 - 6 * 3_600_000, current: false, open: true, recovered: true, recoveryCopy: true },
1652 { path: "/mock/sessions/c.jsonl", preview: "write the README and badges", turns: 8, createdAt: t0 - 4 * day, lastActivityAt: t0 - day - 3_600_000, modTime: t0 - day - 3_600_000, current: false, open: false },
1653 { path: "/mock/sessions/d.jsonl", preview: "explain the plugin host design", turns: 3, createdAt: t0 - 5 * day, lastActivityAt: t0 - 4 * day, modTime: t0 - 4 * day, current: false, open: false },
1654 ];
1655 const trashedSessions: SessionMeta[] = [
1656 {
1657 path: "/mock/sessions/.trash/trash-dev-standard.jsonl",
1658 title: t("mock.trashDevStandardTitle"),
1659 preview: t("mock.trashDevStandardPreview"),
1660 turns: 4,
1661 createdAt: t0 - 8 * day,
1662 lastActivityAt: t0 - 7 * day,
1663 modTime: t0 - 7 * day,
1664 deletedAt: t0 - 20 * 60_000,
1665 current: false,
1666 open: false,
1667 scope: "project",
1668 workspaceRoot: "~/projects/joyquant-db",
1669 topicId: "topic_dev_standard",
1670 topicTitle: t("mock.trashDevStandardTitle"),
1671 },
1672 {
1673 path: "/mock/sessions/.trash/trash-p3a-review.jsonl",
1674 title: t("mock.trashP3aTitle"),
1675 preview: t("mock.trashP3aPreview"),
1676 turns: 7,
1677 createdAt: t0 - 6 * day,
1678 lastActivityAt: t0 - 5 * day,
1679 modTime: t0 - 5 * day,
1680 deletedAt: t0 - 2 * 3_600_000,
1681 current: false,
1682 open: false,
1683 scope: "project",
1684 workspaceRoot: "~/projects/joyquant-sys",
1685 topicId: "topic_p3a_pd",
1686 topicTitle: t("mock.trashP3aTitle"),
1687 },
1688 {
1689 path: "/mock/sessions/.trash/trash-global-product.jsonl",
1690 title: t("mock.trashGlobalProductTitle"),
1691 preview: t("mock.trashGlobalProductPreview"),
1692 turns: 2,
1693 createdAt: t0 - 4 * day,
1694 lastActivityAt: t0 - 3 * day,
1695 modTime: t0 - 3 * day,
1696 deletedAt: t0 - day,
1697 current: false,
1698 open: false,
1699 scope: "global",
1700 topicId: "topic_product",
1701 topicTitle: t("mock.trashGlobalProductTitle"),
1702 recovered: true,
1703 recoveryCopy: true,
1704 },
1705 ];
1706 if (freshMock) {
1707 sessions.splice(0);
1708 trashedSessions.splice(0);
1709 }
1710 // Mutable settings so the Settings panel's edits are observable in browser dev.
1711 const settings: SettingsView = {
1712 modelSettingsFingerprint: "mock-model-settings-0",
1713 defaultModel: "deepseek",
1714 plannerModel: "",
1715 visionModel: "",
1716 webSearchModel: "auto",
1717 webSearchModels: ["deepseek/deepseek-v4-flash", "deepseek/deepseek-v4-pro"],
1718 webSearchModelStatus: "ready",
1719 subagentModel: "",
1720 subagentEffort: "",
1721 autoPlan: "off",
1722 providers: [
1723 { name: "deepseek", builtIn: true, added: deepSeekUpgradeMock, kind: "openai", baseUrl: "https://api.deepseek.com", modelsUrl: "", models: ["deepseek-v4-flash"], visionModels: [], visionModelsConfigured: false, default: "deepseek-v4-flash", apiKeyEnv: "DEEPSEEK_API_KEY", headers: deepSeekUpgradeMock ? { "X-Route": "official-custom" } : undefined, keySet: true, balanceUrl: "https://api.deepseek.com/user/balance", contextWindow: 1_000_000, reasoningProtocol: "", thinking: "enabled", webSearch: true, serverWebSearchCapability: true, supportedEfforts: ["disabled", "low", "high", "max"], defaultEffort: "high", recommendedUpgradeAvailable: false },
1724 ],
1725 officialProviders: [
1726 { name: "deepseek", builtIn: true, added: false, kind: "openai", baseUrl: "https://api.deepseek.com", modelsUrl: "", models: ["deepseek-v4-flash", "deepseek-v4-pro"], visionModels: [], visionModelsConfigured: false, default: "deepseek-v4-flash", apiKeyEnv: "DEEPSEEK_API_KEY", keySet: true, balanceUrl: "https://api.deepseek.com/user/balance", contextWindow: 1_000_000, reasoningProtocol: "", thinking: "enabled", webSearch: true, serverWebSearchCapability: true, supportedEfforts: ["disabled", "low", "high", "max"], defaultEffort: "high" },
1727 ],
1728 providerPresets: mockProviderPresetViews(),
1729 permissions: { mode: "ask", allow: ["ls", "read_file"], ask: [], deny: ["Bash(rm:*)"] },
1730 sandbox: { bash: browserPreviewBashSandboxMode(), network: true, workspaceRoot: "", allowWrite: [], effectiveWorkspaceRoot: cwd, effectiveWriteRoots: [cwd], shell: "auto", effectiveShell: browserPreviewEffectiveShell("auto"), resolvedShell: browserPreviewEffectiveShell("auto"), shellReloadRequired: false, ...browserPreviewShellSupport(browserPlatformOverride()) },
1731 network: {
1732 proxyMode: "auto",
1733 proxyUrl: "",
1734 noProxy: "",
1735 proxy: { type: "socks5", server: "127.0.0.1", port: 7890, username: "", password: "" },
1736 },
1737 agent: { temperature: 0.2, maxSteps: 0, plannerMaxSteps: 0, maxSubagentDepth: 2, maxSubagentConcurrency: 6, maxParallelWriters: 3, systemPrompt: "You are Reasonix, a coding agent.", reasoningLanguage: "auto", compactRatio: 0.8 },
1738 bot: {
1739 enabled: !freshMock,
1740 model: "",
1741 toolApprovalMode: "ask",
1742 maxSteps: 0,
1743 debounceMs: 1500,
1744 queueMode: "steer",
1745 queueCap: 20,
1746 queueDrop: "summarize",
1747 ignoreSelfMessages: true,
1748 selfUserIds: {
1749 qq: [],
1750 feishu: [],
1751 weixin: [],
1752 dingtalk: [],
1753 },
1754 control: {
1755 enabled: false,
1756 addr: "127.0.0.1:37913",
1757 tokenEnv: "REASONIX_BOT_CONTROL_TOKEN",
1758 },
1759 pairing: {
1760 enabled: true,
1761 requestTtlMinutes: 60,
1762 maxPendingPerPlatform: 3,
1763 },
1764 routes: [],
1765 allowlist: {
1766 enabled: true,
1767 allowAll: false,
1768 qqUsers: [],
1769 feishuUsers: freshMock ? [] : ["ou_mock_user_001"],
1770 weixinUsers: freshMock ? [] : ["wxid_mock_user_001"],
1771 qqApprovers: [],
1772 feishuApprovers: [],
1773 weixinApprovers: [],
1774 qqAdmins: [],
1775 feishuAdmins: [],
1776 weixinAdmins: [],
1777 qqGroups: [],
1778 feishuGroups: [],
1779 weixinGroups: [],
1780 dingtalkUsers: [],
1781 dingtalkApprovers: [],
1782 dingtalkAdmins: [],
1783 dingtalkGroups: [],
1784 },
1785 qq: { enabled: false, appId: "", appSecretEnv: "QQ_BOT_APP_SECRET", secretSet: false, sandbox: false, model: "", toolApprovalMode: "ask", workspaceRoot: "", access: { enabled: true, allowAll: false, pairingEnabled: true, users: [], groups: [], approvers: [], admins: [] } },
1786 feishu: {
1787 enabled: false,
1788 domain: "feishu",
1789 appId: "",
1790 appSecretEnv: "FEISHU_BOT_APP_SECRET",
1791 secretSet: false,
1792 verificationToken: "",
1793 mode: "webhook",
1794 webhookPort: 8080,
1795 requireMention: true,
1796 },
1797 weixin: {
1798 enabled: false,
1799 accountId: "default",
1800 tokenEnv: "WEIXIN_BOT_TOKEN",
1801 tokenSet: false,
1802 apiBase: "https://ilinkai.weixin.qq.com",
1803 },
1804 dingtalk: {
1805 enabled: false,
1806 clientId: "",
1807 clientSecretEnv: "DINGTALK_CLIENT_SECRET",
1808 secretSet: false,
1809 botName: "",
1810 requireMention: true,
1811 model: "",
1812 toolApprovalMode: "",
1813 workspaceRoot: "",
1814 access: { enabled: true, allowAll: false, pairingEnabled: true, users: [], groups: [], approvers: [], admins: [] },
1815 },
1816 connections: freshMock ? [] : [
1817 {
1818 id: "mock-lark-kun",
1819 provider: "feishu",
1820 domain: "lark",
1821 label: "kun",
1822 enabled: true,
1823 status: "connected",
1824 model: "",
1825 toolApprovalMode: "",
1826 workspaceRoot: "",
1827 access: { enabled: true, allowAll: false, pairingEnabled: true, users: ["ou_mock_user_001"], groups: [], approvers: [], admins: [] },
1828 credential: {
1829 appId: "cli_mock_lark",
1830 appSecretEnv: "FEISHU_BOT_APP_SECRET",
1831 accountId: "",
1832 tokenEnv: "",
1833 secretSet: true,
1834 },
1835 sessionMappings: [
1836 {
1837 remoteId: "ou_mock_user_001",
1838 sessionId: "topic:topic_product",
1839 sessionSource: "",
1840 chatType: "",
1841 userId: "",
1842 threadId: "",
1843 scope: "global",
1844 workspaceRoot: "",
1845 updatedAt: new Date(Date.now() - 4 * 60_000).toISOString(),
1846 },
1847 ],
1848 lastError: "",
1849 createdAt: new Date(Date.now() - 86_400_000).toISOString(),
1850 updatedAt: new Date(Date.now() - 4 * 60_000).toISOString(),
1851 },
1852 {
1853 id: "mock-weixin-kun",
1854 provider: "weixin",
1855 domain: "weixin",
1856 label: "kun",
1857 enabled: true,
1858 status: "connected",
1859 model: "",
1860 toolApprovalMode: "",
1861 workspaceRoot: "",
1862 access: { enabled: true, allowAll: false, pairingEnabled: true, users: ["wxid_mock_user_001"], groups: [], approvers: [], admins: [] },
1863 credential: {
1864 appId: "",
1865 appSecretEnv: "",
1866 accountId: "default",
1867 tokenEnv: "WEIXIN_BOT_TOKEN",
1868 secretSet: true,
1869 },
1870 sessionMappings: [
1871 {
1872 remoteId: "wxid_mock_user_001",
1873 sessionId: "topic:topic_ai",
1874 sessionSource: "",
1875 chatType: "",
1876 userId: "",
1877 threadId: "",
1878 scope: "global",
1879 workspaceRoot: "",
1880 updatedAt: new Date(Date.now() - 12 * 60_000).toISOString(),
1881 },
1882 ],
1883 lastError: "",
1884 createdAt: new Date(Date.now() - 86_400_000).toISOString(),
1885 updatedAt: new Date(Date.now() - 12 * 60_000).toISOString(),
1886 },
1887 ],
1888 },
1889 desktopLanguage: "",
1890 desktopCurrency: "",
1891 desktopTheme: "auto",
1892 desktopThemeStyle: "graphite",
1893 desktopTerminalTheme: "auto",
1894 conversationWidth: "standard",
1895 closeBehavior: "background",
1896 displayMode: "standard", sessionExperience: "standard", reasoningDisplayMode: "auto", reasoningDisplayModeExplicit: false,
1897 statusBarStyle: "icon",
1898 statusBarItems: [...DEFAULT_STATUS_BAR_ITEMS],
1899 defaultToolApprovalMode: "workspace-write",
1900 checkUpdates: true,
1901 updaterEnabled: true,
1902 updateChannel: "stable",
1903 telemetry: true,
1904 metrics: true,
1905 configPath: "~/.reasonix/config.toml",
1906 shadowedByPath: "~/projects/reasonix/reasonix.toml",
1907 providerKinds: ["openai", "anthropic", "responses"],
1908 autoApproveTools: false,
1909 bypass: false,
1910 };
1911 const hookEvents = ["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop", "PostLLMCall", "SessionStart", "SessionEnd", "SubagentStop", "Notification", "PreCompact"];
1912 const hookSettings: Record<string, HooksSettingsView> = {
1913 global: {
1914 scope: "global",
1915 path: "~/.reasonix/settings.json",
1916 projectRoot: "",
1917 trusted: true,
1918 events: hookEvents,
1919 hooks: [
1920 { event: "Stop", command: "echo turn done", description: "Notify after each turn" },
1921 ],
1922 },
1923 project: {
1924 scope: "project",
1925 path: "./.reasonix/settings.json",
1926 projectRoot: "/mock/project",
1927 trusted: false,
1928 events: hookEvents,
1929 hooks: [],
1930 },
1931 };
1932 settings.providers = settings.providers.map((provider) =>
1933 provider.apiKeyEnv === "DEEPSEEK_API_KEY" ? { ...provider, keySet: !freshMock } : provider,
1934 );
1935 if (freshMock) {
1936 settings.configPath = "~/.reasonix/config.toml";
1937 settings.shadowedByPath = "";
1938 }
1939 const mockNow = Date.now();
1940 const mockProjectTree: ProjectNode[] = freshMock ? [] : benchMock ? [
1941 {
1942 key: "project_~/projects/reasonix",
1943 kind: "project",
1944 label: "reasonix",
1945 root: "~/projects/reasonix",
1946 projectColor: "purple",
1947 children: [
1948 { key: "topic_bench_markdown", kind: "topic", label: "● bench:markdown-46t", root: "~/projects/reasonix", topicId: "topic_bench_markdown", projectColor: "purple", turns: 46, lastActivityAt: mockNow - 60_000, open: true },
1949 { key: "topic_bench_tools", kind: "topic", label: "● bench:tools-38t", root: "~/projects/reasonix", topicId: "topic_bench_tools", projectColor: "blue", turns: 38, lastActivityAt: mockNow - 120_000, open: true },
1950 { key: "topic_bench_small", kind: "topic", label: "bench:small-6t", root: "~/projects/reasonix", topicId: "topic_bench_small", projectColor: "green", turns: 6, lastActivityAt: mockNow - 180_000 },
1951 { key: "topic_bench_giant_turn", kind: "topic", label: "bench:giant-turn", root: "~/projects/reasonix", topicId: "topic_bench_giant_turn", projectColor: "amber", turns: 1, lastActivityAt: mockNow - 240_000 },
1952 { key: "topic_bench_windowed", kind: "topic", label: "bench:windowed-1000t", root: "~/projects/reasonix", topicId: "topic_bench_windowed", projectColor: "blue", turns: 1000, lastActivityAt: mockNow - 270_000 },
1953 { key: "topic_bench_reported_long_turn", kind: "topic", label: "bench:reported-long-turn", root: "~/projects/reasonix", topicId: "topic_bench_reported_long_turn", projectColor: "amber", turns: 1, lastActivityAt: mockNow - 300_000 },
1954 { key: "topic_bench_geometry_contract", kind: "topic", label: "bench:geometry-blocks", root: "~/projects/reasonix", topicId: "topic_bench_geometry_contract", projectColor: "amber", turns: 1, lastActivityAt: mockNow - 330_000 },
1955 { key: "topic_bench_storm", kind: "topic", label: "bench:storm-40t", root: "~/projects/reasonix", topicId: "topic_bench_storm", projectColor: "red", turns: 40, lastActivityAt: mockNow - 360_000 },
1956 { key: "topic_bench_selection_table", kind: "topic", label: "bench:selection-table", root: "~/projects/reasonix", topicId: "topic_bench_selection_table" },
1957 ],
1958 },
1959 ] : [
1960 {
1961 key: "project_~/projects/joyquant-db",
1962 kind: "project",
1963 label: t("mock.projectJoyquantDb"),
1964 root: "~/projects/joyquant-db",
1965 projectColor: "blue",
1966 children: [
1967 { key: "topic_dev_standard", kind: "topic", label: `● ${t("mock.topicDevStandard")}`, root: "~/projects/joyquant-db", topicId: "topic_dev_standard", projectColor: "blue", turns: 18, createdAt: mockNow - 3 * 24 * 60 * 60_000, lastActivityAt: mockNow - 8 * 60_000, open: true, running: runningMock },
1968 { key: "topic_db_maint", kind: "topic", label: t("mock.topicDbMaint"), root: "~/projects/joyquant-db", topicId: "topic_db_maint", projectColor: "blue", turns: 7, createdAt: mockNow - 2 * 24 * 60 * 60_000, lastActivityAt: mockNow - 2 * 60 * 60_000 },
1969 { key: "topic_env", kind: "topic", label: t("mock.topicEnv"), root: "~/projects/joyquant-db", topicId: "topic_env", projectColor: "blue", turns: 3, createdAt: mockNow - 24 * 60 * 60_000, lastActivityAt: mockNow - 26 * 60 * 60_000 },
1970 ],
1971 },
1972 {
1973 key: "project_~/projects/joyquant-sys",
1974 kind: "project",
1975 label: t("mock.projectJoyquantSys"),
1976 root: "~/projects/joyquant-sys",
1977 projectColor: "purple",
1978 children: [
1979 { key: "topic_p3b_pd", kind: "topic", label: `● ${t("mock.topicP3b")}`, root: "~/projects/joyquant-sys", topicId: "topic_p3b_pd", projectColor: "purple", turns: 11, lastActivityAt: mockNow - 3 * 24 * 60 * 60_000, status: runningMock ? "streaming" : undefined },
1980 { key: "topic_p3a_pd", kind: "topic", label: t("mock.topicP3a"), root: "~/projects/joyquant-sys", topicId: "topic_p3a_pd", projectColor: "purple", turns: 9, lastActivityAt: mockNow - 4 * 24 * 60 * 60_000, status: runningMock ? "thinking" : undefined },
1981 { key: "topic_hotfix", kind: "topic", label: t("mock.topicHotfix"), root: "~/projects/joyquant-sys", topicId: "topic_hotfix", projectColor: "purple", turns: 4, lastActivityAt: mockNow - 5 * 24 * 60 * 60_000, status: runningMock ? "thinking" : undefined },
1982 { key: "topic_sys_coord", kind: "topic", label: t("mock.topicSysCoord"), root: "~/projects/joyquant-sys", topicId: "topic_sys_coord", projectColor: "purple", turns: 14, lastActivityAt: mockNow - 6 * 24 * 60 * 60_000, status: runningMock ? "waiting_confirmation" : undefined },
1983 { key: "topic_sys_standard", kind: "topic", label: t("mock.topicSysStandard"), root: "~/projects/joyquant-sys", topicId: "topic_sys_standard", projectColor: "purple", turns: 6, lastActivityAt: mockNow - 7 * 24 * 60 * 60_000, status: "paused" },
1984 { key: "topic_sys_exception", kind: "topic", label: t("mock.topicSysException"), root: "~/projects/joyquant-sys", topicId: "topic_sys_exception", projectColor: "purple", turns: 2, lastActivityAt: mockNow - 8 * 24 * 60 * 60_000, status: "error" },
1985 ],
1986 },
1987 {
1988 key: "global_folder",
1989 kind: "global_folder",
1990 label: "Global",
1991 root: globalWorkspaceRoot,
1992 children: [
1993 { key: "global_topic_product", kind: "global_topic", label: t("mock.topicProduct"), topicId: "topic_product", turns: 5, lastActivityAt: mockNow - 8 * 24 * 60 * 60_000 },
1994 { key: "global_topic_ai", kind: "global_topic", label: t("mock.topicAi"), topicId: "topic_ai", turns: 8, lastActivityAt: mockNow - 10 * 24 * 60 * 60_000 },
1995 { key: "global_topic_lab", kind: "global_topic", label: t("mock.topicLab"), topicId: "topic_lab", turns: 2, lastActivityAt: mockNow - 12 * 24 * 60 * 60_000 },
1996 ],
1997 },
1998 ];
1999 const ensureMockGlobalFolder = (): ProjectNode => {
2000 let node = mockProjectTree.find((item) => item.kind === "global_folder");
2001 if (!node) {
2002 node = {
2003 key: "global_folder",
2004 kind: "global_folder",
2005 label: "Global",
2006 root: globalWorkspaceRoot,
2007 children: [],
2008 };
2009 mockProjectTree.push(node);
2010 }
2011 return node;
2012 };
2013 const mockProjectTreeForDisplay = () => {
2014 const pinnedProjects = mockProjectTree.filter((node) => node.kind === "project" && node.pinned);
2015 if (pinnedProjects.length === 0) return mockProjectTree;
2016 const rest = mockProjectTree.filter((node) => !(node.kind === "project" && node.pinned));
2017 return [...pinnedProjects, ...rest];
2018 };
2019 const cloneProjectTree = () => {
2020 if (mockProjectTree.length === 0) ensureMockGlobalFolder();
2021 return remoteProjects.appendToTree(JSON.parse(JSON.stringify(mockProjectTreeForDisplay())) as ProjectNode[]);
2022 };
2023 const projectChildren = (node: ProjectNode): ProjectNode[] => Array.isArray(node.children) ? node.children : [];
2024 const findMockTopic = (topicId: string): ProjectNode | null => {
2025 for (const parent of mockProjectTree) {
2026 const found = projectChildren(parent).find((child) => child.topicId === topicId);
2027 if (found) return found;
2028 }
2029 return null;
2030 };
2031 const setMockTopicPinned = (topicId: string, pinned: boolean) => {
2032 for (const parent of mockProjectTree) {
2033 const children = projectChildren(parent);
2034 const index = children.findIndex((child) => child.topicId === topicId);
2035 if (index < 0) continue;
2036 const topic = { ...children[index], pinned: pinned || undefined };
2037 if (!pinned) {
2038 parent.children = children.map((child, i) => (i === index ? topic : child));
2039 return;
2040 }
2041 const remaining = children.filter((_, i) => i !== index);
2042 parent.children = [topic, ...remaining];
2043 return;
2044 }
2045 };
2046 const setMockProjectPinned = (workspaceRoot: string, pinned: boolean) => {
2047 const index = mockProjectTree.findIndex((node) => node.kind === "project" && node.root === workspaceRoot);
2048 if (index < 0) return;
2049 mockProjectTree[index] = { ...mockProjectTree[index], pinned: pinned || undefined };
2050 };
2051 const deleteMockTopic = (topicId: string) => {
2052 for (const parent of mockProjectTree) {
2053 parent.children = projectChildren(parent).filter((child) => child.topicId !== topicId);
2054 }
2055 };
2056 const topicLabel = (topicId: string, fallback: string) => (findMockTopic(topicId)?.label || fallback).replace(/^●\s*/, "");
2057 const mockTopicStatus = (topicId: string) => findMockTopic(topicId)?.status ?? "";
2058 const mockTopicIsRunning = (topicId: string) => {
2059 const status = mockTopicStatus(topicId);
2060 return status === "streaming" || status === "thinking" || status === "waiting_confirmation";
2061 };
2062 const mockTopicIsBlank = (topicId: string) => {
2063 const topic = findMockTopic(topicId);
2064 return Boolean(topic && topic.label === t("mock.newSession") && !topic.turns && !topic.lastActivityAt && !topic.status);
2065 };
2066 const mockTopicRunsInScenario = (topicId: string) => runningMock && mockTopicIsRunning(topicId);
2067 // Benchmark fixtures (?mock=bench) live in a lazily imported module: the
2068 // generators build ~1MiB of mock content and must stay out of the eager
2069 // bundle (initial-chunk gzip budget). See bridgeBenchFixtures.ts.
2070 const benchFixturesPromise = benchMock ? import("./bridgeBenchFixtures") : null;
2071 const mockHistoryPage = (messages: HistoryMessage[], beforeTurn = 0, limit = 60): HistoryPage => {
2072 const totalTurns = messages.reduce((count, message) => count + (message.role === "user" ? 1 : 0), 0);
2073 const safeLimit = Math.max(1, Math.min(200, Math.floor(limit || 60)));
2074 const endTurn = beforeTurn > 0 && beforeTurn <= totalTurns ? beforeTurn : totalTurns;
2075 const startTurn = Math.max(0, endTurn - safeLimit);
2076 let turn = -1;
2077 const pageMessages = messages.filter((message) => {
2078 if (message.role === "user") turn += 1;
2079 if (turn < 0) return startTurn === 0;
2080 return turn >= startTurn && turn < endTurn;
2081 });
2082 return { messages: pageMessages, startTurn, endTurn, totalTurns, hasOlder: startTurn > 0 };
2083 };
2084 const mockRuntimeInjected = new Set<string>();
2085 const queueMockTopicRuntime = (tab: TabMeta) => {
2086 if (!runningMock) return;
2087 const status = mockTopicStatus(tab.topicId);
2088 if (status !== "streaming" && status !== "thinking" && status !== "waiting_confirmation") return;
2089 const key = `${tab.id}:${tab.topicId}:${status}`;
2090 if (mockRuntimeInjected.has(key)) return;
2091 mockRuntimeInjected.add(key);
2092 window.setTimeout(() => {
2093 void withMockTabScope(tab.id, async () => {
2094 emitMockTurnStarted();
2095 await delay(120);
2096 if (tab.topicId === "topic_p3b_pd") {
2097 const text = "我会先把范围拆成三层:目标、依赖、风险。当前已经确认 p3b 的交付边界,接下来补充每个模块的验收口径...";
2098 for (const ch of text) {
2099 emit({ kind: "text", text: ch });
2100 await delay(5);
2101 }
2102 return;
2103 }
2104 if (tab.topicId === "topic_p3a_pd") {
2105 emit({ kind: "reasoning", text: "我正在对比 p3a 和 p3b 的差异:先看约束,再看变更风险,最后判断是否需要拆成独立任务。\n\n" });
2106 await delay(220);
2107 emit({ kind: "reasoning", text: "当前倾向:先保留 p3a 的兼容路径,不急于删除旧逻辑。" });
2108 return;
2109 }
2110 if (tab.topicId === "topic_hotfix") {
2111 const id = "mock-hotfix-shell";
2112 emit({ kind: "tool_dispatch", tool: { id, name: "bash", args: JSON.stringify({ command: "git status --short && npm test" }), readOnly: true } });
2113 await delay(180);
2114 emit({ kind: "tool_progress", tool: { id, name: "bash", readOnly: true, output: "$ git status --short\n M internal/sys/runner.go\n\n$ npm test\nrunning targeted regression tests...\n" } });
2115 return;
2116 }
2117 if (tab.topicId === "topic_sys_coord") {
2118 pendingApprovalPreview = true;
2119 pendingApprovalPreviewPrompt = { id: "mock-sys-confirm", tool: "bash" };
2120 emit({ kind: "reasoning", text: "我已经准备好执行同步脚本,但这个操作会影响本地 workspace,需要用户确认。" });
2121 await delay(160);
2122 emitMockPrompt({
2123 kind: "approval_request",
2124 approval: {
2125 id: "mock-sys-confirm",
2126 tool: "bash",
2127 subject: "npm run sync:joyquant-sys\n\n该命令会同步 SYS 项目配置并刷新本地缓存。",
2128 },
2129 });
2130 }
2131 });
2132 }, 180);
2133 };
2134 const setMockActiveTab = (tabId: string) => {
2135 mockTabs = mockTabs.map((tab) => ({ ...tab, active: tab.id === tabId }));
2136 };
2137 // Single-surface prunes stash removed tabs so a later re-activation restores
2138 // the SAME tab identity (the real backend "opens or reuses" the topic's
2139 // tab), keeping the transcript store's (tabId, sessionPath) cache warm.
2140 const mockPrunedTabs = new Map<string, TabMeta>();
2141 const mockTabGraveyardKey = (tab: Pick<TabMeta, "scope" | "workspaceRoot" | "topicId">) =>
2142 `${tab.scope}:${tab.workspaceRoot}:${tab.topicId}`;
2143 const pruneMockTabsTo = (keepTabId: string) => {
2144 for (const tab of mockTabs) {
2145 if (tab.id !== keepTabId) mockPrunedTabs.set(mockTabGraveyardKey(tab), tab);
2146 }
2147 mockTabs = mockTabs.filter((item) => item.id === keepTabId).map((item) => ({ ...item, active: true }));
2148 };
2149 const restoreMockPrunedTab = (scope: string, workspaceRoot: string, topicId: string): TabMeta | undefined => {
2150 const key = mockTabGraveyardKey({ scope, workspaceRoot, topicId });
2151 const tab = mockPrunedTabs.get(key);
2152 if (!tab) return undefined;
2153 mockPrunedTabs.delete(key);
2154 return tab;
2155 };
2156 const currentMockTurnTabId = () => mockScopedTabId || mockTabs.find((tab) => tab.active)?.id;
2157 const setMockTabRunning = (tabId: string | undefined, running: boolean) => {
2158 if (!tabId) return;
2159 mockTabs = mockTabs.map((tab) => (tab.id === tabId ? { ...tab, running } : tab));
2160 };
2161 const mockInteractions = createBrowserMockInteractionIdentity({ emit, currentTabId: currentMockTurnTabId, setRunning: setMockTabRunning });
2162 const { emitPrompt: emitMockPrompt, turnStarted: emitMockTurnStarted, turnDone: emitMockTurnDone } = mockInteractions;
2163 // Fresh user decisions never auto-allow on a posture switch (mirrors the
2164 // backend's requiresFreshApprovalTool set).
2165 const mockFreshApprovalTools = new Set(["exit_plan_mode", "sandbox_escape", "memory_remember", "memory_forget", "managed_config_write"]);
2166 // Mirrors the backend drain contract for the mode-switch bindings: returns
2167 // the prompt ids the new posture auto-allowed; fresh prompts stay pending.
2168 const drainMockApprovalPreviews = (toolApprovalMode: string): string[] => {
2169 const preset = normalizeToolApprovalMode(toolApprovalMode);
2170 if (preset !== "workspace-write" && preset !== "danger-full-access") return [];
2171 const prompt = pendingApprovalPreviewPrompt;
2172 if (!pendingApprovalPreview || !prompt || mockFreshApprovalTools.has(prompt.tool)) return [];
2173 pendingApprovalPreview = false;
2174 pendingApprovalPreviewPrompt = undefined;
2175 emit({ kind: "message", text: `approval preview auto-allowed (${toolApprovalMode})` });
2176 emitMockTurnDone();
2177 return [prompt.id];
2178 };
2179 let mockTabs: TabMeta[] = benchMock ? [
2180 // Phase F benchmark scenario: the two heaviest sessions pre-opened, the
2181 // markdown-heavy one active (cold open renders the 500KiB answer).
2182 {
2183 id: "tab_bench_markdown",
2184 scope: "project",
2185 workspaceRoot: "~/projects/reasonix",
2186 workspaceName: "reasonix",
2187 workspacePath: "~/projects/reasonix",
2188 gitBranch: "bench",
2189 topicId: "topic_bench_markdown",
2190 topicTitle: "bench:markdown-46t",
2191 projectColor: "purple",
2192 label: "DeepSeek-R1",
2193 ready: true,
2194 running: false,
2195 mode: "normal",
2196 collaborationMode: "normal",
2197 toolApprovalMode: "ask",
2198 tokenMode: "full",
2199 active: true,
2200 cwd: "~/projects/reasonix",
2201 },
2202 {
2203 id: "tab_bench_tools",
2204 scope: "project",
2205 workspaceRoot: "~/projects/reasonix",
2206 workspaceName: "reasonix",
2207 workspacePath: "~/projects/reasonix",
2208 gitBranch: "bench",
2209 topicId: "topic_bench_tools",
2210 topicTitle: "bench:tools-38t",
2211 projectColor: "blue",
2212 label: "DeepSeek-R1",
2213 ready: true,
2214 running: false,
2215 mode: "normal",
2216 collaborationMode: "normal",
2217 toolApprovalMode: "ask",
2218 tokenMode: "full",
2219 active: false,
2220 cwd: "~/projects/reasonix",
2221 },
2222 ] : noticePreviewMock ? [
2223 {
2224 id: "tab_notice_preview",
2225 scope: "project",
2226 workspaceRoot: "~/projects/reasonix",
2227 workspaceName: "reasonix",
2228 workspacePath: "~/projects/reasonix",
2229 gitBranch: "codex/compact-chat-notices-i18n",
2230 topicId: "topic_notice_preview",
2231 topicTitle: "Compact notice preview",
2232 projectColor: "green",
2233 label: "DeepSeek-R1",
2234 ready: true,
2235 running: false,
2236 mode: "normal",
2237 collaborationMode: "normal",
2238 toolApprovalMode: "ask",
2239 tokenMode: "full",
2240 active: true,
2241 cwd: "~/projects/reasonix",
2242 },
2243 ] : freshMock ? [
2244 {
2245 id: "tab_global",
2246 scope: "global",
2247 workspaceRoot: globalWorkspaceRoot,
2248 workspaceName: "Global",
2249 workspacePath: globalWorkspaceRoot,
2250 topicId: "",
2251 topicTitle: "Global",
2252 label: "DeepSeek-R1",
2253 ready: true,
2254 running: false,
2255 mode: "normal",
2256 collaborationMode: "normal",
2257 toolApprovalMode: "ask",
2258 tokenMode: "full",
2259 active: true,
2260 cwd: globalWorkspaceRoot,
2261 },
2262 ] : [
2263 {
2264 id: "tab_joyquant_db",
2265 scope: "project",
2266 workspaceRoot: "~/projects/joyquant-db",
2267 workspaceName: "joyquant-db",
2268 workspacePath: "~/projects/joyquant-db",
2269 gitBranch: "main",
2270 topicId: "topic_dev_standard",
2271 topicTitle: t("mock.trashDevStandardTitle"),
2272 projectColor: "blue",
2273 label: "DeepSeek-R1",
2274 ready: true,
2275 running: false,
2276 mode: "normal",
2277 collaborationMode: "normal",
2278 toolApprovalMode: "ask",
2279 tokenMode: "full",
2280 active: !guidanceMock,
2281 cwd: "~/projects/joyquant-db",
2282 },
2283 {
2284 id: "tab_joyquant_sys",
2285 scope: "project",
2286 workspaceRoot: "~/projects/joyquant-sys",
2287 workspaceName: "joyquant-sys",
2288 workspacePath: "~/projects/joyquant-sys",
2289 gitBranch: "feature/p3b",
2290 topicId: "topic_p3b_pd",
2291 topicTitle: "p3b P&D",
2292 projectColor: "purple",
2293 label: "DeepSeek-R1",
2294 ready: true,
2295 running: runningMock && mockTopicIsRunning("topic_p3b_pd"),
2296 mode: "normal",
2297 collaborationMode: "normal",
2298 toolApprovalMode: "ask",
2299 tokenMode: "full",
2300 active: guidanceMock,
2301 cwd: "~/projects/joyquant-sys",
2302 },
2303 {
2304 id: "tab_global",
2305 scope: "global",
2306 workspaceRoot: globalWorkspaceRoot,
2307 workspaceName: "Global",
2308 workspacePath: globalWorkspaceRoot,
2309 topicId: "topic_global",
2310 topicTitle: "Global",
2311 label: "DeepSeek-R1",
2312 ready: true,
2313 running: false,
2314 mode: "normal",
2315 collaborationMode: "normal",
2316 toolApprovalMode: "ask",
2317 tokenMode: "full",
2318 active: false,
2319 cwd: globalWorkspaceRoot,
2320 },
2321 ];
2322 if (sandboxEscapeMock) {
2323 window.setTimeout(() => {
2324 if (pendingApprovalPreview) return;
2325 pendingApprovalPreview = true;
2326 pendingApprovalPreviewPrompt = { id: "mock-sandbox-escape-preview", tool: "sandbox_escape" };
2327 emitMockTurnStarted();
2328 emit({ kind: "reasoning", text: t("mock.sandboxEscapeReasoning") });
2329 emitMockPrompt({
2330 kind: "approval_request",
2331 approval: {
2332 id: "mock-sandbox-escape-preview",
2333 tool: "sandbox_escape",
2334 subject: t("mock.sandboxEscapeSubject"),
2335 reason: t("mock.sandboxEscapeReason"),
2336 },
2337 });
2338 }, 800);
2339 }
2340 const mockModelCatalog = [
2341 { ref: "deepseek/deepseek-v4-flash", provider: "deepseek", model: "deepseek-v4-flash" },
2342 { ref: "deepseek/deepseek-v4-pro", provider: "deepseek", model: "deepseek-v4-pro" },
2343 ];
2344 const defaultMockModelRef = mockModelCatalog[0].ref;
2345 const mockModelRef = (name: string): string => {
2346 const trimmed = name.trim();
2347 if (!trimmed || trimmed === "DeepSeek-R1") return defaultMockModelRef;
2348 const exact = mockModelCatalog.find((model) => model.ref === trimmed);
2349 if (exact) return exact.ref;
2350 const byModel = mockModelCatalog.find((model) => model.model === trimmed);
2351 return byModel?.ref ?? trimmed;
2352 };
2353 const mockModelLabel = (ref: string): string => mockModelCatalog.find((model) => model.ref === mockModelRef(ref))?.model ?? ref.split("/").pop() ?? ref;
2354 const mockTabModelRef = (tab?: TabMeta): string => mockModelRef(tab?.label ?? "");
2355 let mockTerminalSessions: TerminalSessionView[] = [];
2356 const mockTerminalOutput = new Map<string, string>();
2357 const mockTerminalTabIDs = new Map<string, string>();
2358 const mockTerminalBytes = (text: string): string => {
2359 if (typeof btoa === "function") return btoa(unescape(encodeURIComponent(text)));
2360 return "";
2361 };
2362 const setMockTabModel = (tabID: string | undefined, name: string) => {
2363 const ref = mockModelRef(name);
2364 const label = mockModelLabel(ref);
2365 let applied = false;
2366 mockTabs = mockTabs.map((tab) => {
2367 const match = tabID ? tab.id === tabID : tab.active;
2368 if (!match) return tab;
2369 applied = true;
2370 return { ...tab, label };
2371 });
2372 if (!applied && mockTabs.length > 0) {
2373 mockTabs = mockTabs.map((tab, index) => (index === 0 ? { ...tab, label } : tab));
2374 }
2375 };
2376 const mockArchivedSessionIDs = new Set<string>();
2377 const mockPurgedSessionIDs = new Set<string>();
2378 const mockSessionIDForNode = (node: ProjectNode) => (node.topicId || node.key || "mock-session").replace(/[^a-zA-Z0-9._-]/g, "-");
2379 const mockWorkspaceID = (node: ProjectNode) => node.kind === "global_folder" ? "global" : `project-${(node.root || node.key).replace(/[^a-zA-Z0-9._-]/g, "-")}`;
2380 const mockWorkspaceSnapshot = (): WorkspaceSnapshot => ({
2381 generation: 1,
2382 workspaces: mockProjectTreeForDisplay().filter((node) => node.kind === "project" || node.kind === "global_folder").map((node) => ({
2383 id: mockWorkspaceID(node), root: node.root || "", title: node.label,
2384 sessionIds: projectChildren(node).map(mockSessionIDForNode), visible: true, createdAt: 0, updatedAt: 0,
2385 })),
2386 archivedSessionIds: [...mockArchivedSessionIDs], pendingCreates: [],
2387 });
2388 return { ...({} as AttachmentBindings),
2389 ...makeLazySessionUIMock(async (scope, root, id) => {
2390 const tab = { ...mockTabs[0], id: `tab-${id}`, topicId: id, scope, workspaceRoot: root,
2391 sessionId: id, session: { hostId: "local", sessionId: id }, ready: true, active: false, running: false,
2392 sessionPath: `session-id:${id}`, label: settings.defaultModel || "deepseek/deepseek-chat", topicTitle: "New conversation" };
2393 mockTabs = [...mockTabs, tab];
2394 let parent = scope === "global" ? ensureMockGlobalFolder() : mockProjectTree.find(node => node.kind === "project" && node.root === root);
2395 if (!parent) { parent = { key:`project_${root}`, kind:"project", root, label:root, children:[] }; mockProjectTree.push(parent); }
2396 parent.children = [...(parent.children || []), { key:`session_${id}`,kind:"session",root,session:{hostId:"local",sessionId:id},topicId:id,label:"New conversation",sessionPath:`session-id:${id}`,open:true,turns:0 }];
2397 notifyMockProjectTreeChanged();
2398 }),
2399 ...makeLazyPreviousDraftMock(),
2400 ...makeMockSessionExportBindings(),
2401 ...makeMockSessionCatalogBindings(cloneProjectTree),
2402 ...makeMockBlankProjectBindings(),
2403 async GetWorkspaceSnapshot() { return mockWorkspaceSnapshot(); },
2404 async GetLegacyEmptySessionCleanupStatus() {
2405 return { version: 1, state: "complete", removed: 0, pending: 0, busy: 0, unknown: 0, protected: 0, hasContent: 0, items: [] };
2406 },
2407 async RetryLegacyEmptySessionCleanup() {
2408 throw new Error("Automatic empty-session cleanup has been retired");
2409 },
2410 ...makeMockSessionLifecycleBindings(mockWorkspaceSnapshot, mockArchivedSessionIDs, mockPurgedSessionIDs, notifyMockProjectTreeChanged, mockProjectTree),
2411 async CreateSession(_workspaceId: string) { return { hostId: "local", sessionId: `mock-${Date.now()}` }; },
2412 async ForkSession(_ref: SessionRef, _turnBoundary: string) { return { hostId: "local", sessionId: `mock-fork-${Date.now()}` }; },
2413 async ForkSessionTarget(_selector: SessionSelector, _turnBoundary: string) { return { hostId: "local", sessionId: `mock-fork-${Date.now()}` }; },
2414 async GetSessionActivityBaseline(selector: SessionSelector) {
2415 return { ref: selector.ref ?? { hostId: "local", sessionId: "" }, resultSequence: 0, eventVersion: "", lifecycleGeneration: 0, complete: false };
2416 },
2417 async CopySessionTarget(_selector: SessionSelector, operationId: string): Promise<SessionCreationResult> {
2418 return {
2419 ref: { hostId: "local", sessionId: `mock-copy-${operationId || Date.now()}` },
2420 operationId: operationId || `mock-copy-operation-${Date.now()}`,
2421 committed: true,
2422 };
2423 },
2424 async HistorySliceForTarget(_selector: SessionSelector, _request: HistorySliceRequest): Promise<HistorySlice> {
2425 return { entries: [], nextCursor: "", hasOlder: false, totalTurns: 0, startTurn: 0, endTurn: 0, stale: false, revision: 0 };
2426 },
2427 async HistoryContentForTarget(_selector: SessionSelector, ref: HistoryContentRef, chunkIndex: number): Promise<HistoryContentChunk> {
2428 return {
2429 entryId: ref.entryId, field: ref.field, chunk: Math.max(0, chunkIndex),
2430 chunks: 1, data: "", done: true, stale: false,
2431 };
2432 },
2433 async SearchHistoryContentForTarget(_selector: SessionSelector, _query: string, _cursor: string, _limit: number): Promise<HistorySearchPage> {
2434 return {
2435 items: [], nextCursor: "", revision: 0, partial: false, staleCursor: false,
2436 status: { state: "ready", mode: "incremental", total: 0, indexed: 0, pending: 0, failed: 0, revision: 0 },
2437 };
2438 },
2439 async SessionHistoryPageForTarget(_selector: SessionSelector, _cursor: string, _limit: number): Promise<MessageHistoryPage> {
2440 return { messages: [], snapshotSequence: 0, coverageSequence: 0, status: "ready", totalTurns: 0, generation: "mock", hasMore: false };
2441 },
2442 async SessionHistoryContentForTarget(_selector: SessionSelector, ref: SessionContentRef, offset: number): Promise<SessionHistoryContentChunk> {
2443 return { data: "", nextOffset: Math.min(Math.max(0, offset), ref.bytes), done: offset >= ref.bytes };
2444 },
2445 async LocateSessionMessageForTarget(_selector: SessionSelector, messageId: string, snapshot: number): Promise<MessageLocation> {
2446 return { messageId, snapshotSequence: snapshot, coverageSequence: snapshot, status: "ready", position: 0, visibleTurn: 0 };
2447 },
2448 async SessionMessageFieldForTarget(
2449 _selector: SessionSelector,
2450 messageId: string,
2451 version: number,
2452 field: string,
2453 offset: number,
2454 _length: number,
2455 ): Promise<MessageFieldPage> {
2456 return { status: "ready", messageId, version, field, totalBytes: 0, offset, data: "", nextOffset: offset, encoding: "utf8" };
2457 },
2458 async SearchSessionHistoryForTarget(_selector: SessionSelector, _query: string, _cursor: string, _limit: number): Promise<SearchHistoryPage> {
2459 return { hits: [], snapshotSequence: 0, coverageSequence: 0, status: "ready", hasMore: false };
2460 },
2461 async SessionHistoryWindowForTarget(_selector: SessionSelector, _request: HistoryWindowRequest): Promise<HistoryWindowPage> {
2462 return { messages: [], status: "ready", snapshotSequence: 0, coverageSequence: 0, totalTurns: 0, hasOlder: false, hasNewer: false };
2463 },
2464 async ListWorkspaceSessions(workspaceId: string, query: string, _cursor: string, limit: number, includeArchived: boolean) {
2465 const parent = mockProjectTreeForDisplay().find((node) => mockWorkspaceID(node) === workspaceId);
2466 const needle = query.trim().toLowerCase();
2467 const sessions = projectChildren(parent ?? { key: "", kind: "global_folder", label: "", children: [] }).map((node) => {
2468 const sessionId = mockSessionIDForNode(node), isArchived = mockArchivedSessionIDs.has(sessionId);
2469 return {
2470 ref: { hostId: "local", sessionId }, workspaceId, title: node.label, preview: node.preview || "", turns: node.turns || 0,
2471 createdAt: node.createdAt || 0, updatedAt: node.lastActivityAt || 0, blank: !node.turns && !node.preview,
2472 archived: isArchived, running: Boolean(node.running), metadataStatus: "ready", health: "healthy",
2473 };
2474 }).filter((row) => !mockPurgedSessionIDs.has(row.ref.sessionId) && (includeArchived || !row.archived) && (!needle || `${row.title}\n${row.preview}`.toLowerCase().includes(needle))).slice(0, limit);
2475 return { sessions, registryGeneration: 1 };
2476 },
2477 async OpenSession(ref: SessionRef) {
2478 if (ref.hostId !== "local") throw new Error(`unsupported mock session host: ${ref.hostId}`);
2479 const { rebindMockSessionTab } = await import("./bridgeMockSessionNavigation");
2480 const rebound = rebindMockSessionTab(ref, mockTabs.find((candidate) => candidate.active) ?? mockTabs[0], mockProjectTreeForDisplay(), globalWorkspaceRoot, mockTopicRunsInScenario);
2481 // SessionRef navigation rebinds the existing surface; legacy Topic
2482 // activation swaps tab ids and makes its ready event correctly stale.
2483 pruneMockTabsTo(rebound.id);
2484 mockTabs = [rebound];
2485 emitMockReady(rebound.id);
2486 return this.HistoryPageForTab(rebound.id, 0, 60);
2487 },
2488 async ReadSessionHistory(_ref: SessionRef, _cursor: string, _limit: number) { return { messages: [], startTurn: 0, endTurn: 0, totalTurns: 0, hasOlder: false }; },
2489 async RenameCanonicalSession(_ref: SessionRef, _title: string) {},
2490 async SetSessionPinned(_selector: SessionSelector, _pinned: boolean) { notifyMockProjectTreeChanged(); },
2491 async ArchiveCanonicalSession(ref: SessionRef) { mockArchivedSessionIDs.add(ref.sessionId); notifyMockProjectTreeChanged(); },
2492 async ArchiveSessionTarget(selector: SessionSelector): Promise<SessionMutationResult> {
2493 const node = mockSessionTitleTarget(mockProjectTree, selector);
2494 const targetKey = node ? sessionTitleTarget(node) : selector.sessionPath?.trim() || selector.topicId?.trim() || selector.ref?.sessionId || "";
2495 if (selector.ref?.sessionId) mockArchivedSessionIDs.add(selector.ref.sessionId);
2496 if (selector.sessionPath) await this.DeleteSession(selector.sessionPath);
2497 notifyMockProjectTreeChanged();
2498 return { targetKey, operationId: `mock-archive-${Date.now()}`, committed: true, lifecycleGeneration: 2 };
2499 },
2500 async RestoreCanonicalSession(ref: SessionRef) { mockArchivedSessionIDs.delete(ref.sessionId); notifyMockProjectTreeChanged(); },
2501 async RestoreSessionTarget(selector: SessionSelector): Promise<SessionMutationResult> {
2502 const node = mockSessionTitleTarget(mockProjectTree, selector);
2503 const targetKey = node ? sessionTitleTarget(node) : selector.sessionPath?.trim() || selector.topicId?.trim() || selector.ref?.sessionId || "";
2504 if (selector.ref?.sessionId) mockArchivedSessionIDs.delete(selector.ref.sessionId);
2505 notifyMockProjectTreeChanged();
2506 return { targetKey, operationId: `mock-restore-${Date.now()}`, committed: true, lifecycleGeneration: 3 };
2507 },
2508 async DeleteSessionTarget(selector: SessionSelector): Promise<SessionMutationResult> {
2509 const node = mockSessionTitleTarget(mockProjectTree, selector);
2510 const sessionId = selector.ref?.sessionId || (node ? mockSessionIDForNode(node) : "");
2511 if (sessionId) mockPurgedSessionIDs.add(sessionId);
2512 notifyMockProjectTreeChanged();
2513 return { targetKey: node ? sessionTitleTarget(node) : sessionId, operationId: `mock-delete-${Date.now()}`, committed: true, lifecycleGeneration: 4 };
2514 },
2515 async MoveWorkspaceSession(_workspaceId: string, _sessionId: string, _beforeSessionId: string) {},
2516 async MoveSessionTarget(selector: SessionSelector, _workspaceId: string, _beforeSessionId: string): Promise<SessionMutationResult> {
2517 const node = mockSessionTitleTarget(mockProjectTree, selector);
2518 return { targetKey: node ? sessionTitleTarget(node) : "", operationId: `mock-move-${Date.now()}`, committed: true, lifecycleGeneration: 1 };
2519 },
2520 async RenameWorkspace(_workspaceId: string, _title: string) {},
2521 async SetWorkspaceVisible(_workspaceId: string, _visible: boolean) {},
2522 async MoveWorkspace(_workspaceId: string, _beforeWorkspaceId: string) {},
2523 async GetSessionArchitectureDiagnostics() {
2524 return {
2525 pending_operations: 0, missing_members: 0, identity_mismatches: 0,
2526 source_conflicts: 0, recovery_entries: 0,
2527 session_headers_total: 0, workspace_members_total: 0, unassigned_sessions: 0,
2528 migration_pending: 0, migration_failed: 0, migration_completed: 0,
2529 projection_pending: 0, projection_failed: 0, pending_create_recovered: 0,
2530 prune_blocked_persistence: 0,
2531 };
2532 },
2533 async MinimiseMainWindow() {
2534 console.info("mock MinimiseMainWindow");
2535 },
2536 async ToggleMaximiseMainWindow() {
2537 console.info("mock ToggleMaximiseMainWindow");
2538 },
2539 async IsMainWindowMaximised() {
2540 return false;
2541 },
2542 async CloseMainWindow() {
2543 console.info("mock CloseMainWindow");
2544 },
2545 async Platform() {
2546 const override = browserPlatformOverride();
2547 if (override) return override;
2548 // Mirror the OS the browser dev mock runs on.
2549 const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
2550 if (/Win/i.test(ua)) return "windows";
2551 if (/Mac/i.test(ua)) return "darwin";
2552 return "linux";
2553 },
2554 async Submit(input, submissionID?: string) {
2555 cancelled = false;
2556 emitMockTurnStarted(submissionID);
2557 const trimmedInput = input.trim().toLowerCase();
2558 // Deterministic browser QA for the real recovery/source components.
2559 if (trimmedInput === "/mock-protocol-recovery") {
2560 setMockTabRunning(currentMockTurnTabId(), false);
2561 emit({kind:"turn_done",err:"上游拒绝了请求,但未提供具体原因",protocolRecovery:{id:"mock-protocol-once"}});
2562 return;
2563 }
2564 if (trimmedInput === "/recover-context mock-protocol-once") {
2565 await delay(1500);
2566 if (cancelled) return;
2567 emit({kind:"tool_dispatch",tool:{id:"mock-search",name:"web_search",args:'{"query":"OpenCode documentation"}',readOnly:true}});
2568 emit({kind:"tool_result",tool:{id:"mock-search",name:"web_search",args:'{"query":"OpenCode documentation"}',readOnly:true,output:JSON.stringify({summary:"搜索摘要仍然可读。",sources:[],sources_status:"not_provided"})}});
2569 emit({kind:"notice",level:"info",code:"search_sources_not_provided",text:"搜索已完成,供应商未提供可用的结构化来源"});
2570 emitMockTurnDone(submissionID);
2571 return;
2572 }
2573 const decisionSurfaceMock = decisionSurfaceMockFromInput(trimmedInput);
2574 const goalMatch = /^\/goal(?:\s+([\s\S]*))?$/.exec(input.trim());
2575 if (goalMatch) {
2576 const arg = stripLegacyGoalBudgetFlags((goalMatch[1] ?? "").trim());
2577 const lowered = arg.toLowerCase();
2578 const active = mockTabs.find((tab) => tab.active);
2579 if (!arg || lowered === "status") {
2580 emit({ kind: "notice", level: "info", text: active?.goal ? `goal: ${active.goal}` : "goal: none" });
2581 emitMockTurnDone(submissionID);
2582 return;
2583 }
2584 if (["clear", "off", "stop", "done"].includes(lowered)) {
2585 mockTabs = mockTabs.map((tab) => (tab.active ? { ...tab, goal: "", goalStatus: "stopped", collaborationMode: "normal" } : tab));
2586 emit({ kind: "notice", level: "info", text: "goal cleared" });
2587 emitMockTurnDone(submissionID);
2588 return;
2589 }
2590 mockTabs = mockTabs.map((tab) => (tab.active ? { ...tab, goal: arg, goalStatus: "running", collaborationMode: "goal" } : tab));
2591 emit({ kind: "notice", level: "info", text: `goal set: ${arg}` });
2592 await delay(350);
2593 if (cancelled) return;
2594 const reply = `Autonomous goal run started for: **${arg}**\n\nMock run completed.\n\n[goal:complete]`;
2595 emit({ kind: "message", text: reply });
2596 mockTabs = mockTabs.map((tab) => (tab.active ? { ...tab, goal: "", goalStatus: "complete", collaborationMode: "normal" } : tab));
2597 emit({ kind: "notice", level: "info", text: "goal complete" });
2598 emitMockTurnDone(submissionID);
2599 return;
2600 }
2601 if (decisionSurfaceMock === "mcp_interaction") return (await import("./mockMCPInteraction")).showMockMCPInteraction(delay, () => cancelled, emitMockPrompt);
2602 if (decisionSurfaceMock === "tool_approval") {
2603 pendingApprovalPreview = true;
2604 pendingApprovalPreviewPrompt = { id: "mock-approval-preview", tool: "bash" };
2605 await delay(250);
2606 if (cancelled) return;
2607 emitMockPrompt({
2608 kind: "approval_request",
2609 approval: {
2610 id: "mock-approval-preview",
2611 tool: "bash",
2612 subject: t("mock.approvalSubject"),
2613 },
2614 });
2615 return;
2616 }
2617 if (trimmedInput === "/recovery-preview" || trimmedInput === "recovery preview" || trimmedInput === "恢复预览") {
2618 pendingApprovalPreview = true;
2619 pendingApprovalPreviewPrompt = { id: "mock-recovery-preview", tool: "write_file" };
2620 await delay(250);
2621 if (cancelled) return;
2622 emitMockPrompt({
2623 kind: "approval_request",
2624 approval: {
2625 id: "mock-recovery-preview",
2626 tool: "write_file",
2627 subject: "internal/recovery/gate.go",
2628 reason: "The proposed recovery changes the implementation method after a failing verification.",
2629 fresh: true,
2630 kind: "recovery",
2631 recovery: {
2632 source_agent: "root",
2633 failed_tool: "bash",
2634 failed_summary: "go test ./internal/recovery failed",
2635 diagnosis: "The failure is isolated to recovery state persistence.",
2636 next_tool: "write_file",
2637 next_action: "Update internal/recovery/gate.go",
2638 change_kind: "strategy",
2639 change_rationale: "The proposed edit changes the recovery method and needs a fresh decision.",
2640 plan_before: [
2641 "1. Keep the existing Auto execution path [in_progress]",
2642 "2. Add execution-risk approval prompts [pending]",
2643 "3. Run the recovery regression suite [pending]",
2644 ].join("\n"),
2645 plan_after: [
2646 "1. Keep the existing Auto execution path [in_progress]",
2647 "2. Ask only when strategy or scope changes [pending]",
2648 "3. Show the old and proposed plan before deciding [pending]",
2649 "4. Run the recovery regression suite [pending]",
2650 ].join("\n"),
2651 },
2652 },
2653 });
2654 return;
2655 }
2656 if (
2657 trimmedInput === "/sandbox-escape-preview" ||
2658 trimmedInput === "sandbox escape preview" ||
2659 trimmedInput === "sandbox_escape preview" ||
2660 trimmedInput === "sandbox escape预览"
2661 ) {
2662 pendingApprovalPreview = true;
2663 pendingApprovalPreviewPrompt = { id: "mock-sandbox-escape-preview", tool: "sandbox_escape" };
2664 await delay(250);
2665 if (cancelled) return;
2666 emitMockPrompt({
2667 kind: "approval_request",
2668 approval: {
2669 id: "mock-sandbox-escape-preview",
2670 tool: "sandbox_escape",
2671 subject: t("mock.sandboxEscapeSubject"),
2672 reason: t("mock.sandboxEscapeReason"),
2673 },
2674 });
2675 return;
2676 }
2677 if (decisionSurfaceMock === "plan_approval") {
2678 pendingApprovalPreview = true;
2679 pendingApprovalPreviewPrompt = { id: "mock-plan-approval-preview", tool: "exit_plan_mode" };
2680 await delay(250);
2681 if (cancelled) return;
2682 emitMockPrompt({
2683 kind: "approval_request",
2684 approval: {
2685 id: "mock-plan-approval-preview",
2686 tool: "exit_plan_mode",
2687 subject: "",
2688 },
2689 });
2690 return;
2691 }
2692 if (isLongDecisionOptionsMockInput(trimmedInput)) {
2693 pendingAskPreview = true;
2694 await delay(250);
2695 if (cancelled) return;
2696
2697 const longDescription = (...parts: string[]) => [...parts, ...parts, ...parts].join(" ");
2698 const longLabel = (...parts: string[]) => [...parts, ...parts, ...parts].join(" · ");
2699 const q1Option1Description = t("mock.askQ1Opt1Desc");
2700 const q1Option2Description = t("mock.askQ1Opt2Desc");
2701 const q1Option3Description = t("mock.askQ1Opt3Desc");
2702 const q2Option1Description = t("mock.askQ2Opt1Desc");
2703 const q2Option2Description = t("mock.askQ2Opt2Desc");
2704 const q2Option3Description = t("mock.askQ2Opt3Desc");
2705 const allowOnceDescription = t("approval.allowOnceDesc");
2706 const denyDescription = t("approval.denyDesc");
2707
2708 emitMockPrompt({
2709 kind: "ask_request",
2710 ask: {
2711 id: "mock-long-options",
2712 questions: [
2713 {
2714 id: "long-options",
2715 header: `${t("mock.askQ1Header")} · QA`,
2716 prompt: `${t("mock.askQ1Prompt")} ${t("mock.askQ2Prompt")}`,
2717 options: [
2718 {
2719 label: t("mock.askQ1Opt1Label"),
2720 description: longDescription(q1Option1Description, q2Option1Description, allowOnceDescription),
2721 },
2722 {
2723 label: t("mock.askQ1Opt2Label"),
2724 description: longDescription(q1Option2Description, q2Option2Description, denyDescription),
2725 },
2726 {
2727 label: t("mock.askQ1Opt3Label"),
2728 description: longDescription(q1Option3Description, q2Option3Description, allowOnceDescription),
2729 },
2730 {
2731 // Deliberately omit description here: this exercises the
2732 // legacy/malformed payload fallback where the complete
2733 // decision was placed in label instead of split into a
2734 // short label plus supporting description.
2735 label: longLabel(
2736 t("mock.askQ2Opt1Label"),
2737 t("mock.askQ1Opt3Label"),
2738 t("mock.askQ2Opt3Label"),
2739 t("mock.askQ1Opt1Label"),
2740 ),
2741 },
2742 {
2743 label: t("mock.askQ2Opt2Label"),
2744 description: longDescription(
2745 q2Option2Description,
2746 "DecisionSurfacePreviewWithAnExtremelyLongUnbrokenIdentifierForOverflowVerification0123456789",
2747 q1Option1Description,
2748 ),
2749 },
2750 {
2751 label: t("mock.askQ2Opt3Label"),
2752 description: longDescription(q2Option3Description, q1Option1Description, q2Option2Description),
2753 },
2754 {
2755 label: t("approval.deny"),
2756 description: longDescription(denyDescription, q1Option2Description, q2Option1Description),
2757 },
2758 ],
2759 },
2760 ],
2761 },
2762 });
2763 return;
2764 }
2765 if (decisionSurfaceMock === "ask") {
2766 pendingAskPreview = true;
2767 await delay(250);
2768 if (cancelled) return;
2769 emitMockPrompt({
2770 kind: "ask_request",
2771 ask: {
2772 id: `mock-ask-preview-${Date.now()}`,
2773 questions: [
2774 {
2775 id: "q1",
2776 header: t("mock.askQ1Header"),
2777 prompt: t("mock.askQ1Prompt"),
2778 options: [
2779 { label: t("mock.askQ1Opt1Label"), description: t("mock.askQ1Opt1Desc") },
2780 { label: t("mock.askQ1Opt2Label"), description: t("mock.askQ1Opt2Desc") },
2781 { label: t("mock.askQ1Opt3Label"), description: t("mock.askQ1Opt3Desc") },
2782 ],
2783 },
2784 {
2785 id: "q2",
2786 header: t("mock.askQ2Header"),
2787 prompt: t("mock.askQ2Prompt"),
2788 options: [
2789 { label: t("mock.askQ2Opt1Label"), description: t("mock.askQ2Opt1Desc") },
2790 { label: t("mock.askQ2Opt2Label"), description: t("mock.askQ2Opt2Desc") },
2791 { label: t("mock.askQ2Opt3Label"), description: t("mock.askQ2Opt3Desc") },
2792 ],
2793 },
2794 ],
2795 },
2796 });
2797 return;
2798 }
2799 if (trimmedInput === "/todo-preview" || trimmedInput === "todo preview" || trimmedInput === "todo预览") {
2800 await delay(250);
2801 if (cancelled) return;
2802 emit({
2803 kind: "tool_dispatch",
2804 tool: {
2805 id: "mock-todo-preview",
2806 name: "todo_write",
2807 args: JSON.stringify({
2808 todos: [
2809 { content: t("mock.todo1"), status: "completed" },
2810 { content: t("mock.todo2"), status: "in_progress" },
2811 { content: t("mock.todo3"), status: "pending" },
2812 ],
2813 }),
2814 readOnly: false,
2815 },
2816 });
2817 await delay(150);
2818 emit({
2819 kind: "tool_result",
2820 tool: {
2821 id: "mock-todo-preview",
2822 name: "todo_write",
2823 args: JSON.stringify({
2824 todos: [
2825 { content: t("mock.todo1"), status: "completed" },
2826 { content: t("mock.todo2"), status: "in_progress" },
2827 { content: t("mock.todo3"), status: "pending" },
2828 ],
2829 }),
2830 output: "todo list updated",
2831 readOnly: false,
2832 durationMs: 150,
2833 },
2834 });
2835 emitMockTurnDone(submissionID);
2836 return;
2837 }
2838 if (trimmedInput === "/process-preview" || trimmedInput === "process preview" || trimmedInput === "过程预览") {
2839 await delay(200);
2840 if (cancelled) return;
2841 emit({ kind: "phase", text: "Preparing context" });
2842 await delay(120);
2843 emit({ kind: "notice", level: "info", text: "Loaded project instructions from AGENTS.md." });
2844 await delay(120);
2845 emit({ kind: "notice", level: "warn", text: "Network access is enabled; external results may change over time." });
2846 await delay(120);
2847 emit({ kind: "compaction_started", compaction: { trigger: "manual" } });
2848 await delay(320);
2849 emit({
2850 kind: "compaction_done",
2851 compaction: {
2852 trigger: "manual",
2853 messages: 6,
2854 summary: "Preserved the active task, relevant files, and UI decisions while trimming earlier exploratory context.",
2855 },
2856 });
2857 emit({ kind: "message", text: "Process card preview complete." });
2858 emitMockTurnDone(submissionID);
2859 return;
2860 }
2861 if (trimmedInput === "/nested-preview" || trimmedInput === "nested preview" || trimmedInput === "嵌套预览") {
2862 const parentId = "mock-nested-explore";
2863 await delay(180);
2864 if (cancelled) return;
2865 emit({
2866 kind: "reasoning",
2867 text: "我先快速探索相关文件,再整理这个工具行的视觉层级。",
2868 });
2869 emit({
2870 kind: "message",
2871 text: "",
2872 reasoning: "我先快速探索相关文件,再整理这个工具行的视觉层级。",
2873 });
2874 emit({
2875 kind: "tool_dispatch",
2876 tool: {
2877 id: parentId,
2878 name: "explore",
2879 args: JSON.stringify({ task: "在 Reasonix 前端中检查工具调用图标和嵌套调用展示" }),
2880 readOnly: true,
2881 profile: { model: "mock-reasonix", effort: "high" },
2882 },
2883 });
2884 for (let i = 1; i <= 30; i += 1) {
2885 if (cancelled) return;
2886 const id = `mock-nested-${i}`;
2887 const isSearch = i % 3 === 0;
2888 const name = isSearch ? "grep" : "read_file";
2889 const args = isSearch
2890 ? { pattern: i % 2 === 0 ? "tool__nested-count" : "explore", path: "desktop/frontend/src" }
2891 : { path: `desktop/frontend/src/${i % 2 === 0 ? "components/ToolCard.tsx" : "styles.css"}`, offset: i * 10, limit: 40 };
2892 emit({ kind: "tool_dispatch", tool: { id, name, args: JSON.stringify(args), readOnly: true, parentId } });
2893 emit({
2894 kind: "tool_result",
2895 tool: {
2896 id,
2897 name,
2898 readOnly: true,
2899 output: isSearch ? "3 matches" : "read 40 lines",
2900 durationMs: 24 + i,
2901 },
2902 });
2903 await delay(18);
2904 }
2905 emit({
2906 kind: "tool_result",
2907 tool: {
2908 id: parentId,
2909 name: "explore",
2910 readOnly: true,
2911 output: "已读 20 个文件 · 搜索 10 个文件",
2912 durationMs: 61510,
2913 },
2914 });
2915 emit({
2916 kind: "message",
2917 text: "Mock nested tool preview complete. The explore row now shows the compass count marker.",
2918 });
2919 emitMockTurnDone(submissionID);
2920 return;
2921 }
2922 // Simulate the server's pre-first-token latency so the deferred user bubble
2923 // and the "un-send on Esc before any reply" path are observable in browser
2924 // dev. Bail if cancelled during the wait — nothing was streamed yet.
2925 await delay(700);
2926 if (cancelled) return;
2927 const reasoningChunks = [
2928 "我先判断这是浏览器预览环境,所以不会调用真实 kernel。\n",
2929 "接着模拟 provider 的 reasoning delta:先展示思考过程,再切到正式回复。\n",
2930 "完成后前端应该把过程区折叠成“已工作 N 秒”。\n",
2931 ];
2932 for (const chunk of reasoningChunks) {
2933 if (cancelled) return;
2934 emit({ kind: "reasoning", reasoning: chunk });
2935 await delay(520);
2936 }
2937 if (cancelled) return;
2938 await delay(260);
2939 const reply =
2940 `You said: **${input}**\n\n` +
2941 "This is the browser dev mock — the real reply comes from the kernel " +
2942 "inside the desktop shell. Here's a fenced block to exercise the editor seam:\n\n" +
2943 "```go\nfunc main() {\n println(\"hello from the mock\")\n}\n```\n";
2944 for (const ch of reply) {
2945 if (cancelled) break;
2946 emit({ kind: "text", text: ch });
2947 await delay(6);
2948 }
2949 emit({ kind: "message", text: reply });
2950 emit({
2951 kind: "tool_dispatch",
2952 tool: {
2953 id: "t1",
2954 name: "edit_file",
2955 args: '{"path":"main.go","old_string":"println(\\"hi\\")","new_string":"println(\\"hello\\")"}',
2956 readOnly: false,
2957 },
2958 });
2959 await delay(350);
2960 emit({
2961 kind: "tool_result",
2962 tool: { id: "t1", name: "edit_file", output: "edited main.go", readOnly: false, durationMs: 350 },
2963 });
2964 emit({
2965 kind: "usage",
2966 usage: {
2967 promptTokens: 1280,
2968 completionTokens: 64,
2969 totalTokens: 1344,
2970 cacheHitTokens: 1024,
2971 cacheMissTokens: 256,
2972 sessionCacheHitTokens: 1024,
2973 sessionCacheMissTokens: 256,
2974 cost: 0.0064,
2975 currency: "¥",
2976 currencyCode: "CNY",
2977 costComplete: true,
2978 displayComplete: true,
2979 displayStatus: "matched",
2980 costQuote: {
2981 original: { amount: "0.0064", currency: "CNY" },
2982 selected: { amount: "0.0064", currency: "CNY" },
2983 estimated: true,
2984 costComplete: true,
2985 displayComplete: true,
2986 complete: true,
2987 displayStatus: "matched",
2988 aggregateMode: "single_currency",
2989 modelRef: "deepseek-official/deepseek-v4-flash",
2990 rateBand: "off_peak",
2991 ratedAt: "2026-08-17T00:30:00Z",
2992 },
2993 },
2994 });
2995 emitMockTurnDone(submissionID);
2996 },
2997 async SubmitToTab(_tabID, input) { await withMockTabScope(_tabID, () => this.Submit(input)); },
2998 async SubmitToTabWithID(_tabID, input, submissionID) { const submit = this.Submit as (value: string, id?: string) => Promise<void>; await withMockTabScope(_tabID, () => submit(input, submissionID)); },
2999 async StartTurnForTab(_tabID, input, submissionID) {
3000 const turnId = `mock-turn-${submissionID}`;
3001 const submit = this.Submit as (value: string, id?: string) => Promise<void>;
3002 void withMockTabScope(_tabID, () => submit(input, submissionID)).catch((error) => {
3003 console.error("mock turn failed", error);
3004 });
3005 return { turnId, status: "started", disposition: "turn_started", runtimeEpoch: "mock", submissionId: submissionID };
3006 },
3007 async SubmitDisplay(_display, input) { await this.Submit(input); },
3008 async SubmitDisplayToTab(_tabID, display, input) { await withMockTabScope(_tabID, () => this.SubmitDisplay(display, input)); },
3009 async SubmitDisplayToTabWithID(_tabID, _display, input, submissionID) { await this.SubmitToTabWithID(_tabID, input, submissionID); },
3010 async SubmitDeliveryRecoveryToTab(_tabID, display, input) { await withMockTabScope(_tabID, () => this.SubmitDisplay(display, input)); },
3011 async SubmitDeliveryRecoveryToTabWithID(_tabID, _display, input, submissionID) { await this.SubmitToTabWithID(_tabID, input, submissionID); },
3012 async SubmitInvocationsToTab(_tabID, display, input, _invocations) { await withMockTabScope(_tabID, () => this.SubmitDisplay(display, input)); },
3013 async SubmitInvocationsToTabWithID(_tabID, _display, input, _invocations, submissionID) { await this.SubmitToTabWithID(_tabID, input, submissionID); },
3014 async SubmitInitialGoalToTab(
3015 _tabID,
3016 goal,
3017 display,
3018 input,
3019 invocations,
3020 _collaborationMode,
3021 _toolApprovalMode,
3022 ) {
3023 return await withMockTabScope(_tabID, async () => {
3024 await this.SetGoalForTab(_tabID, goal);
3025 if (invocations.length > 0) {
3026 await this.SubmitInvocationsToTab(_tabID, display, input, invocations);
3027 return [];
3028 }
3029 await this.SubmitDisplayToTab(_tabID, display, input);
3030 return [];
3031 });
3032 },
3033 async SubmitInitialGoalToTabWithID(_tabID, goal, display, input, invocations, _collaborationMode, _toolApprovalMode, submissionID) { await this.SetGoalForTab(_tabID, goal); if (invocations.length > 0) await this.SubmitInvocationsToTabWithID(_tabID, display, input, invocations, submissionID); else await this.SubmitDisplayToTabWithID(_tabID, display, input, submissionID); return []; },
3034 async SubmitEditedDisplayToTab(_tabID, display, input, _original) { await withMockTabScope(_tabID, () => this.SubmitDisplay(display, input)); },
3035 async SubmitEditedDisplayToTabWithID(_tabID, display, input, _original, submissionID) { await this.SubmitDisplayToTabWithID(_tabID, display, input, submissionID); },
3036 async RunShellForTab(_tabID, command) {
3037 await withMockTabScope(_tabID, async () => {
3038 cancelled = false;
3039 emitMockTurnStarted();
3040 await delay(100);
3041 if (cancelled) return;
3042 const id = `shell-${command.slice(0, 32)}`;
3043 emit({ kind: "tool_dispatch", tool: { id, name: "bash", args: JSON.stringify({ command }), readOnly: false } });
3044 await delay(200);
3045 if (cancelled) return;
3046 emit({ kind: "tool_progress", tool: { id, name: "bash", output: `$ ${command}\n(mock output)\n`, readOnly: false } });
3047 await delay(100);
3048 if (cancelled) return;
3049 emit({ kind: "tool_result", tool: { id, name: "bash", output: `$ ${command}\n(mock output)\n`, readOnly: false, durationMs: 300 } });
3050 emitMockTurnDone();
3051 });
3052 },
3053 async Steer(_text) {
3054 // Mock: emit a steer event as confirmation in the transcript.
3055 emit({ kind: "steer", text: _text });
3056 },
3057 async SteerForTab(_tabID, _text) {
3058 await this.Steer(_text);
3059 },
3060 ...inboxQueuePreview && Object.fromEntries(["CaptureInboxTarget", "InboxQueueForTarget", "EnqueueInboxFollowupForTarget", "LookupInboxFollowupForTarget"].map(name => [name, async (...args: unknown[]) => {
3061 const bindings = await inboxQueuePreview as Record<string, (...values: unknown[]) => Promise<unknown>>;
3062 return bindings[name](...args);
3063 }])),
3064 async InboxSnapshot(_tabID) { if (inboxQueuePreview) return (await inboxQueuePreview).InboxSnapshot(_tabID); if (recoveryMock) return (await import("./inboxRecoveryPreview")).inboxRecoveryPreviewSnapshot();
3065 return {
3066 revision: 0,
3067 paused: false,
3068 recovered: false, sessionPath: "",
3069 items: [],
3070 itemsCount: 0,
3071 bytes: 0,
3072 maxItems: 64,
3073 maxBytes: 64 * 1024 * 1024,
3074 };
3075 },
3076 async EnqueueInboxFollowup(_tabID, _display, _submit, _idempotency) {
3077 return { itemId: `mock-${Date.now()}`, disposition: "queued_followup", position: 1, paused: false };
3078 },
3079 async EnqueueInboxFollowupWithInvocations(_tabID, _display, _submit, _invocations, _idempotency) {
3080 return { itemId: `mock-invocation-${Date.now()}`, disposition: "queued_followup", position: 1, paused: false };
3081 },
3082 async EnqueueInboxSteer(_tabID, display, submit, _idempotency) {
3083 const itemId = `mock-steer-${Date.now()}`;
3084 emit({ kind: "steer", text: submit || display, itemId });
3085 return { itemId, disposition: "steer_accepted", position: 1, paused: false };
3086 },
3087 async SteerInboxItem(_tabID, itemID) {
3088 emit({ kind: "steer", itemId: itemID });
3089 return { itemId: itemID, disposition: "steer_accepted", position: 1, paused: false };
3090 },
3091 async ReadInboxItem(_tabID, id) {
3092 return { id, displayText: "", rawText: "", submitText: "" };
3093 },
3094 async UpdateInboxItem() {},
3095 async DeleteInboxItem() {},
3096 async MoveInboxItem() {},
3097 async SetInboxPaused(_tabID, paused) { if (recoveryMock) (await import("./inboxRecoveryPreview")).setInboxRecoveryPreviewPaused(paused); },
3098 async RetryInboxItem() {},
3099 async RefreshInboxItem() {},
3100 async InboxHasItems() { return recoveryMock; },
3101 async Cancel() {
3102 cancelled = true;
3103 emitMockTurnDone();
3104 },
3105 async CancelTab(_tabID) {
3106 await withMockTabScope(_tabID, () => this.Cancel());
3107 },
3108 async CancelSessionForTab(_tabID) {
3109 await withMockTabScope(_tabID, () => this.Cancel());
3110 return { sessionRef: "", headId: "", runtimeEpoch: "mock", accepted: true, alreadyIdle: false, recoveryRequired: false };
3111 },
3112 async CancelTabWithInboxItems(_tabID, _itemIDs) {
3113 await withMockTabScope(_tabID, () => this.Cancel());
3114 },
3115 async CancelTabWithInboxItemsResult(_tabID, itemIDs) { await withMockTabScope(_tabID, () => this.Cancel()); return { discardedItemIds: [...itemIDs] }; },
3116 async Approve(_id, allow, session, persist) {
3117 if (!pendingApprovalPreview) return;
3118 pendingApprovalPreview = false;
3119 pendingApprovalPreviewPrompt = undefined;
3120 const suffix = persist ? "grant saved" : session ? "grant active this session" : "allowed once";
3121 emit({
3122 kind: "message",
3123 text: `approval preview answered: ${allow ? suffix : "denied"}`,
3124 });
3125 emitMockTurnDone();
3126 },
3127 async ApproveTab(_tabID, id, allow, session, persist) {
3128 await withMockTabScope(_tabID, () => this.Approve(id, allow, session, persist));
3129 },
3130 async ResolvePlanDecision(id, action) {
3131 const active = mockTabs.find((tab) => tab.active);
3132 await this.ResolvePlanDecisionTab(active?.id ?? "", id, action);
3133 },
3134 async ResolvePlanDecisionTab(_tabID, id, action) {
3135 await withMockTabScope(_tabID, async () => {
3136 void id;
3137 pendingApprovalPreview = false;
3138 pendingApprovalPreviewPrompt = undefined;
3139 emit({
3140 kind: "message",
3141 text: `plan preview answered: ${action}`,
3142 });
3143 emitMockTurnDone();
3144 });
3145 },
3146 async ResolveRecovery(id, action, feedback) {
3147 const active = mockTabs.find((tab) => tab.active);
3148 await this.ResolveRecoveryTab(active?.id ?? "", id, action, feedback);
3149 },
3150 async ResolveRecoveryTab(_tabID, id, action, feedback) {
3151 void id;
3152 void feedback;
3153 pendingApprovalPreview = false;
3154 pendingApprovalPreviewPrompt = undefined;
3155 emit({
3156 kind: "message",
3157 text: `recovery preview answered: ${action}`,
3158 });
3159 emitMockTurnDone();
3160 },
3161 async SetRecoveryCheckpointEnabled(_enabled) {},
3162 async SetRecoveryCheckpointEnabledTab(_tabID, _enabled) {},
3163 async RecoveryCheckpointEnabled() {
3164 return true;
3165 },
3166 async RecoveryCheckpointEnabledTab(_tabID) {
3167 return true;
3168 },
3169 async AnswerQuestion(_id, answers) {
3170 if (!pendingAskPreview) return;
3171 pendingAskPreview = false;
3172 const summary = answers
3173 .map((answer) => `${answer.questionId}: ${(answer.selected ?? []).join(", ") || "(no answer)"}`)
3174 .join("\n");
3175 emit({ kind: "message", text: `ask preview answered:\n\n${summary}` });
3176 emitMockTurnDone();
3177 },
3178 async AnswerMCPInteractionForTab(_tabID, id, _action, _content) {
3179 if (!cancelled && (await import("./mockMCPInteraction")).consumeMockMCPInteraction(id)) await withMockTabScope(_tabID, async () => { emit({ kind: "prompt_answered", itemId: id }); emitMockTurnDone(); });
3180 },
3181 ...makeMockMCPAppBindings(), ...makeMockPinnedContextBindings(),
3182 async AnswerQuestionForTab(_tabID, id, answers) {
3183 await withMockTabScope(_tabID, () => this.AnswerQuestion(id, answers));
3184 },
3185 async ResolvePromptForTab(tabID, promptID, _turnID, _runtimeEpoch, kind, answer) {
3186 await withMockTabScope(tabID, async () => {
3187 if (kind === "ask") return this.AnswerQuestion(promptID, answer.questions ?? []);
3188 if (kind === "approval") return this.Approve(promptID, Boolean(answer.allow), Boolean(answer.session), Boolean(answer.persist));
3189 if (kind === "plan") return this.ResolvePlanDecisionTab(tabID, promptID, (answer.action ?? "exit_plan") as "start_execution" | "revise_plan" | "exit_plan");
3190 if (kind === "recovery") return this.ResolveRecoveryTab(tabID, promptID, answer.action ?? "revise", answer.feedback ?? "");
3191 if (kind === "mcp") return this.AnswerMCPInteractionForTab(tabID, promptID, (answer.action ?? "cancel") as "accept" | "decline" | "cancel", answer.content ?? null);
3192 throw new Error(`unsupported prompt kind: ${kind}`);
3193 });
3194 },
3195 async ResolvePromptForSession(target, answer) { await this.ResolvePromptForTab?.(target.tabId, target.promptId, target.turnId, target.runtimeEpoch, target.kind, answer); },
3196 async ReplayPendingPrompts() {},
3197 async ReplayPendingPromptsForTab(_tabID) {},
3198 async ConfirmAction(req) {
3199 void req;
3200 return false;
3201 },
3202 async SetPlanMode(on) {
3203 const active = mockTabs.find((tab) => tab.active);
3204 if (active) await this.SetModeForTab(active.id, modeWithPlan(normalizeMode(active.mode), on));
3205 },
3206 async SetMode(mode) {
3207 const active = mockTabs.find((tab) => tab.active);
3208 if (active) await this.SetModeForTab(active.id, mode);
3209 },
3210 async SetModeForTab(tabID, mode) {
3211 const nextMode = normalizeMode(mode);
3212 let nextToolApprovalMode: ToolApprovalMode | "" = "";
3213 mockTabs = mockTabs.map((tab) => {
3214 if (tab.id !== tabID) return tab;
3215 nextToolApprovalMode = mockToolApprovalModeAfterModeChange(tab.toolApprovalMode, nextMode);
3216 return {
3217 ...tab,
3218 mode: nextMode,
3219 collaborationMode: normalizeCollaborationMode(undefined, tab.goal, nextMode),
3220 toolApprovalMode: nextToolApprovalMode,
3221 };
3222 });
3223 return drainMockApprovalPreviews(nextToolApprovalMode);
3224 },
3225 async SetCollaborationModeForTab(tabID, mode) {
3226 const next = normalizeCollaborationMode(mode);
3227 mockTabs = mockTabs.map((tab) => {
3228 if (tab.id !== tabID) return tab;
3229 const toolMode = normalizeToolApprovalMode(tab.toolApprovalMode, normalizeMode(tab.mode));
3230 return {
3231 ...tab,
3232 collaborationMode: next,
3233 goal: next === "normal" || next === "plan" ? "" : tab.goal,
3234 mode: modeWithPlan(modeWithAutoApproveTools(normalizeMode(tab.mode), toolMode === "danger-full-access"), next === "plan"),
3235 };
3236 });
3237 },
3238 async SetToolApprovalMode(mode) {
3239 const active = mockTabs.find((tab) => tab.active);
3240 if (active) await this.SetToolApprovalModeForTab(active.id, mode);
3241 },
3242 async SetToolApprovalModeForTab(tabID, mode) {
3243 const next = normalizeToolApprovalMode(mode);
3244 settings.autoApproveTools = next === "danger-full-access";
3245 settings.bypass = next === "danger-full-access";
3246 mockTabs = mockTabs.map((tab) =>
3247 tab.id === tabID
3248 ? {
3249 ...tab,
3250 toolApprovalMode: next,
3251 mode: modeWithAutoApproveTools(normalizeMode(tab.mode), next === "danger-full-access"),
3252 }
3253 : tab,
3254 );
3255 return drainMockApprovalPreviews(next);
3256 },
3257 async PermissionSnapshotForTab(tabID) {
3258 const tab = mockTabs.find((candidate) => candidate.id === tabID);
3259 if (!tab) throw new Error("tab not found");
3260 return {
3261 sessionId: tab.sessionPath || tab.id,
3262 generation: 1,
3263 revision: Number((tab as TabMeta & { permissionRevision?: number }).permissionRevision ?? 1),
3264 preset: normalizeToolApprovalMode(tab.toolApprovalMode),
3265 workspaceRoot: tab.workspaceRoot || tab.cwd || "",
3266 grants: [],
3267 capabilities: {
3268 backend: "mock",
3269 enforcement: "full",
3270 supportedPresets: ["read-only", "workspace-write", "danger-full-access"],
3271 },
3272 };
3273 },
3274 async SetPermissionPresetForTab(tabID, expectedSessionID, preset, expectedRevision) {
3275 const current = await this.PermissionSnapshotForTab(tabID);
3276 if (current.sessionId !== expectedSessionID) throw new Error("reasonix_error:permission_session_changed");
3277 if (current.revision !== expectedRevision) throw new Error("permission revision changed");
3278 await this.SetToolApprovalModeForTab(tabID, preset);
3279 mockTabs = mockTabs.map((tab) => tab.id === tabID ? { ...tab, permissionRevision: current.revision + 1 } as TabMeta : tab);
3280 return { ...current, revision: current.revision + 1, preset: normalizeToolApprovalMode(preset) };
3281 },
3282 async RevokePermissionGrantForTab(tabID, _scope, _target, expectedRevision) {
3283 const current = await this.PermissionSnapshotForTab(tabID);
3284 if (current.revision !== expectedRevision) throw new Error("permission revision changed");
3285 return { ...current, revision: current.revision + 1, grants: [] };
3286 },
3287 async SetComposerProfileForTab(tabID, collaborationMode, toolApprovalMode, goal) {
3288 const nextCollaboration = normalizeCollaborationMode(collaborationMode);
3289 const nextToolApproval = normalizeToolApprovalMode(toolApprovalMode);
3290 const nextGoal = goal.trim();
3291 settings.autoApproveTools = nextToolApproval === "danger-full-access";
3292 settings.bypass = nextToolApproval === "danger-full-access";
3293 mockTabs = mockTabs.map((tab) => {
3294 if (tab.id !== tabID) return tab;
3295 const plan = !nextGoal && nextCollaboration === "plan";
3296 return {
3297 ...tab,
3298 collaborationMode: nextGoal ? "goal" : plan ? "plan" : "normal",
3299 toolApprovalMode: nextToolApproval,
3300 goal: nextGoal,
3301 goalStatus: nextGoal ? "running" : "stopped",
3302 mode: modeWithAutoApproveTools(modeWithPlan(normalizeMode(tab.mode), plan), nextToolApproval === "danger-full-access"),
3303 };
3304 });
3305 return drainMockApprovalPreviews(nextToolApproval);
3306 },
3307 async SetGoal(goal) { const active = mockTabs.find((tab) => tab.active); if (active) await this.SetGoalForTab(active.id, goal); },
3308 async SetGoalForTab(tabID, goal) {
3309 const nextGoal = goal.trim();
3310 mockTabs = mockTabs.map((tab) =>
3311 tab.id === tabID
3312 ? {
3313 ...tab,
3314 goal: nextGoal,
3315 goalStatus: nextGoal ? "running" : "stopped",
3316 collaborationMode: nextGoal ? "goal" : "normal",
3317 mode: modeWithPlan(normalizeMode(tab.mode), false),
3318 }
3319 : tab,
3320 );
3321 },
3322 async EditGoalForTab(tabID, objective, maxGoalRounds) { mockTabs = mockTabs.map((tab) => editMockGoalTab(tab, tabID, objective, maxGoalRounds)); },
3323 async ResumeGoalForTab(tabID) {
3324 let resumed = false;
3325 mockTabs = mockTabs.map((tab) => {
3326 if (tab.id !== tabID || !tab.goal || tab.goalStatus === "complete") return tab;
3327 resumed = true;
3328 return { ...tab, goalStatus: "running", collaborationMode: "goal", goalRuntime: undefined };
3329 });
3330 return resumed;
3331 },
3332 async PauseGoalForTab(tabID) {
3333 let paused = false;
3334 mockTabs = mockTabs.map((tab) => {
3335 if (tab.id !== tabID || !tab.goal || tab.goalStatus !== "running") return tab;
3336 paused = true;
3337 return { ...tab, goalStatus: "blocked", goalRuntime: undefined };
3338 });
3339 return paused;
3340 },
3341 async ClearGoalForTab(tabID) { await this.SetGoalForTab(tabID, ""); },
3342 async Compact() {},
3343 async CompactForTab() {},
3344 async NewSession() {},
3345 async NewSessionForTab() {},
3346 async ClearSession() { return { sessionPath: "", sessionGeneration: 0 }; },
3347 async ClearSessionForTab() { return { sessionPath: "", sessionGeneration: 0 }; },
3348 async Checkpoints() {
3349 return [
3350 { turn: 0, prompt: "你好呀", files: ["src/App.tsx"], fileCount: 1, turnFileCount: 1, time: Date.now() - 30_000, canCode: true, canConversation: true },
3351 ];
3352 },
3353 async CheckpointsForTab() { return this.Checkpoints(); },
3354 async Rewind() {},
3355 async RewindForTab() {},
3356 async PreviewRewindForTab() {
3357 return { ok: true, canFiles: true, canConversation: true, planId: "mock", fileCount: 0 };
3358 },
3359 async CommitRewindForTab() {
3360 return { ok: true, undoAvailable: true, transactionId: "mock-tx" };
3361 },
3362 async UndoRewindForTab() {
3363 return { ok: true, undoAvailable: false };
3364 },
3365 async PreviewWorkspaceFileRevertForTab(_tabID, path) {
3366 return { ok: true, canFiles: true, path, planId: "mock-file" };
3367 },
3368 async CommitWorkspaceFileRevertForTab() {
3369 return { ok: true, undoAvailable: true, transactionId: "mock-file-tx" };
3370 },
3371 ...makeMockForkBindings(
3372 () => mockTabs,
3373 (tabs) => { mockTabs = tabs; },
3374 t("rewind.fork"),
3375 (tabID) => getMock().HistoryForTab(tabID),
3376 ),
3377 async SummarizeFrom() {},
3378 async SummarizeFromForTab() {},
3379 async SummarizeUpTo() {},
3380 async SummarizeUpToForTab() {},
3381 async History() {
3382 return [];
3383 },
3384 async HistoryForTab(tabID?: string) {
3385 const tab = mockTabs.find((item) => item.id === tabID) ?? mockTabs.find((item) => item.active);
3386 if (tab?.topicId) {
3387 queueMockTopicRuntime(tab);
3388 if (benchFixturesPromise) {
3389 const fixtures = await benchFixturesPromise;
3390 const history = fixtures.benchTopicHistory(tab.topicId);
3391 if (history) return history;
3392 }
3393 return withMockHistoryIds(tab.id, topicHistoryFixture(t0, tab.topicId));
3394 }
3395 return withMockHistoryIds(tabID ?? "mock", await this.History());
3396 },
3397 async HistoryPage(beforeTurn = 0, limit = 60) {
3398 return mockHistoryPage(await this.History(), beforeTurn, limit);
3399 },
3400 async HistoryPageForTab(tabID: string, beforeTurn = 0, limit = 60) {
3401 return mockHistoryPage(await this.HistoryForTab(tabID), beforeTurn, limit);
3402 },
3403 async HistoryCheckpointTurnsForTab(tabID: string) {
3404 const turns: number[] = [];
3405 for (const message of await this.HistoryForTab(tabID)) {
3406 if (message.role !== "user") continue;
3407 turns.push(message.checkpointTurn ?? turns.length);
3408 }
3409 return turns;
3410 },
3411 async HistorySliceForTab(tabID: string, req: HistorySliceRequest) {
3412 return mockHistorySlice(tabID, await this.HistoryForTab(tabID), req, benchMock);
3413 },
3414 async HistoryContentForTab(tabID: string, ref: HistoryContentRef, chunkIndex: number): Promise<HistoryContentChunk> {
3415 const out: HistoryContentChunk = { entryId: ref.entryId, field: ref.field, chunk: Math.max(0, chunkIndex), chunks: 1, data: "", done: true, stale: false };
3416 const match = /:m(\d+):o\d+$/.exec(ref.entryId);
3417 if (!match) return out;
3418 const messages = await this.HistoryForTab(tabID);
3419 const message = messages[Number(match[1])];
3420 if (benchMock && message?.content?.includes("ASYNC LAYOUT EXPANSION COMPLETE")) await delay((await benchFixturesPromise)!.benchHydrationDelay());
3421 // Storm fixture: pace ref resolutions deterministically by entry
3422 // index so opening the session produces a seconds-long patch storm
3423 // instead of a single burst (#8657).
3424 if (benchMock && (message?.content?.includes("BENCH STORM HYDRATION RESOLVED") || message?.reasoning?.includes("BENCH STORM HYDRATION RESOLVED"))) {
3425 await delay(50 + (Number(match[1]) % 24) * 120);
3426 }
3427 if (!message) return { ...out, stale: true };
3428 out.data = mockHistoryContentField(message, ref);
3429 out.chunks = 1;
3430 return out;
3431 },
3432 ...makeMockSessionReaderBindings(),
3433 async ListSessions() {
3434 return sessions.map((s) => ({ ...s }));
3435 },
3436 async ListSessionsForTab() {
3437 return sessions.map((s) => ({ ...s }));
3438 },
3439 ...makeMockHistoryCatalogBindings(sessions),
3440 async ListTrashedSessions() {
3441 return trashedSessions.map((s) => ({ ...s }));
3442 },
3443 async ResumeSession(path: string) {
3444 sessions.forEach((s) => {
3445 s.current = s.path === path;
3446 s.open = s.open || s.path === path;
3447 });
3448 return [
3449 { role: "user", content: `(mock) resumed ${path}` },
3450 { role: "assistant", content: "This is a mock resumed transcript — the real one comes from the kernel." },
3451 ];
3452 },
3453 async ResumeSessionForTab(_tabID: string, path: string) {
3454 return this.ResumeSession(path);
3455 },
3456 async ResumeSessionPage(path: string, limit = 60) {
3457 return mockHistoryPage(await this.ResumeSession(path), 0, limit);
3458 },
3459 async ResumeSessionPageForTab(_tabID: string, path: string, limit = 60) {
3460 return this.ResumeSessionPage(path, limit);
3461 },
3462 async OpenChannelSessionForTab(tabID: string, path: string) {
3463 mockTabs = mockTabs.map((tab) => tab.id === tabID ? { ...tab, sessionPath: path, readOnly: true } : tab);
3464 return this.ResumeSession(path);
3465 },
3466 async OpenChannelSessionPageForTab(tabID: string, path: string, limit = 60) {
3467 return mockHistoryPage(await this.OpenChannelSessionForTab(tabID, path), 0, limit);
3468 },
3469 async QuerySessionTakeover(_tabId: string) {
3470 return { available: false, reason: "mock" } as import("./types").SessionTakeoverView;
3471 },
3472 async TakeoverSession(_tabId: string, _mode: "wait" | "interrupt") {},
3473 async PreviewSession(path: string) {
3474 const s = sessions.find((x) => x.path === path) ?? trashedSessions.find((x) => x.path === path);
3475 return [
3476 { role: "user", content: s?.preview || `(mock) preview ${path}` },
3477 { role: "phase", content: "Preparing read-only preview" },
3478 {
3479 role: "assistant",
3480 content: "This is a read-only mock preview. The active conversation is unchanged.",
3481 reasoning: "Preview reads the saved session without resuming it.",
3482 },
3483 { role: "notice", level: "info", content: "Preview mode keeps the active conversation untouched." },
3484 { role: "compaction", content: "", trigger: "manual", messages: 3, summary: "Mock preview preserved the latest task, tool result, and answer summary." },
3485 ];
3486 },
3487 async DeleteSession(path: string) {
3488 const i = sessions.findIndex((s) => s.path === path);
3489 if (i >= 0) {
3490 const [s] = sessions.splice(i, 1);
3491 trashedSessions.unshift({
3492 ...s,
3493 current: false,
3494 open: false,
3495 path: s.path.replace("/mock/sessions/", "/mock/sessions/.trash/"),
3496 deletedAt: Date.now(),
3497 });
3498 }
3499 },
3500 async DeleteRecoveryCopy(path: string) {
3501 return this.DeleteSession(path);
3502 },
3503 async GetRecoveryLineage(key) {
3504 const topic = findMockTopic(key.topicId);
3505 return {
3506 groupId: key.topicId,
3507 state: topic?.recoveryState ?? "normal",
3508 branchCount: topic?.recoveryBranchCount ?? 0,
3509 unresolved: topic?.recoveryUnresolvedCount ?? 0,
3510 cleanupEligible: topic?.recoveryCleanupEligibleCount ?? 0,
3511 members: [],
3512 };
3513 },
3514 async GetSessionVersionState(key) {
3515 const lineage = await this.GetRecoveryLineage(key);
3516 return { conversationId: key.topicId, canContinue: true, requiresChoice: lineage.state === "diverged" && lineage.unresolved > 0, lineage };
3517 },
3518 async SetActiveSessionVersion() {},
3519 async RetrySessionRecovery() {},
3520 async ReconcileRecoveryVersions() {},
3521 async ChooseRecoveryBranch() {},
3522 async RenameSessionHead() {},
3523 async CleanRecoveryLineage(request) {
3524 const topic = findMockTopic(request.topicId);
3525 const eligible = topic?.recoveryCleanupEligibleCount ?? 0;
3526 if (request.apply && topic) topic.recoveryCleanupEligibleCount = 0;
3527 return { eligible, moved: request.apply ? eligible : 0, busy: 0, kept: 0, dryRun: !request.apply, items: [] };
3528 },
3529 async RestoreSession(path: string) {
3530 const i = trashedSessions.findIndex((s) => s.path === path);
3531 if (i >= 0) {
3532 const [s] = trashedSessions.splice(i, 1);
3533 sessions.unshift({
3534 ...s,
3535 path: s.path.replace("/mock/sessions/.trash/", "/mock/sessions/"),
3536 deletedAt: undefined,
3537 });
3538 }
3539 },
3540 async PurgeTrashedSession(path: string) {
3541 const i = trashedSessions.findIndex((s) => s.path === path);
3542 if (i >= 0) trashedSessions.splice(i, 1);
3543 },
3544 async PurgeRecoveryCopy(path: string) {
3545 return this.PurgeTrashedSession(path);
3546 },
3547 async RenameSession(path: string, title: string) {
3548 const s = sessions.find((x) => x.path === path);
3549 if (s) s.title = title.trim() || undefined;
3550 },
3551 async ScanPromptHistory(nonce: string) {
3552 // Dev mock returns a static set of sample prompts for UI development.
3553 const entries: PromptHistoryEntry[] = [
3554 { text: "Explain the architecture of this project", at: Date.now() - 60000, sessionPath: "/mock/sessions/arch.jsonl", turn: 0 },
3555 { text: "Fix the login button styling", at: Date.now() - 120000, sessionPath: "/mock/sessions/arch.jsonl", turn: 1 },
3556 { text: "What is the capital of France?", at: Date.now() - 300000, sessionPath: "/mock/sessions/general.jsonl", turn: 0 },
3557 ];
3558 return { entries, nonce: "mock-" + nonce, olderCursor: "", hasOlder: false };
3559 },
3560 async ListWorkspaces() {
3561 return mockProjectTree
3562 .filter((node) => node.kind === "project" && node.root)
3563 .map((node) => ({
3564 path: node.root!,
3565 name: node.label || baseName(node.root!),
3566 current: node.root === cwd,
3567 }));
3568 },
3569 async PickWorkspace() {
3570 // Browser dev has no native dialog; simulate picking a folder and re-root so
3571 // the topbar folder chip visibly changes.
3572 return mockSwitchWorkspace(cwd.endsWith("another-project") ? "~/projects/reasonix" : "~/projects/another-project");
3573 },
3574 async SwitchWorkspace(path: string) {
3575 return mockSwitchWorkspace(path);
3576 },
3577 async RemoveWorkspace(path: string) {
3578 workspaces = workspaces.filter((p) => p !== path);
3579 const index = mockProjectTree.findIndex((node) => node.root === path);
3580 if (index >= 0) mockProjectTree.splice(index, 1);
3581 },
3582 async ContextUsageForTab() {
3583 return {
3584 used: 42124,
3585 window: 128000,
3586 sessionTokens: 34479,
3587 compactRatio: 0.8,
3588 sessionCost: 0.1287,
3589 sessionCurrency: "CNY",
3590 sessionCostQuote: {
3591 original: { amount: "0.1287", currency: "CNY" },
3592 selected: { amount: "0.1287", currency: "CNY" },
3593 estimated: true,
3594 costComplete: true,
3595 displayComplete: true,
3596 complete: true,
3597 displayStatus: "matched",
3598 aggregateMode: "single_currency",
3599 rateBand: "mixed",
3600 },
3601 };
3602 },
3603 async Balance() {
3604 // Mirror the active mock provider: deepseek-flash carries a balance_url.
3605 const p = settings.providers.find((x) => x.name === settings.defaultModel);
3606 if (!p?.balanceUrl) return { available: false, display: "" };
3607 return { available: true, display: "¥128.50" };
3608 },
3609 async BalanceForTab() {
3610 return this.Balance();
3611 },
3612 async UsageStats() {
3613 // Browser dev mock has no stats files; the panel does not consume
3614 // provider aggregates, so keep this initial-bundle fallback lean.
3615 return { from: "", to: "", tokens: 0, requests: 0, turns: 0, cacheHit: 0, cacheMiss: 0, activeDays: 0, topModel: "", daily: [], models: [] } as unknown as UsageStatsRange;
3616 },
3617 async Jobs() {
3618 return []; // browser dev mock has no background jobs
3619 },
3620 async JobsForTab() {
3621 return this.Jobs();
3622 },
3623 async CancelJob() {
3624 return false;
3625 },
3626 async CancelJobForTab(_tabID, jobID) {
3627 return this.CancelJob(jobID);
3628 },
3629 async CancelJobsForTab(_tabID, jobIDs) {
3630 return { cancelled: [], notRunning: [...jobIDs] };
3631 },
3632 async ActiveWorkForTab() {
3633 return { running: false, pendingPrompt: false, cancellable: false, jobs: [] };
3634 },
3635 async BackgroundRuntimes() {
3636 return [];
3637 },
3638 async RevealBackgroundRuntime() {
3639 throw new Error("background runtime is unavailable in browser preview");
3640 },
3641 async WorkspaceConflictForTab() {
3642 return {
3643 state: "none", ownerWork: { running: false, pendingPrompt: false, cancellable: false, jobs: [] },
3644 canReveal: false, canCreateWorktree: false,
3645 };
3646 },
3647 async RevealWorkspaceWriterForTab() {
3648 throw new Error("workspace writer is unavailable in browser preview");
3649 },
3650 async CloseTabWithPolicy(tabID) {
3651 return this.CloseTab(tabID);
3652 },
3653 async ToolResultForTab() {
3654 return null;
3655 },
3656 async Meta() {
3657 const active = withMockSessionIdentity(mockTabs.find((tab) => tab.active) ?? mockTabs[0]);
3658 const toolApprovalMode = normalizeToolApprovalMode(active?.toolApprovalMode, active ? normalizeMode(active.mode) : "normal", settings.autoApproveTools);
3659 const autoApproveTools = toolApprovalMode === "danger-full-access";
3660 const collaborationMode = normalizeCollaborationMode(active?.collaborationMode, active?.goal, active ? normalizeMode(active.mode) : "normal");
3661 const workspacePath = active?.workspacePath || active?.workspaceRoot || active?.cwd || cwd;
3662 return {
3663 label: active?.label ?? "DeepSeek-R1",
3664 ready: active?.ready ?? true,
3665 eventChannel: EVENT_CHANNEL,
3666 cwd: active?.cwd || cwd,
3667 workspaceRoot: active?.workspaceRoot || workspacePath,
3668 workspaceName: active?.workspaceName,
3669 workspacePath,
3670 ...mockSessionMeta(active),
3671 sandboxPath: settings.sandbox.workspaceRoot,
3672 gitBranch: active?.gitBranch || (active?.scope === "project" ? "main" : ""),
3673 imageInputEnabled: true,
3674 autoApproveTools,
3675 bypass: autoApproveTools,
3676 collaborationMode,
3677 toolApprovalMode,
3678 goal: active?.goal ?? "",
3679 goalStatus: active?.goalStatus ?? (active?.goal ? "running" : "stopped"),
3680 };
3681 },
3682 async MetaForTab(tabID) {
3683 const tab = withMockSessionIdentity(mockTabs.find((item) => item.id === tabID) ?? mockTabs.find((item) => item.active) ?? mockTabs[0]);
3684 const toolApprovalMode = normalizeToolApprovalMode(tab?.toolApprovalMode, tab ? normalizeMode(tab.mode) : "normal", settings.autoApproveTools);
3685 const autoApproveTools = toolApprovalMode === "danger-full-access";
3686 const collaborationMode = normalizeCollaborationMode(tab?.collaborationMode, tab?.goal, tab ? normalizeMode(tab.mode) : "normal");
3687 const workspacePath = tab?.workspacePath || tab?.workspaceRoot || tab?.cwd || cwd;
3688 return {
3689 label: tab?.label ?? "DeepSeek-R1",
3690 ready: tab?.ready ?? true,
3691 eventChannel: EVENT_CHANNEL,
3692 cwd: tab?.cwd || cwd,
3693 workspaceRoot: tab?.workspaceRoot || workspacePath,
3694 workspaceName: tab?.workspaceName,
3695 workspacePath,
3696 ...mockSessionMeta(tab),
3697 sandboxPath: settings.sandbox.workspaceRoot,
3698 gitBranch: tab?.gitBranch || (tab?.scope === "project" ? "main" : ""),
3699 autoApproveTools,
3700 bypass: autoApproveTools,
3701 collaborationMode,
3702 toolApprovalMode,
3703 goal: tab?.goal ?? "",
3704 goalStatus: tab?.goalStatus ?? (tab?.goal ? "running" : "stopped"),
3705 };
3706 },
3707 async Commands() {
3708 const commands: CommandInfo[] = [
3709 { name: "new", description: "start new session; save transcript", kind: "builtin" as const, group: "actions" },
3710 { name: "clear", description: "discard current context", kind: "builtin" as const, group: "actions" },
3711 { name: "compact", description: "Summarize older history to free up context", kind: "builtin" as const, group: "actions" },
3712 { name: "model", description: "Switch model", kind: "builtin" as const, group: "actions" },
3713 { name: "effort", description: "Set reasoning effort", kind: "builtin" as const, group: "actions" },
3714 { name: "skill", description: "List skills", kind: "builtin" as const, group: "skills" },
3715 { name: "mcp", description: "Manage MCP servers", kind: "builtin" as const, group: "integrations" },
3716 { name: "plugins", description: "Manage plugin packages", kind: "builtin" as const, group: "integrations" },
3717 { name: "review", description: "Review the staged diff", hint: "[focus]", kind: "custom" as const, group: "skills" },
3718 ];
3719 const seen = new Set(commands.map((command) => command.name));
3720 for (const skill of capSkills) {
3721 if (skill.enabled === false) continue;
3722 const name = (skill.invocation || `/${skill.name}`).replace(/^\/+/, "");
3723 if (!name || seen.has(name)) continue;
3724 seen.add(name);
3725 commands.push({
3726 name,
3727 description: skill.description,
3728 kind: skill.runAs === "subagent" ? "subagent" : "skill",
3729 group: skill.runAs === "subagent" ? "subagents" : "skills",
3730 color: skill.color,
3731 });
3732 }
3733 return commands;
3734 },
3735 async Capabilities() {
3736 return {
3737 servers: capServers.map((s) => ({ ...s })),
3738 skills: capSkills.map((s) => ({ ...s })),
3739 skillRoots: capSkillRoots.map((s) => ({ ...s })),
3740 plugins: capPlugins.map((p) => ({ ...p })),
3741 };
3742 },
3743 async MCPServers() {
3744 return capServers.map((s) => ({ ...s }));
3745 },
3746 async MCPCapabilityMatrix() {
3747 return { views: [], hostProfile: "desktop-apps-2026-01-26-v1" };
3748 },
3749 async MCPMarketplace(query: string) {
3750 const servers = [
3751 {
3752 name: "io.modelcontextprotocol/server-filesystem",
3753 suggestedName: "server-filesystem",
3754 title: "Filesystem",
3755 description: "Secure file operations through MCP.",
3756 version: "1.0.0",
3757 installable: true,
3758 transport: "stdio",
3759 command: "npx",
3760 args: ["-y", "@modelcontextprotocol/server-filesystem@1.0.0"],
3761 },
3762 {
3763 name: "io.example/manual",
3764 suggestedName: "manual",
3765 title: "Manual setup example",
3766 description: "Requires an API key before installation.",
3767 version: "1.0.0",
3768 installable: false,
3769 unavailableReason: "package requires environment variables or arguments",
3770 args: [],
3771 },
3772 ];
3773 const normalized = query.trim().toLowerCase();
3774 return {
3775 servers: normalized ? servers.filter((entry) => [entry.name, entry.title, entry.description].join(" ").toLowerCase().includes(normalized)) : servers,
3776 cached: false,
3777 } as MCPMarketplaceView;
3778 },
3779 async MCPMarketplaceResolve(registryName: string) {
3780 const result = await this.MCPMarketplace(registryName);
3781 const entry = result.servers.find((candidate) => candidate.name.toLowerCase() === registryName.trim().toLowerCase());
3782 if (!entry) throw new Error(`MCP Registry has no server named ${JSON.stringify(registryName)}`);
3783 return entry;
3784 },
3785 async SkillsSettings() {
3786 return {
3787 skills: capSkills.map((s) => ({ ...s })),
3788 skillRoots: capSkillRoots.map((s) => ({ ...s })),
3789 allowImplicitInvocation: true,
3790 };
3791 },
3792 async RuntimeDoctor() {
3793 return {
3794 text: "runtime status: mock\nrecoverability: clean=true irreversible=false\nresume: allow=true cleanRollback=true\n",
3795 publishedGeneration: 0,
3796 allowResume: true,
3797 cleanRollback: true,
3798 hasIrreversible: false,
3799 noOpRebuilds: 0,
3800 fullRebuilds: 0,
3801 subgraphRebuilds: 0,
3802 staleDrops: 0,
3803 admissionRejected: 0, runtimeOwnerFallbacks: 0,
3804 };
3805 },
3806 async CapabilityDiagnostics(includeSessionRuntime: boolean) {
3807 const report: CapabilityDiagnosticsReport = {
3808 schema_version: 1,
3809 root: "<workspace>",
3810 live: false,
3811 summary: {
3812 errors: 0,
3813 warnings: 1,
3814 infos: includeSessionRuntime ? 1 : 0,
3815 instructions: 1,
3816 skills: capSkills.length,
3817 commands: 0,
3818 hooks: 0,
3819 plugins: capPlugins.length,
3820 mcp_servers: capServers.length,
3821 },
3822 instructions: { docs: [{ path: "<workspace>/AGENTS.md", scope: "project", directory: "<workspace>", depth: 0, order: 1 }] },
3823 skills: {
3824 roots: [{ path: "<workspace>/.reasonix/skills", scope: "project", status: "ok" }],
3825 entries: capSkills.map((s) => ({
3826 name: s.name,
3827 description: s.description,
3828 scope: s.scope,
3829 path: "(mock)",
3830 status: "winner",
3831 run_as: s.runAs,
3832 })),
3833 winners: capSkills.length,
3834 shadowed: 0,
3835 },
3836 commands: { roots: [], entries: [], winners: 0, shadowed: 0 },
3837 hooks: { trusted_project: true, project_defines_hooks: false, sources: [], entries: [] },
3838 plugins: {
3839 packages: capPlugins.map((p) => ({
3840 name: p.name,
3841 enabled: p.enabled,
3842 root: p.root || "<external>/plugin",
3843 skills: p.skills ?? 0,
3844 commands: 0,
3845 hooks: p.hooks ?? 0,
3846 mcp_servers: p.mcpServers ?? 0,
3847 status: p.enabled ? "ok" : "disabled",
3848 })),
3849 },
3850 mcp: {
3851 servers: capServers.map((s) => ({
3852 name: s.name,
3853 transport: s.transport || "stdio",
3854 start_intent: s.startIntent === "off" ? "off" : "automatic",
3855 source: "toml",
3856 runtime_status: includeSessionRuntime ? s.status || "connected" : undefined,
3857 tool_count: s.tools,
3858 env_keys: s.envKeys ?? [],
3859 header_keys: s.headerKeys ?? [],
3860 })),
3861 },
3862 issues: [
3863 {
3864 severity: "warning",
3865 code: "skill.missing_description",
3866 subsystem: "skills",
3867 name: "example",
3868 message: "mock warning for browser harness",
3869 remediation: "Add a description frontmatter field",
3870 settings_tab: "skills",
3871 },
3872 ...(includeSessionRuntime
3873 ? [{
3874 severity: "info" as const,
3875 code: "mcp.runtime_unavailable",
3876 subsystem: "mcp",
3877 message: "browser mock has no live Host; runtime fields are synthetic",
3878 settings_tab: "mcp",
3879 }]
3880 : []),
3881 ],
3882 };
3883 return JSON.parse(JSON.stringify(report)) as CapabilityDiagnosticsReport;
3884 },
3885 async CredentialDiagnostics(_probe: boolean) {
3886 return credentialDiagnostics();
3887 },
3888 async RepairCredentials(dryRun: boolean) {
3889 return credentialDiagnostics([dryRun ? "would repair credential access" : "repaired credential access"]);
3890 },
3891 async RetryAuthenticationForTab(_tabId: string) {
3892 return { status: "ready" };
3893 },
3894 async Plugins() {
3895 return capPlugins.map((p) => ({ ...p }));
3896 },
3897 async PlanPluginInstall(source: string, options: PluginInstallOptions) {
3898 const name = options.name || source.split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || "plugin";
3899 return JSON.stringify({
3900 ok: true,
3901 status: "planned",
3902 kind: "plugin",
3903 actions: [{ kind: "plugin", action: "install_plugin_package", name, source, status: "planned" }],
3904 });
3905 },
3906 async InstallPlugin(source: string, options: PluginInstallOptions) {
3907 const name = options.name || source.split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || "plugin";
3908 const existing = capPlugins.findIndex((p) => p.name === name);
3909 const view: PluginView = {
3910 name,
3911 version: "dev",
3912 description: "Mock plugin",
3913 source,
3914 root: `~/.reasonix/plugins/${name}`,
3915 manifestKind: "reasonix",
3916 enabled: true,
3917 skills: 1,
3918 hooks: 0,
3919 mcpServers: 0,
3920 skillDetails: [{ name: "plan", description: "Plan work before implementation", invocation: "/plan", runAs: "inline" }],
3921 };
3922 if (existing >= 0) capPlugins[existing] = view;
3923 else capPlugins.push(view);
3924 return JSON.stringify({ ok: true, status: "done", kind: "plugin", actions: [{ kind: "plugin", name }] });
3925 },
3926 async RemovePlugin(name: string) {
3927 capPlugins = capPlugins.filter((p) => p.name !== name);
3928 },
3929 async SetPluginEnabled(name: string, enabled: boolean) {
3930 capPlugins = capPlugins.map((p) => p.name === name ? { ...p, enabled } : p);
3931 },
3932 async UpdatePlugin(name: string) {
3933 capPlugins = capPlugins.map((p) => p.name === name ? { ...p, version: p.version || "dev" } : p);
3934 return JSON.stringify({ ok: true, status: "done", kind: "plugin", name });
3935 },
3936 async PluginDoctor(name: string) {
3937 return capPlugins.find((p) => p.name === name) || {
3938 name,
3939 root: "",
3940 enabled: false,
3941 skills: 0,
3942 hooks: 0,
3943 mcpServers: 0,
3944 error: "plugin is not installed",
3945 };
3946 },
3947 async AddMCPServer(input: MCPServerInput) {
3948 const tools = input.transport === "stdio" ? 3 : 5;
3949 capServers.push({
3950 name: input.name,
3951 transport: input.transport,
3952 status: "connected",
3953 configured: true,
3954 autoStart: true,
3955 tier: "background",
3956 command: input.command,
3957 args: input.args,
3958 url: input.url,
3959 envKeys: input.env ? Object.keys(input.env).sort() : undefined,
3960 headerKeys: input.headers ? Object.keys(input.headers).sort() : undefined,
3961 tools,
3962 prompts: 0,
3963 resources: 0,
3964 toolList: Array.from({ length: tools }, (_, i) => ({
3965 name: `${input.name}_tool_${i + 1}`,
3966 description: `Mock tool ${i + 1} exposed by ${input.name}.`,
3967 })),
3968 });
3969 return tools;
3970 },
3971 async InstallMCPServer(input: MCPServerInput) {
3972 const tools = await this.AddMCPServer(input);
3973 return { name: input.name, state: "ready" as const, toolCount: tools, action: "none" as const, message: `${input.name} is ready` };
3974 },
3975 async UpdateMCPServer(name: string, input: MCPServerInput) {
3976 capServers = capServers.map((s) => {
3977 if (s.name !== name) return s;
3978 const connected = s.status === "connected" || s.status === "failed" || s.autoStart !== false;
3979 const nextStatus = s.status === "disabled" ? "disabled" : connected ? "connected" : "deferred";
3980 const nextTools = nextStatus === "connected" ? s.tools || (input.transport === "stdio" ? 3 : 5) : 0;
3981 return {
3982 ...s,
3983 transport: input.transport,
3984 status: nextStatus,
3985 command: input.transport === "stdio" ? input.command : "",
3986 args: input.transport === "stdio" ? input.args : [],
3987 url: input.transport === "stdio" ? "" : input.url,
3988 envKeys: input.env ? Object.keys(input.env).sort() : s.envKeys,
3989 headerKeys: input.headers ? Object.keys(input.headers).sort() : s.headerKeys,
3990 tools: nextTools,
3991 error: undefined,
3992 authStatus: nextStatus !== "connected" && input.transport !== "stdio" ? "possible" : undefined,
3993 authUrl: nextStatus !== "connected" && input.transport !== "stdio" ? input.url : undefined,
3994 };
3995 });
3996 },
3997 async RemoveMCPServer(name: string) {
3998 capServers = capServers.filter((s) => s.name !== name);
3999 },
4000 async AuthorizeAndConnectMCPServer(name: string) {
4001 capServers = capServers.map((s) => s.name === name
4002 ? { ...s, status: "connected", runtimeState: "ready", tools: s.tools || 4, error: undefined, requiresLaunchApproval: false }
4003 : s);
4004 },
4005 async AuthenticateMCPServer(name: string) {
4006 capServers = capServers.map((s) => s.name === name
4007 ? { ...s, status: "connected", runtimeState: "ready", tools: s.tools || 4, error: undefined, authStatus: "none", authUrl: undefined }
4008 : s);
4009 },
4010 async ReconnectMCPServer(name: string) {
4011 capServers = capServers.map((s) =>
4012 s.name === name
4013 ? { ...s, status: "initializing", error: undefined, authStatus: undefined, authUrl: undefined }
4014 : s,
4015 );
4016 await new Promise((r) => setTimeout(r, 400));
4017 capServers = capServers.map((s) =>
4018 s.name === name ? { ...s, status: "connected", tools: s.tools || 4 } : s,
4019 );
4020 },
4021 async ClearMCPServerAuthentication(name: string) {
4022 capServers = capServers.map((s) =>
4023 s.name === name
4024 ? {
4025 ...s,
4026 status: s.autoStart === false ? "disabled" : "initializing",
4027 tools: 0,
4028 error: undefined,
4029 authStatus: s.transport !== "stdio" ? "possible" : undefined,
4030 authUrl: s.transport !== "stdio" ? s.url : undefined,
4031 authConfigured: undefined,
4032 }
4033 : s,
4034 );
4035 },
4036 async PickSkillFolder() {
4037 return "~/my-skills";
4038 },
4039 async PickPluginFolder() {
4040 return "~/plugins/superpowers";
4041 },
4042 async AddSkillPath(path: string) {
4043 const dir = path.trim() || "~/my-skills";
4044 if (!capSkillRoots.some((r) => r.scope === "custom" && r.dir === dir)) {
4045 capSkillRoots.push({
4046 dir,
4047 scope: "custom",
4048 priority: capSkillRoots.length + 1,
4049 status: "ok",
4050 enabled: true,
4051 configured: true,
4052 removable: true,
4053 skills: 1,
4054 skillItems: [{ name: "local-dev", description: "Local custom development workflow", scope: "custom", runAs: "inline" }],
4055 });
4056 }
4057 if (!capSkills.some((s) => s.name === "local-dev")) {
4058 capSkills.push({ name: "local-dev", description: "Local custom development workflow", scope: "custom", runAs: "inline", enabled: true });
4059 }
4060 },
4061 async RemoveSkillPath(path: string) {
4062 capSkillRoots = capSkillRoots.filter((r) => r.dir !== path);
4063 if (!capSkillRoots.some((r) => r.scope === "custom")) {
4064 const idx = capSkills.findIndex((s) => s.name === "local-dev");
4065 if (idx >= 0) capSkills.splice(idx, 1);
4066 }
4067 },
4068 async SetSkillPathEnabled(path: string, enabled: boolean) {
4069 const root = capSkillRoots.find((r) => r.dir === path);
4070 if (root) {
4071 root.enabled = enabled;
4072 root.status = enabled ? "ok" : "disabled";
4073 root.skills = enabled ? (root.skillItems?.length ?? 0) : 0;
4074 }
4075 },
4076 async RefreshSkills() {},
4077 async ReloadCommands() {},
4078 async SetSkillEnabled(name: string, enabled: boolean) {
4079 const skill = capSkills.find((s) => s.name === name);
4080 if (skill) skill.enabled = enabled;
4081 },
4082 async SetSkillImplicitInvocation(_enabled: boolean) {},
4083 async AvailableSubagentTools() {
4084 return [
4085 { name: "read_file", description: "Read a file's contents", readOnlyHint: true },
4086 { name: "ls", description: "List a directory", readOnlyHint: true },
4087 { name: "glob", description: "Find files by name pattern", readOnlyHint: true },
4088 { name: "grep", description: "Search file contents", readOnlyHint: true },
4089 { name: "code_index", description: "Look up symbol definitions and file outlines", readOnlyHint: true },
4090 { name: "edit_file", description: "Edit an existing file" },
4091 { name: "write_file", description: "Write a new file" },
4092 { name: "bash", description: "Run a shell command" },
4093 { name: "web_fetch", description: "Fetch a URL" },
4094 ];
4095 },
4096 async CreateSubagentProfile(input: SubagentProfileInput) {
4097 const name = input.name.trim();
4098 const builtinNames = ["init", "explore", "research", "install-capability", "review", "security-review", "test"];
4099 if (builtinNames.includes(name)) throw new Error(`"${name}" is a built-in subagent name and cannot be reused`);
4100 if (capSkills.some((s) => s.name === name)) throw new Error(`"${name}" already exists`);
4101 capSkills.push({
4102 name, description: input.description, scope: input.scope === "project" ? "project" : "global",
4103 runAs: "subagent", enabled: true, model: input.model, effort: input.effort,
4104 allowedTools: input.allowedTools, color: input.color, invocation: `/${name}`, invocationMode: "manual",
4105 });
4106 return `~/.reasonix/skills/${name}/SKILL.md`;
4107 },
4108 async UpdateSubagentProfile(name: string, scope: string, input: SubagentProfileInput) {
4109 const skill = capSkills.find((s) => s.name === name && s.scope === scope);
4110 if (!skill) throw new Error(`"${name}" resolves at a different scope — refusing to update`);
4111 skill.description = input.description;
4112 skill.color = input.color;
4113 skill.model = input.model;
4114 skill.effort = input.effort;
4115 skill.allowedTools = input.allowedTools;
4116 },
4117 async DeleteSubagentProfile(name: string, scope: string) {
4118 const idx = capSkills.findIndex((s) => s.name === name && s.scope === scope);
4119 if (idx < 0) throw new Error(`"${name}" resolves at a different scope — refusing to delete`);
4120 capSkills.splice(idx, 1);
4121 },
4122 async SetSubagentProfileModel(name: string, ref: string) {
4123 const skill = capSkills.find((s) => s.name === name);
4124 if (skill) skill.configuredModel = ref || undefined;
4125 },
4126 async SetSubagentProfileEffort(name: string, level: string) {
4127 const skill = capSkills.find((s) => s.name === name);
4128 if (skill) skill.configuredEffort = level || undefined;
4129 },
4130 async CancelTrySubagentProfile() {},
4131 async TrySubagentProfile(input: SubagentProfileInput, task: string) {
4132 if (!task.trim()) throw new Error("task is required");
4133 if (!input.systemPrompt.trim()) throw new Error("system prompt is required");
4134 await new Promise((resolve) => setTimeout(resolve, 400));
4135 return `[mock run of "${input.name || "draft"}"]\n\nTask: ${task}\n\n(This is a dev-mode mock response — the real backend runs an isolated subagent loop against your configured model.)`;
4136 },
4137 async SetMCPServerEnabled(name: string, enabled: boolean) {
4138 capServers = capServers.map((s) =>
4139 s.name === name
4140 ? {
4141 ...s,
4142 status: enabled ? "connected" : "disabled",
4143 autoStart: s.builtIn ? enabled : s.autoStart,
4144 tools: enabled ? s.tools || 4 : 0,
4145 error: undefined,
4146 authStatus: !enabled && s.transport !== "stdio" ? "possible" : undefined,
4147 authUrl: !enabled && s.transport !== "stdio" ? s.url : undefined,
4148 }
4149 : s,
4150 );
4151 },
4152 async SetMCPServerTier(name: string, tier: string) {
4153 capServers = capServers.map((s) => {
4154 if (s.name !== name) return s;
4155 const tools = s.tools || (s.transport === "stdio" ? 3 : 5);
4156 return { ...s, tier, autoStart: true, status: "connected", tools, error: undefined, authStatus: undefined, authUrl: undefined };
4157 });
4158 },
4159 async SlashArgs(input: string) {
4160 // Mirror a slice of the real arg hints so the menu is exercisable in browser dev.
4161 const from = input.lastIndexOf(" ") + 1;
4162 const cur = input.slice(from);
4163 const cmd = input.slice(0, input.indexOf(" ") < 0 ? input.length : input.indexOf(" "));
4164 const subs: Record<string, { label: string; insert: string; hint: string; descend?: boolean }[]> = {
4165 "/skill": [
4166 { label: "list", insert: "list", hint: "list skills" },
4167 { label: "show", insert: "show ", hint: "show a skill's body", descend: true },
4168 { label: "enable", insert: "enable ", hint: "enable a disabled skill", descend: true },
4169 { label: "disable", insert: "disable ", hint: "disable an enabled skill", descend: true },
4170 { label: "new", insert: "new ", hint: "scaffold a new skill" },
4171 { label: "paths", insert: "paths", hint: "show discovery paths" },
4172 ],
4173 "/hooks": [
4174 { label: "list", insert: "list", hint: "list active hooks" },
4175 ],
4176 "/model": [
4177 { label: "deepseek/deepseek-v4-flash", insert: "deepseek/deepseek-v4-flash", hint: "current" },
4178 { label: "deepseek/deepseek-v4-pro", insert: "deepseek/deepseek-v4-pro", hint: "" },
4179 ],
4180 "/effort": [
4181 { label: "auto", insert: "auto", hint: "use the model default" },
4182 { label: "high", insert: "high", hint: "deeper reasoning" },
4183 { label: "max", insert: "max", hint: "maximum reasoning" },
4184 ],
4185 };
4186 const items = (subs[cmd] ?? [])
4187 .filter((it) => it.label.toLowerCase().startsWith(cur.toLowerCase()))
4188 .map((it) => ({ label: it.label, insert: it.insert, hint: it.hint, descend: it.descend ?? false }));
4189 return { items, from };
4190 },
4191 async ListDir(rel: string) {
4192 // A tiny fake tree so the @ menu is navigable in browser dev.
4193 if (rel === "" || rel === "./") {
4194 return [
4195 { name: "internal", isDir: true },
4196 { name: "desktop", isDir: true },
4197 { name: "README.md", isDir: false },
4198 { name: "go.mod", isDir: false },
4199 ];
4200 }
4201 if (rel === "internal/") {
4202 return [
4203 { name: "control", isDir: true },
4204 { name: "boot", isDir: true },
4205 { name: "event.go", isDir: false },
4206 ];
4207 }
4208 return [{ name: "file.go", isDir: false }];
4209 },
4210 async ListDirForTab(_tabID: string, rel: string) {
4211 return this.ListDir(rel);
4212 },
4213 async ListDirForTarget(_target: ComposerTarget, rel: string) {
4214 return this.ListDir(rel);
4215 },
4216 async SearchFileRefs(query: string) {
4217 const q = query.toLowerCase();
4218 return ["desktop/frontend/src/lib/bridge.ts", "desktop/frontend/src/main.tsx", "internal/control/refs.go"]
4219 .filter((path) => path.split("/").pop()?.toLowerCase().includes(q))
4220 .map((name) => ({ name, isDir: false }));
4221 },
4222 async SearchFileRefsForTab(_tabID: string, query: string) {
4223 return this.SearchFileRefs(query);
4224 },
4225 async SearchFileRefsForTarget(_target: ComposerTarget, query: string) {
4226 return this.SearchFileRefs(query);
4227 },
4228 async ReadFile(rel: string) {
4229 return mockWorkspaceFile(rel);
4230 },
4231 async ReadFileForTab(_tabID: string, rel: string) {
4232 return this.ReadFile(rel);
4233 },
4234 async CreateWorkspaceBrowserPreviewForTab(_tabID: string, rel: string) {
4235 return `http://127.0.0.1:0/__reasonix_workspace_media/mock/${encodeURIComponent(rel)}`;
4236 },
4237 async ReadPresentedFileForTab(tabID: string, _toolCallID: string, path: string) {
4238 return this.ReadFileForTab(tabID, path);
4239 },
4240 async ReadPresentedFileSourceForTab(tabID: string, _toolCallID: string, path: string) {
4241 return this.ReadFileForTab(tabID, path);
4242 },
4243 async ReadPresentedTextPageForTab(_tabID: string, _toolCallID: string, path: string, offset: number, expectedVersion: string) {
4244 return { path, body: "", offset, nextOffset: offset, size: offset, hasMore: false, version: expectedVersion };
4245 },
4246 async ResolveChatFileReferencesForTab(_tabID: string, turnKey: string, candidates: ChatFileReferenceRequest[]): Promise<ChatFileReferenceResult> {
4247 return {
4248 turnKey,
4249 references: candidates.map(candidate => ({
4250 key: candidate.key,
4251 path: candidate.path,
4252 status: "unavailable" as const,
4253 actions: [],
4254 reason: "not-found" as const,
4255 })),
4256 };
4257 },
4258 async ReadReferenceFileForTab(tabID: string, path: string) {
4259 return this.ReadFileForTab(tabID, path);
4260 },
4261 async ReadReferenceFileSourceForTab(tabID: string, path: string) {
4262 return this.ReadFileForTab(tabID, path);
4263 },
4264 async SanitizeMarkdownSVG(): Promise<MarkdownSVGView> {
4265 return { ok: false, reason: "unsupported" };
4266 },
4267 async CreatePresentedBrowserPreviewForTab(tabID: string, _toolCallID: string, path: string) {
4268 return this.CreateWorkspaceBrowserPreviewForTab(tabID, path);
4269 },
4270 async RevokeWorkspaceBrowserPreview() {},
4271 async RevokeWorkspaceMediaPreview() {},
4272 async SaveRemoteFileAs(_hostID: string, remotePath: string) {
4273 return remotePath;
4274 },
4275 async SaveRemotePresentedFileAs(_tabID: string, hostID: string, _toolCallID: string, remotePath: string) {
4276 return this.SaveRemoteFileAs(hostID, remotePath);
4277 },
4278 async ResolveRemotePresentedPathForTab(_tabID: string, _hostID: string, _toolCallID: string, remotePath: string) {
4279 return remotePath.startsWith("/") ? remotePath : `/remote/workspace/${remotePath}`;
4280 },
4281 async ResolveRemoteWorkspacePathForTab(_tabID: string, _hostID: string, _toolCallID: string, remotePath: string) {
4282 return remotePath.startsWith("/") ? remotePath : `/remote/workspace/${remotePath}`;
4283 },
4284 async ResolveMarkdownImageForTab(_tabID: string, source: string) {
4285 return { url: source, openHref: source };
4286 },
4287 async WorkspaceRevisionForTab(_tabID: string) {
4288 return { revisions: { content: 0, tree: 0, workingTree: 0, gitMeta: 0, session: 0 }, watchState: "active" as const };
4289 },
4290 async WorkspaceChanges(_tabID: string) {
4291 return {
4292 gitAvailable: true,
4293 gitBranch: "main",
4294 files: [
4295 {
4296 path: "desktop/frontend/src/components/WorkspacePanel.tsx",
4297 sources: ["session", "git"],
4298 gitStatus: "M",
4299 turns: [0, 2],
4300 latestPrompt: "Mock session edited the workspace panel.",
4301 latestTime: Date.now() - 60_000,
4302 },
4303 { path: "README.md", sources: ["git"], gitStatus: "??" },
4304 { path: "internal/control/controller.go", sources: ["session"], turns: [1], latestTime: Date.now() - 120_000 },
4305 ],
4306 };
4307 },
4308 async WorkspaceTurnChanges(_tabID: string, _sessionPath: string, turn: number, _resultID: string) {
4309 return { turn, coverage: "unknown" as const, files: [], reasons: [], added: 0, removed: 0 };
4310 },
4311 async WorkspaceTurnChangeDetail() { return null; },
4312 async TurnCheckLog() { return null; },
4313 async WorkspaceChangeDetail(_tabID: string, path: string) {
4314 return {
4315 source: "git" as const,
4316 added: 2,
4317 removed: 1,
4318 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1,2 +1,3 @@\n-old line\n+new line\n context\n+another line`,
4319 };
4320 },
4321 async GitBranches() {
4322 return ["main", "dev", "feature/branch-switcher"];
4323 },
4324 async GitBranchesForTab(_tabID: string, _workspaceRoot: string) { return this.GitBranches(); },
4325 async GitCheckoutForTab(_tabID: string, _workspaceRoot: string, branch: string) { await this.GitCheckout(branch); },
4326 async GitCreateBranchForTab(_tabID: string, _workspaceRoot: string, name: string) { await this.GitCreateBranch(name); },
4327 async WorkspaceGitStatsForTab(tabID: string, _workspaceRoot: string) { return this.WorkspaceChanges(tabID); },
4328 async GitCheckout(_branch: string) {
4329 console.info("mock GitCheckout", _branch);
4330 },
4331 async GitCreateBranch(_name: string) {
4332 console.info("mock GitCreateBranch", _name);
4333 },
4334 async WorkspaceGitHistory(_tabID: string, path: string) {
4335 return [
4336 { hash: "abcdef123456", author: "Mock Author", date: new Date().toISOString(), message: "Mock commit message for " + path },
4337 ];
4338 },
4339 async WorkspaceGitCommitDetail(_tabID: string, _hash: string, path: string) {
4340 if (path) {
4341 return { diff: "--- a/mock\n+++ b/mock\n@@ -1,1 +1,1 @@\n-mock\n+mock diff" };
4342 }
4343 return { files: ["mock_file_1.ts", "mock_file_2.ts"] };
4344 },
4345 async OpenLocalPath(path: string) {
4346 console.info("mock OpenLocalPath", path);
4347 },
4348 async OpenWorkspacePathForTab(_tabID: string, rel: string) {
4349 console.info("mock OpenWorkspacePath", rel);
4350 },
4351 async OpenPresentedPathForTab(tabID: string, _toolCallID: string, path: string) {
4352 return this.OpenWorkspacePathForTab(tabID, path);
4353 },
4354 async OpenReferencePathForTab(_tabID: string, path: string) {
4355 console.info("mock OpenReferencePathForTab", path);
4356 },
4357 async ResolvePresentedPathForTab(tabID: string, _toolCallID: string, path: string) {
4358 return this.ResolveWorkspacePathForTab(tabID, path);
4359 },
4360 async ResolveReferencePathForTab(_tabID: string, path: string) {
4361 return path;
4362 },
4363 async ResolveWorkspacePathForTab(_tabID: string, rel: string) { return `${cwd.replace(/[\\/]+$/, "")}/${rel.replace(/^[/\\]+/, "").replace(/[\\/]+$/, "")}`; },
4364 async ExternalOpeners() {
4365 return {
4366 openers: [
4367 { id: "vscode", name: "VS Code", kind: "editor", iconDataUrl: mockExternalOpenerIconDataURL("#1684d6", "V") },
4368 { id: "cursor", name: "Cursor", kind: "editor", iconDataUrl: mockExternalOpenerIconDataURL("#25262a", "C") },
4369 { id: "finder", name: "Finder", kind: "file-manager", iconDataUrl: mockExternalOpenerIconDataURL("#36aaf4", "F") },
4370 { id: "ghostty", name: "Ghostty", kind: "terminal", iconDataUrl: mockExternalOpenerIconDataURL("#264db6", ">") },
4371 ],
4372 preferred: "vscode",
4373 } as ExternalOpenersView;
4374 }, async ExternalOpenersForTab(_tabID: string) { return { ...(await this.ExternalOpeners()), workspaceOpenable: true }; },
4375 async SetPreferredExternalOpener(_id: string) {},
4376 async OpenWorkspaceInExternalOpenerForTab(_tabID: string, _id: string) {}, async OpenLocalPathInExternalOpener(path: string, id: string) { console.info("mock OpenLocalPathInExternalOpener", path, id); }, async SaveLocalPathAs(path: string) { console.info("mock SaveLocalPathAs", path); return path; },
4377 async RevealWorkspacePathForTab(_tabID: string, rel: string) {
4378 console.info("mock RevealWorkspacePath", rel);
4379 },
4380 async RevealPresentedPathForTab(tabID: string, _toolCallID: string, path: string) {
4381 return this.RevealWorkspacePathForTab(tabID, path);
4382 },
4383 async RevealReferencePathForTab(_tabID: string, path: string) {
4384 console.info("mock RevealReferencePathForTab", path);
4385 },
4386 async SaveWorkspacePathAsForTab(_tabID: string, rel: string) {
4387 console.info("mock SaveWorkspacePathAsForTab", rel);
4388 return rel;
4389 },
4390 async SavePresentedPathAsForTab(tabID: string, _toolCallID: string, path: string) {
4391 return this.SaveWorkspacePathAsForTab(tabID, path);
4392 },
4393 async SaveReferencePathAsForTab(_tabID: string, path: string) {
4394 return path;
4395 },
4396 async RevealPath(path: string) {
4397 console.info("mock RevealPath", path);
4398 },
4399 async PickExportFile(defaultFilename: string, _mimeType: string) {
4400 return defaultFilename;
4401 },
4402 async ExportGoalDiagnostics() {
4403 return "goal-diagnostics.json";
4404 },
4405 async ExportManualCreationDiagnostics() {
4406 return "reasonix-creation-diagnostics.json";
4407 },
4408 async SaveExportFile(path: string, payload: string, base64Encoded: boolean) {
4409 const a = document.createElement("a");
4410 let url = "";
4411 if (base64Encoded) {
4412 url = `data:application/octet-stream;base64,${payload}`;
4413 } else {
4414 url = URL.createObjectURL(new Blob([payload], { type: "text/plain;charset=utf-8" }));
4415 }
4416 a.href = url;
4417 a.download = path;
4418 document.body.appendChild(a);
4419 a.click();
4420 a.remove();
4421 if (!base64Encoded) URL.revokeObjectURL(url);
4422 },
4423 async SaveSessionMarkdownForTab(_tabID: string, path: string, title: string) {
4424 await this.SaveExportFile(path, `# ${title || "Reasonix session"}\n`, false);
4425 },
4426 async SaveExportImageFiles(path: string, payloads: string[]) {
4427 if (payloads.length === 0) throw new Error("No image payloads to export");
4428 const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
4429 const dot = path.lastIndexOf(".");
4430 const extensionStart = dot > slash ? dot : path.length;
4431 const stem = path.slice(0, extensionStart);
4432 const extension = path.slice(extensionStart);
4433 for (let index = 0; index < payloads.length; index++) {
4434 const partPath = payloads.length > 1
4435 ? `${stem}-${index + 1}-of-${payloads.length}${extension}`
4436 : path;
4437 await this.SaveExportFile(partPath, payloads[index], true);
4438 }
4439 },
4440 async Models() {
4441 const active = mockTabs.find((tab) => tab.active) ?? mockTabs[0];
4442 const current = mockTabModelRef(active);
4443 return mockModelCatalog.map((model) => ({ ...model, current: model.ref === current }));
4444 },
4445 async ModelsForTab(tabID) {
4446 const tab = mockTabs.find((item) => item.id === tabID) ?? mockTabs.find((item) => item.active) ?? mockTabs[0];
4447 const current = mockTabModelRef(tab);
4448 return mockModelCatalog.map((model) => ({ ...model, current: model.ref === current }));
4449 },
4450 async ModelsForDraft(draftID) {
4451 const current = (await this.GetSessionDraft(draftID)).settings.model;
4452 return mockModelCatalog.map((model) => ({ ...model, current: model.ref === current }));
4453 },
4454 async SetModel(name) {
4455 setMockTabModel(undefined, name);
4456 },
4457 async SetModelForTab(tabID, name) {
4458 setMockTabModel(tabID, name);
4459 },
4460 async Effort() {
4461 return { supported: true, current: mockEffort, default: "high", levels: ["auto", "high", "max"] };
4462 },
4463 async EffortForTab() {
4464 return this.Effort();
4465 },
4466 async SetEffort(level: string) {
4467 mockEffort = level || "auto";
4468 },
4469 async SetEffortForTab(_tabID, level) {
4470 await this.SetEffort(level);
4471 },
4472 async ReloadRuntime(_tabID) {},
4473 async Memory() {
4474 return {
4475 available: true,
4476 storeDir: "~/.reasonix/projects/-mock/memory",
4477 storeGlobalDir: "~/.reasonix/memory/global",
4478 docs: [
4479 {
4480 path: "REASONIX.md",
4481 scope: "project",
4482 directory: ".",
4483 body: "# Reasonix project memory\n\nMock doc shown in the browser dev seam.\n\n## Notes\n\n- prefers concise replies",
4484 imports: [],
4485 depth: 0,
4486 order: 0,
4487 precedence: 0,
4488 },
4489 {
4490 path: "~/.reasonix/REASONIX.md",
4491 scope: "user",
4492 body: t("mock.memoryBody"),
4493 imports: [],
4494 depth: -1,
4495 order: 1,
4496 precedence: 1,
4497 },
4498 ],
4499 instructionDiagnostics: [],
4500 facts: [
4501 {
4502 name: "prefers-tabs",
4503 description: "User prefers tabs",
4504 type: "user",
4505 scope: "project",
4506 body: "Indent with tabs.",
4507 freshness: "fresh",
4508 },
4509 ],
4510 archives: [
4511 {
4512 name: "old-plan",
4513 description: "Superseded planning note",
4514 type: "project",
4515 scope: "project",
4516 body: "This plan was archived after the implementation changed.",
4517 path: "~/.reasonix/projects/-mock/memory/.archive/20260612-021500.000-old-plan.md",
4518 archivedAt: "2026-06-12T02:15:00Z",
4519 freshness: "current",
4520 },
4521 ],
4522 scopes: [
4523 { scope: "user", path: "~/.reasonix/REASONIX.md" },
4524 { scope: "project", path: "REASONIX.md" },
4525 { scope: "local", path: "REASONIX.local.md" },
4526 ],
4527 conflicts: [],
4528 lastRecall: {
4529 query: "",
4530 hits: [],
4531 omitted: 0,
4532 charBudget: 2400,
4533 usedChars: 0,
4534 suppressed: "no user turn yet",
4535 },
4536 };
4537 },
4538 async MemorySuggestions() {
4539 return {
4540 memories: [
4541 {
4542 id: "memory-prefers-concise-replies",
4543 name: "prefers-concise-replies",
4544 title: "Prefers concise replies",
4545 description: "User prefers concise replies unless detail is requested.",
4546 type: "user",
4547 scope: "project",
4548 body: "User prefers concise replies unless detail is requested.\n\n**Why:** Suggested from recent local history.\n**How to apply:** Keep answers brief by default.",
4549 reason: "future-facing preference",
4550 evidence: ["mock-session: always keep replies concise"],
4551 },
4552 ],
4553 skills: [
4554 {
4555 id: "skill-reasonix-pr-followup",
4556 name: "reasonix-pr-followup",
4557 description: "Review or update a Reasonix GitHub PR, address feedback, verify, and publish safely.",
4558 scope: "project",
4559 body: "# Reasonix PR Followup\n\nUse this skill for repeated Reasonix PR work.\n\n## Workflow\n\n1. Confirm branch and PR state.\n2. Inspect the diff.\n3. Fix actionable feedback.\n4. Verify and update the PR.\n",
4560 reason: "recent history repeatedly touched PR workflows",
4561 evidence: ["mock-pr-session: 提交到pr,并更新内容", "mock-review-session: 解决该pr下机器人提出来的问题"],
4562 },
4563 ],
4564 generatedAt: new Date().toISOString(),
4565 available: true,
4566 source: "mock",
4567 };
4568 },
4569 async AcceptMemorySuggestion(suggestion: MemorySuggestion) {
4570 emit({ kind: "notice", level: "info", text: `saved suggested memory → ${suggestion.name}` });
4571 return `${suggestion.name}.md`;
4572 },
4573 async AcceptSkillSuggestion(suggestion: SkillSuggestion) {
4574 emit({ kind: "notice", level: "info", text: `created suggested skill → ${suggestion.name}` });
4575 return `.reasonix/skills/${suggestion.name}/SKILL.md`;
4576 },
4577 async MemorySuggestionsForTab(_tabID: string) {
4578 return this.MemorySuggestions();
4579 },
4580 async AcceptMemorySuggestionForTab(_tabID: string, suggestion: MemorySuggestion) {
4581 return this.AcceptMemorySuggestion(suggestion);
4582 },
4583 async AcceptSkillSuggestionForTab(_tabID: string, suggestion: SkillSuggestion) {
4584 return this.AcceptSkillSuggestion(suggestion);
4585 },
4586 async MemoryForTab(_tabID: string) {
4587 return this.Memory();
4588 },
4589 async MemoryRevisions(_ref: string) {
4590 return [];
4591 },
4592 async MemoryRevisionsForTab(_tabID: string, ref: string) {
4593 return this.MemoryRevisions(ref);
4594 },
4595 async RestoreMemoryRevision(ref: string, revision: number) {
4596 emit({ kind: "notice", level: "info", text: `restored revision → ${ref}@${revision}` });
4597 return {
4598 id: ref,
4599 revision: revision + 1,
4600 name: ref,
4601 description: "Restored memory revision",
4602 type: "project",
4603 scope: "project",
4604 body: "Restored guidance.",
4605 freshness: "fresh",
4606 };
4607 },
4608 async RestoreMemoryRevisionForTab(_tabID: string, ref: string, revision: number) {
4609 return this.RestoreMemoryRevision(ref, revision);
4610 },
4611 async Remember(_scope: string, _note: string) {
4612 emit({ kind: "notice", level: "info", text: `remembered → ${_scope}` });
4613 return `${_scope} REASONIX.md (mock): ${_note}`;
4614 },
4615 async RememberForTab(_tabID: string, scope: string, note: string) {
4616 return this.Remember(scope, note);
4617 },
4618 async Forget(_name: string) {
4619 emit({ kind: "notice", level: "info", text: `forgot → ${_name}` });
4620 },
4621 async ForgetForTab(_tabID: string, name: string) {
4622 return this.Forget(name);
4623 },
4624 async RestoreArchivedMemory(archivePath: string) {
4625 emit({ kind: "notice", level: "info", text: `restored → ${archivePath}` });
4626 return {
4627 id: "mock-restored-memory",
4628 revision: 2,
4629 name: "restored-memory",
4630 description: "Recovered archived memory",
4631 type: "project",
4632 scope: "project",
4633 body: "Recovered guidance.",
4634 freshness: "fresh",
4635 };
4636 },
4637 async RestoreArchivedMemoryForTab(_tabID: string, archivePath: string) {
4638 return this.RestoreArchivedMemory(archivePath);
4639 },
4640 async SaveDoc(_path: string, _body: string) {
4641 emit({ kind: "notice", level: "info", text: `saved → ${_path}` });
4642 return _path;
4643 },
4644 async SaveDocForTab(_tabID: string, path: string, body: string) {
4645 return this.SaveDoc(path, body);
4646 },
4647 async DesktopStartupSettings() {
4648 const { bot, desktopLanguage, desktopTheme, desktopThemeStyle, desktopTerminalTheme, displayMode, sessionExperience, reasoningDisplayMode, reasoningDisplayModeExplicit, statusBarStyle, statusBarItems, checkUpdates, updaterEnabled, conversationWidth } = settings;
4649 return JSON.parse(JSON.stringify({
4650 bot,
4651 desktopLanguage,
4652 desktopTheme,
4653 desktopThemeStyle,
4654 desktopTerminalTheme,
4655 displayMode, sessionExperience, reasoningDisplayMode, reasoningDisplayModeExplicit,
4656 statusBarStyle,
4657 statusBarItems,
4658 checkUpdates,
4659 updaterEnabled,
4660 conversationWidth,
4661 })) as DesktopStartupSettingsView;
4662 },
4663 ...makeMockModelSettingsBindings(settings, loadMockProviderCatalog, mockProviderPresetViews),
4664 async StorageSettings() { return { defaultWorkspace: cwd, statePath: `${cwd}/.reasonix`, cachePath: `${cwd}/.reasonix/cache`, extensionsPath: `${cwd}/.reasonix/plugins` }; },
4665 async HooksSettings(scope: string) {
4666 const key = scope === "project" ? "project" : "global";
4667 return JSON.parse(JSON.stringify(hookSettings[key])) as HooksSettingsView;
4668 },
4669 async SaveHooksSettings(scope: string, hooks: HookConfigView[]) {
4670 const key = scope === "project" ? "project" : "global";
4671 hookSettings[key].hooks = JSON.parse(JSON.stringify(hooks)) as HookConfigView[];
4672 },
4673 async SaveHooksSettingsForRoot(scope: string, _projectRoot: string, hooks: HookConfigView[]) {
4674 const key = scope === "project" ? "project" : "global";
4675 hookSettings[key].hooks = JSON.parse(JSON.stringify(hooks)) as HookConfigView[];
4676 },
4677 async TrustProjectHooks() {
4678 hookSettings.project.trusted = true;
4679 },
4680 async TrustProjectHooksForRoot(_projectRoot: string) {
4681 hookSettings.project.trusted = true;
4682 },
4683 async SetDefaultModel(ref: string) {
4684 settings.defaultModel = ref;
4685 },
4686 async SetPlannerModel(ref: string) {
4687 settings.plannerModel = ref;
4688 },
4689 async SetWebSearchModel(ref: string) {
4690 if (ref && ref !== "auto" && !(settings.webSearchModels ?? []).includes(ref)) throw new Error("Search model unavailable");
4691 settings.webSearchModel = ref || "auto";
4692 settings.effectiveWebSearchModel = settings.webSearchModel;
4693 settings.webSearchModelStatus = "ready";
4694 settings.webSearchModelReason = "";
4695 },
4696 async SetVisionModel(ref: string) {
4697 settings.visionModel = ref;
4698 },
4699 async SetSubagentModel(ref: string) {
4700 settings.subagentModel = ref;
4701 },
4702 async SetSubagentEffort(level: string) {
4703 settings.subagentEffort = level;
4704 },
4705 async SetMaxSubagentDepth(depth: number) {
4706 settings.agent = { ...settings.agent, maxSubagentDepth: depth <= 1 ? 1 : 2 };
4707 },
4708 async SetMaxSubagentConcurrency(n: number) {
4709 const total = Math.max(1, Math.min(32, Math.floor(n) || 6));
4710 const writers = Math.min(total, Math.max(1, settings.agent.maxParallelWriters || 3));
4711 settings.agent = { ...settings.agent, maxSubagentConcurrency: total, maxParallelWriters: writers };
4712 },
4713 async SetMaxParallelWriters(n: number) {
4714 const total = Math.max(1, Math.min(32, settings.agent.maxSubagentConcurrency || 6));
4715 const writers = Math.max(1, Math.min(total, Math.floor(n) || 3));
4716 settings.agent = { ...settings.agent, maxParallelWriters: writers };
4717 },
4718 async SetAutoPlan(mode: string) {
4719 if (mode !== "off") throw new Error("Automatic plan mode has been retired; use Plan Mode explicitly.");
4720 settings.autoPlan = "off";
4721 },
4722 async SetDefaultToolApprovalMode(mode: string) {
4723 settings.defaultToolApprovalMode = normalizeToolApprovalMode(mode);
4724 },
4725 async SetDefaultAutoRecoveryCheckpoint(_enabled: boolean) {
4726 // Legacy no-op; Auto Guard is retired.
4727 },
4728 async SetConnectionKey(name: string, value: string) {
4729 const p = settings.providers.find(p => p.name === name);
4730 if (!p) throw new Error("Connection not found");
4731 p.apiKeyEnv = `REASONIX_CONNECTION_${crypto.randomUUID().replaceAll("-", "")}_KEY`;
4732 p.keySet = Boolean(value.trim());
4733 return "";
4734 },
4735 async AddProviderConnectionWithOptions(_presetID: string, sourceName: string, key: string, baseURL: string, kind: string) {
4736 const source = settings.providers.find(p => p.name === sourceName);
4737 if (!source) throw new Error("Connection template unavailable in preview");
4738 settings.providers.push({...source, kind:kind || source.kind, baseUrl:baseURL || source.baseUrl, requestUrl:"", chatUrl:"", modelsUrl:"", name:`${source.name}-${crypto.randomUUID()}`, builtIn:false, added:true, apiKeyEnv:`REASONIX_CONNECTION_${crypto.randomUUID().replaceAll("-", "")}_KEY`, keySet:Boolean(key.trim())});
4739 return "";
4740 },
4741 async AddProviderConnectionWithURL(_presetID: string, sourceName: string, key: string, baseURL: string) {
4742 const source = settings.providers.find(p => p.name === sourceName);
4743 if (!source) throw new Error("Connection template unavailable in preview");
4744 settings.providers.push({...source, baseUrl:baseURL, requestUrl:"", chatUrl:"", modelsUrl:"", name:`${source.name}-${crypto.randomUUID()}`, builtIn:false, added:true, apiKeyEnv:`REASONIX_CONNECTION_${crypto.randomUUID().replaceAll("-", "")}_KEY`, keySet:Boolean(key.trim())});
4745 return "";
4746 },
4747 async AddProviderConnection(_presetID: string, sourceName: string, key: string) {
4748 const source = settings.providers.find(p => p.name === sourceName);
4749 if (!source) throw new Error("Connection template unavailable in preview");
4750 settings.providers.push({...source, name:`${source.name}-${crypto.randomUUID()}`, builtIn:false, added:true, apiKeyEnv:`REASONIX_CONNECTION_${crypto.randomUUID().replaceAll("-", "")}_KEY`, keySet:Boolean(key.trim())});
4751 return "";
4752 },
4753 async RenameProviderConnections(names: string[], displayName: string) {
4754 for (const name of names) if (!settings.providers.some(p => p.name === name)) throw new Error(`Provider ${name} not found`);
4755 settings.providers = settings.providers.map(p => names.includes(p.name) ? {...p, displayName: displayName.trim()} : p);
4756 },
4757 async SaveProvider(p: ProviderView) {
4758 p.added = true;
4759 const i = settings.providers.findIndex((x) => x.name === p.name);
4760 if (i >= 0) settings.providers[i] = { ...settings.providers[i], ...p };
4761 else settings.providers.push(p);
4762 },
4763 async SetProviderWebSearch(names: string[], enabled: boolean) {
4764 const requested = new Set(names);
4765 settings.providers = settings.providers.map((provider) => (
4766 requested.has(provider.name) ? { ...provider, webSearch: enabled } : provider
4767 ));
4768 },
4769 async SaveProviderModelCatalogs(updates: ProviderModelCatalogUpdate[]) {
4770 const applied: string[] = [];
4771 for (const update of updates) {
4772 const i = settings.providers.findIndex((provider) => provider.name === update.name);
4773 if (i < 0) continue;
4774 const current = settings.providers[i];
4775 if (!update.expectedFingerprint || current.modelCatalogFingerprint !== update.expectedFingerprint) continue;
4776 settings.providers[i] = {
4777 ...current,
4778 models: [...update.models],
4779 default: update.default,
4780 visionModels: [...update.visionModels],
4781 modelCatalogFingerprint: `${update.expectedFingerprint}:updated`,
4782 };
4783 applied.push(update.name);
4784 }
4785 return applied;
4786 },
4787 async SaveProviderWithKey(p: ProviderView, key: string) {
4788 p.added = true;
4789 p.keySet = Boolean(key.trim()) || p.keySet;
4790 const i = settings.providers.findIndex((x) => x.name === p.name);
4791 if (i >= 0) settings.providers[i] = p;
4792 else settings.providers.push(p);
4793 return "";
4794 },
4795 async AddOfficialProviderAccess(kind: string, key: string) {
4796 const templates: Record<string, ProviderView> = {
4797 deepseek: { name: "deepseek", builtIn: true, added: true, kind: "openai", baseUrl: "https://api.deepseek.com", modelsUrl: "", models: ["deepseek-flash", "deepseek-v4-pro"], visionModels: [], visionModelsConfigured: false, default: "deepseek-flash", apiKeyEnv: "DEEPSEEK_API_KEY", keySet: !!key.trim(), balanceUrl: "https://api.deepseek.com/user/balance", contextWindow: 1_000_000, reasoningProtocol: "", thinking: "enabled", webSearch: true, serverWebSearchCapability: true, supportedEfforts: [], defaultEffort: "", modelOverrides: [{ model: "deepseek-flash", reasoningProtocol: "", supportedEfforts: ["disabled", "low", "high", "max"], defaultEffort: "high" }, { model: "deepseek-v4-pro", reasoningProtocol: "", supportedEfforts: ["disabled", "high", "max"], defaultEffort: "high" }] },
4798 };
4799 const next = templates[kind];
4800 if (!next) throw new Error(`unknown official provider template ${kind}`);
4801 const i = settings.providers.findIndex((x) => x.name === next.name);
4802 if (i >= 0) settings.providers[i] = { ...settings.providers[i], ...next, keySet: next.keySet || settings.providers[i].keySet };
4803 else settings.providers.push(next);
4804 return "";
4805 },
4806 async UpgradeDeepSeekProviderAccess(name: string) {
4807 const family = new Set(["deepseek", "deepseek-flash", "deepseek-pro"]);
4808 let changed = false;
4809 settings.providers = settings.providers.map((provider) => {
4810 if ((name === "deepseek" ? family.has(provider.name) : provider.name === name) && provider.recommendedUpgradeAvailable) {
4811 changed = true;
4812 return {
4813 ...provider,
4814 kind: "anthropic",
4815 baseUrl: "https://api.deepseek.com/anthropic",
4816 thinking: provider.thinking || "enabled",
4817 webSearch: provider.webSearch ?? true,
4818 serverWebSearchCapability: true,
4819 recommendedUpgradeAvailable: false,
4820 };
4821 }
4822 return provider;
4823 });
4824 if (!changed) throw new Error(`DeepSeek provider ${name} is not eligible for upgrade`);
4825 return "";
4826 },
4827 async AddProviderPresetAccess(id: string, key: string) {
4828 const preset = settings.providerPresets.find((p) => p.id === id);
4829 if (!preset) throw new Error(`unknown provider preset ${id}`);
4830 const next = cloneMockProviderTemplates(id, key);
4831 if (!next) throw new Error(`unknown provider preset ${id}`);
4832 for (const provider of next) {
4833 const i = settings.providers.findIndex((x) => x.name === provider.name);
4834 if (i >= 0) settings.providers[i] = { ...settings.providers[i], ...provider, keySet: provider.keySet || settings.providers[i].keySet };
4835 else settings.providers.push(provider);
4836 }
4837 preset.added = true;
4838 preset.status = "installed";
4839 preset.statusProviderNames = [...preset.providerNames];
4840 preset.keySet = preset.keySet || !!key.trim();
4841 preset.configured = !preset.requiresKey || preset.keySet;
4842 return "";
4843 },
4844 async ResetProviderPresetAccess(id: string) {
4845 const preset = settings.providerPresets.find((p) => p.id === id);
4846 if (!preset) throw new Error(`unknown provider preset ${id}`);
4847 const next = cloneMockProviderTemplates(id, "");
4848 if (!next) throw new Error(`unknown provider preset ${id}`);
4849 for (const provider of next) {
4850 const i = settings.providers.findIndex((x) => x.name === provider.name);
4851 if (i < 0) throw new Error(`provider preset ${id} cannot be reset because no same-name provider exists`);
4852 const existing = settings.providers[i];
4853 settings.providers[i] = {
4854 ...provider,
4855 added: true,
4856 keySet: existing.apiKeyEnv === provider.apiKeyEnv ? existing.keySet : provider.keySet,
4857 };
4858 }
4859 preset.added = true;
4860 preset.status = "installed";
4861 preset.statusProviderNames = [...preset.providerNames];
4862 preset.keySet = preset.keySet || next.every((provider) => settings.providers.some((item) => item.name === provider.name && item.keySet));
4863 preset.configured = !preset.requiresKey || preset.keySet;
4864 },
4865 async FetchProviderModels(p: ProviderView) {
4866 if (!p.baseUrl.trim()) throw new Error(t("settings.fetchModelsMissingBaseUrl"));
4867 if (providerRequiresKey(p) && !p.apiKeyEnv.trim()) throw new Error(t("settings.fetchModelsMissingKeyEnv"));
4868 await delay(350);
4869 if (p.baseUrl.includes("deepseek")) return ["deepseek-v4-flash", "deepseek-v4-pro"];
4870 if (p.baseUrl.includes("token-plan")) return ["mimo-v2.5", "mimo-v2.5-pro"];
4871 if (p.baseUrl.includes("xiaomimimo")) return ["mimo-v2.5-pro", "mimo-v2.5"];
4872 return ["gpt-5", "gpt-5-mini", "qwen3-coder"];
4873 },
4874 async FetchProviderModelCatalogDraft(p: ProviderView, _key: string) {
4875 return this.FetchProviderModelCatalog(p);
4876 },
4877 async TestProviderModel(_p: ProviderView, _model: string, _key: string) {},
4878 async FetchProviderModelCatalog(p: ProviderView) {
4879 const models = await this.FetchProviderModels(p);
4880 return models.map((model) => ({
4881 model,
4882 inputModalities: p.modelCapabilities?.find((item) => item.model === model)?.inputModalities ?? [],
4883 state: p.modelCapabilities?.find((item) => item.model === model)?.state ?? "unknown",
4884 source: "adapter",
4885 }));
4886 },
4887 async FetchAllProviderModels(providers: ProviderView[]) {
4888 const out: Record<string, string[]> = {};
4889 for (const p of providers) {
4890 try {
4891 out[p.name] = await this.FetchProviderModels(p);
4892 } catch {
4893 out[p.name] = [];
4894 }
4895 }
4896 return out;
4897 },
4898 async FetchAllProviderModelCatalogs(providers: ProviderView[]) {
4899 const out: Record<string, ProviderModelCapabilityView[]> = {};
4900 for (const p of providers) {
4901 try {
4902 out[p.name] = await this.FetchProviderModelCatalog(p);
4903 } catch {
4904 out[p.name] = [];
4905 }
4906 }
4907 return out;
4908 },
4909 async DeleteProvider(name: string) {
4910 settings.providers = settings.providers.filter((p) => p.name !== name);
4911 },
4912 async RemoveProviderAccess(name: string) { settings.providers = removeProviderAccessesForMock(settings.providers, [name]); },
4913 async RemoveProviderAccesses(names: string[]) { settings.providers = removeProviderAccessesForMock(settings.providers, names); },
4914 async SaveProviderKey(apiKeyEnv: string, _value: string) {
4915 settings.providers.forEach((p) => {
4916 if (p.apiKeyEnv === apiKeyEnv) p.keySet = true;
4917 });
4918 return "";
4919 },
4920 async SetProviderKey(apiKeyEnv: string, _value: string) {
4921 settings.providers.forEach((p) => {
4922 if (p.apiKeyEnv === apiKeyEnv) p.keySet = true;
4923 });
4924 return "";
4925 },
4926 async ClearProviderKey(apiKeyEnv: string) {
4927 settings.providers.forEach((p) => {
4928 if (p.apiKeyEnv === apiKeyEnv) p.keySet = false;
4929 });
4930 },
4931 async SetPermissionMode(mode: string) {
4932 settings.permissions.mode = mode;
4933 },
4934 async AddPermissionRule(list: string, rule: string) {
4935 const k = list as "allow" | "ask" | "deny";
4936 if (settings.permissions[k] && !settings.permissions[k].includes(rule)) settings.permissions[k].push(rule);
4937 },
4938 async RemovePermissionRule(list: string, rule: string) {
4939 const k = list as "allow" | "ask" | "deny";
4940 settings.permissions[k] = settings.permissions[k].filter((r) => r !== rule);
4941 },
4942 async ReloadSettings() { reloadBrowserPreviewShell(settings.sandbox); },
4943 async SetShellPreference(prefer: string) {
4944 const sb = settings.sandbox;
4945 if (!sb) return;
4946 sb.shell = prefer;
4947 sb.resolvedShell = browserPreviewEffectiveShell(prefer);
4948 reloadBrowserPreviewShell(sb);
4949 },
4950 async InstallShellSupport(id: string): Promise<ShellInstallResult> {
4951 if (id !== "git-for-windows") throw new Error(`unknown shell support action ${id}`);
4952 if (browserPlatformOverride() !== "windows") return { status: "unsupported_platform", reason: "shell helper install is only available on Windows" };
4953 return {
4954 status: "manual_required",
4955 reason: "automatic installation is disabled because Git for Windows cannot reliably honor user scope",
4956 manualUrl: "https://git-scm.com/download/win",
4957 };
4958 },
4959 async CancelShellInstall() {},
4960 async SetSandbox(bash: string, network: boolean, workspaceRoot: string, allowWrite: string[], shell: string) {
4961 const effectiveWorkspaceRoot = workspaceRoot.trim() || cwd;
4962 const prev = settings.sandbox;
4963 const effectiveShell = browserPreviewEffectiveShell(shell);
4964 const shellSupport = browserPreviewShellSupport(browserPlatformOverride());
4965 settings.sandbox = { bash, network, workspaceRoot, allowWrite, effectiveWorkspaceRoot, effectiveWriteRoots: [effectiveWorkspaceRoot, ...allowWrite], shell, effectiveShell,
4966 resolvedShell: effectiveShell, shellReloadRequired: false,
4967 shellCapabilities: prev?.shellCapabilities ?? shellSupport.shellCapabilities, shellInstallAction: prev?.shellInstallAction ?? shellSupport.shellInstallAction,
4968 shellRepairGuidance: prev?.shellRepairGuidance ?? shellSupport.shellRepairGuidance,
4969 gitCapability: prev?.gitCapability ?? shellSupport.gitCapability, gitRepairGuidance: prev?.gitRepairGuidance ?? shellSupport.gitRepairGuidance };
4970 },
4971 async SetNetwork(n: NetworkView) {
4972 settings.network = n;
4973 },
4974 async SetBotSettings(b: BotSettingsView) {
4975 settings.bot = JSON.parse(JSON.stringify(b)) as BotSettingsView;
4976 },
4977 async SetBotConnectionToolApprovalMode(connID, mode) {
4978 const conn = settings.bot.connections.find((c) => c.id === connID);
4979 if (conn) conn.toolApprovalMode = mode as any;
4980 },
4981 async SetBotDingtalkToolApprovalMode(mode) {
4982 settings.bot.dingtalk.toolApprovalMode = mode as any;
4983 },
4984 async SetBotSecret(envName: string, _value: string) {
4985 const name = envName.trim();
4986 if (settings.bot.qq.appSecretEnv === name) settings.bot.qq.secretSet = true;
4987 if (settings.bot.feishu.appSecretEnv === name) settings.bot.feishu.secretSet = true;
4988 if (settings.bot.weixin.tokenEnv === name) settings.bot.weixin.tokenSet = true;
4989 settings.bot.connections = settings.bot.connections.map((connection) => ({
4990 ...connection,
4991 credential: connection.credential.appSecretEnv === name || connection.credential.tokenEnv === name
4992 ? { ...connection.credential, secretSet: true }
4993 : connection.credential,
4994 }));
4995 },
4996 async ClearBotSecret(envName: string) {
4997 const name = envName.trim();
4998 if (settings.bot.qq.appSecretEnv === name) settings.bot.qq.secretSet = false;
4999 if (settings.bot.feishu.appSecretEnv === name) settings.bot.feishu.secretSet = false;
5000 if (settings.bot.weixin.tokenEnv === name) settings.bot.weixin.tokenSet = false;
5001 settings.bot.connections = settings.bot.connections.map((connection) => ({
5002 ...connection,
5003 credential: connection.credential.appSecretEnv === name || connection.credential.tokenEnv === name
5004 ? { ...connection.credential, secretSet: false }
5005 : connection.credential,
5006 }));
5007 },
5008 async BotRuntimeStatus() {
5009 const qqRunning = settings.bot.qq.enabled && settings.bot.qq.appId.trim() && settings.bot.qq.secretSet;
5010 const runningConnections = (qqRunning ? 1 : 0) + settings.bot.connections.filter((connection) => connection.enabled && connection.status === "connected").length;
5011 const dingtalkRunning = Boolean(settings.bot.dingtalk.enabled && settings.bot.dingtalk.clientId.trim() && settings.bot.dingtalk.secretSet);
5012 const running = settings.bot.enabled && runningConnections > 0;
5013 return {
5014 running,
5015 status: running ? "running" : "stopped",
5016 message: running ? `${runningConnections} bot connection(s) running` : "bot runtime is not started",
5017 connections: runningConnections,
5018 startedAt: running ? new Date(t0).toISOString() : "",
5019 platforms: {
5020 dingtalk: dingtalkRunning ? "running" : settings.bot.dingtalk.clientId.trim() ? "configured" : "",
5021 qq: qqRunning ? "running" : settings.bot.qq.appId.trim() ? "configured" : "",
5022 ...Object.fromEntries(settings.bot.connections
5023 .filter((connection) => connection.provider !== "qq")
5024 .map((connection) => [connection.provider, connection.enabled && connection.status === "connected" ? "running" : connection.credential.secretSet ? "configured" : ""])),
5025 },
5026 };
5027 },
5028 async StartBotConnectionInstall(provider: string, domain: string) {
5029 const normalizedProvider = provider === "weixin" ? "weixin" : "feishu";
5030 const normalizedDomain = normalizedProvider === "weixin" ? "weixin" : domain === "lark" ? "lark" : "feishu";
5031 return {
5032 ok: true,
5033 provider: normalizedProvider,
5034 domain: normalizedDomain,
5035 installId: `mock-${normalizedProvider}-${normalizedDomain}`,
5036 url: "https://example.com/reasonix-bot-qr",
5037 deviceCode: "MOCKDEVICE",
5038 userCode: normalizedProvider === "weixin" ? "" : "MOCK-CODE",
5039 interval: 3,
5040 expireIn: 300,
5041 message: "",
5042 };
5043 },
5044 async PollBotConnectionInstall(installID: string) {
5045 const isWeixin = installID.includes("weixin");
5046 const domain = installID.includes("lark") ? "lark" : isWeixin ? "weixin" : "feishu";
5047 const provider = isWeixin ? "weixin" : "feishu";
5048 const connection = {
5049 id: `${provider}-${domain}`,
5050 provider,
5051 domain,
5052 label: domain === "lark" ? "Lark" : domain === "weixin" ? "微信" : "飞书",
5053 enabled: true,
5054 status: "connected",
5055 model: "",
5056 toolApprovalMode: "",
5057 workspaceRoot: "",
5058 access: { enabled: true, allowAll: false, pairingEnabled: true, users: [provider === "weixin" ? "wxid_mock_user_001" : "ou_mock_user_001"], groups: [], approvers: [], admins: [] },
5059 credential: {
5060 appId: provider === "feishu" ? "cli_mock" : "",
5061 appSecretEnv: provider === "feishu" ? (domain === "lark" ? "LARK_BOT_APP_SECRET" : "FEISHU_BOT_APP_SECRET") : "",
5062 accountId: provider === "weixin" ? "mock-account" : "",
5063 tokenEnv: provider === "weixin" ? "WEIXIN_BOT_TOKEN" : "",
5064 secretSet: true,
5065 },
5066 sessionMappings: [],
5067 lastError: "",
5068 createdAt: new Date().toISOString(),
5069 updatedAt: new Date().toISOString(),
5070 };
5071 settings.bot.connections = [...settings.bot.connections.filter((c) => c.id !== connection.id), connection];
5072 return { done: true, connection, status: "connected", message: "connected", error: "" };
5073 },
5074 async DiagnoseBotConnection(id: string) {
5075 const connection = settings.bot.connections.find((c) => c.id === id);
5076 const occurredAt = new Date().toISOString();
5077 return connection
5078 ? { id, label: connection.label, status: connection.enabled ? "ok" : "disabled", message: connection.enabled ? "连接配置已保存。" : "连接已保存但未启用。", messageId: "", phase: "config", code: connection.enabled ? "config_ok" : "connection_disabled", reportKind: "", reportDetail: "", occurredAt }
5079 : { id, label: "", status: "missing", message: "未找到连接。", messageId: "", phase: "config", code: "connection_missing", reportKind: "bot", reportDetail: JSON.stringify({ schemaVersion: 2, kind: "bot", source: "bot.runtime", label: "bot.mock.config", message: "mock missing bot connection", errorType: "BotConnectionDiagnostic", errorMessage: "bot connection record was not found", topFrame: "bot.config", occurredAt }), occurredAt };
5080 },
5081 async TestBotConnection(id: string, target?: string) {
5082 const diag = await this.DiagnoseBotConnection(id);
5083 if (target?.trim()) return { ...diag, message: `Mock test sent to ${target.trim()}`, messageId: "mock-message-id" };
5084 return diag;
5085 },
5086 async TestDingtalkBot() {
5087 const occurredAt = new Date().toISOString();
5088 return { id: "dingtalk", label: "DingTalk", status: "ok", message: "Mock dingtalk test sent", messageId: "mock-dingtalk-id", phase: "send", code: "dingtalk_test_send_ok", reportKind: "", reportDetail: "", occurredAt };
5089 },
5090 ...createDesktopPreferencesMock(settings),
5091 async SetDesktopAppearance(theme: string, style: string) {
5092 settings.desktopTheme = theme === "auto" || theme === "light" ? theme : "dark";
5093 settings.desktopThemeStyle = style;
5094 mockThemeMode = settings.desktopTheme as "auto" | "light" | "dark";
5095 if (["graphite","aurora","slate","carbon","nocturne","amber"].includes(style)) {
5096 mockBaseStyle = style;
5097 }
5098 },
5099 async SetDesktopTerminalTheme(theme: string) {
5100 settings.desktopTerminalTheme = theme === "dark" || theme === "light" ? theme : "auto";
5101 },
5102 async ListThemePacks() {
5103 const baseActive = !mockActiveThemeId;
5104 return mockThemePacks.map((p) => {
5105 const kind = p.kind || (p.builtin ? "base" : "user");
5106 let active = false;
5107 if (kind === "base") active = baseActive && p.id === mockBaseStyle;
5108 else active = p.id === mockActiveThemeId;
5109 return { ...p, active, tokens: { light: { ...(p.tokens.light || {}) }, dark: { ...(p.tokens.dark || {}) } }, recipes: { ...p.recipes } };
5110 });
5111 },
5112 async GetActiveThemePack() {
5113 // Base style ids are never active packs in the redesigned model.
5114 const pack = mockActiveThemeId && !["graphite","aurora","slate","carbon","nocturne","amber"].includes(mockActiveThemeId)
5115 ? mockThemePacks.find((p) => p.id === mockActiveThemeId)
5116 : null;
5117 return { activeThemeId: pack ? mockActiveThemeId : "", pack: pack ? { ...pack, active: true } : null };
5118 },
5119 async GetThemeExperience() {
5120 const pack = mockActiveThemeId && !["graphite","aurora","slate","carbon","nocturne","amber"].includes(mockActiveThemeId)
5121 ? mockThemePacks.find((p) => p.id === mockActiveThemeId)
5122 : null;
5123 return {
5124 themeMode: mockThemeMode,
5125 baseStyle: mockBaseStyle,
5126 effectiveStyle: pack?.baseStyle || mockBaseStyle,
5127 activeThemeId: pack ? mockActiveThemeId : "",
5128 activePack: pack ? { ...pack, active: true } : null,
5129 };
5130 },
5131 async ActivateThemePack(id: string) {
5132 const next = String(id || "").trim();
5133 if (["graphite","aurora","slate","carbon","nocturne","amber"].includes(next)) {
5134 throw new Error(`base style ${next} is not a theme pack; use ActivateBaseStyle`);
5135 }
5136 mockActiveThemeId = next;
5137 },
5138 async ActivateBaseStyle(style: string) {
5139 const s = String(style || "").trim().toLowerCase();
5140 if (!["graphite","aurora","slate","carbon","nocturne","amber"].includes(s)) {
5141 throw new Error(`unknown base style ${s}`);
5142 }
5143 mockBaseStyle = s;
5144 mockActiveThemeId = "";
5145 },
5146 async DisableThemePack() {
5147 mockActiveThemeId = "";
5148 },
5149 async RestoreGraphiteAppearance() {
5150 mockBaseStyle = "graphite";
5151 mockActiveThemeId = "";
5152 },
5153 async ResetThemePack() {
5154 mockActiveThemeId = "";
5155 },
5156 async SaveThemePack(input: import("./themePack").ThemeSaveInput) {
5157 const pack: import("./themePack").ThemePackView = {
5158 id: input.id,
5159 name: input.name,
5160 author: input.author,
5161 description: input.description,
5162 license: input.license,
5163 baseStyle: input.baseStyle,
5164 builtin: false,
5165 kind: "user",
5166 active: Boolean(input.activate),
5167 hasBackground: Boolean(
5168 (input.background && (input.backgroundDataUrl || input.background.image)) ||
5169 (input.taskBackground && (input.taskBackgroundDataUrl || input.taskBackground.image)),
5170 ),
5171 backgroundUrl: input.backgroundDataUrl || "",
5172 taskBackgroundUrl: input.taskBackgroundDataUrl || "",
5173 tokens: input.tokens || {},
5174 recipes: input.recipes || { density: "comfortable", corners: "soft" },
5175 background: input.background ?? undefined,
5176 taskBackground: input.taskBackground ?? undefined,
5177 };
5178 const idx = mockThemePacks.findIndex((p) => p.id === pack.id);
5179 if (idx >= 0) mockThemePacks[idx] = pack;
5180 else mockThemePacks.push(pack);
5181 if (input.activate) mockActiveThemeId = pack.id;
5182 return pack;
5183 },
5184 async DeleteThemePack(id: string) {
5185 mockThemePacks = mockThemePacks.filter((p) => p.id !== id || p.builtin);
5186 if (mockActiveThemeId === id) mockActiveThemeId = "";
5187 },
5188 async CopyThemePack(sourceID: string, newID: string, newName: string) {
5189 const src = mockThemePacks.find((p) => p.id === sourceID);
5190 if (!src) throw new Error("source theme not found");
5191 const pack: import("./themePack").ThemePackView = {
5192 ...src,
5193 id: newID,
5194 name: newName || `${src.name} Copy`,
5195 builtin: false,
5196 kind: "user",
5197 nameKey: undefined,
5198 descriptionKey: undefined,
5199 active: false,
5200 };
5201 mockThemePacks.push(pack);
5202 return pack;
5203 },
5204 async ImportThemePack(_sourcePath: string, replace: boolean) {
5205 if (replace) {
5206 return { pack: mockThemePacks[0], replaced: true };
5207 }
5208 // Simulate conflict path without re-prompting for a file on confirm.
5209 return { pack: mockThemePacks[0], replaced: false, needsReplace: true, pendingId: "pending-mock" };
5210 },
5211 async ExportThemePack(_id: string, _destPath: string) {
5212 return "";
5213 },
5214 async PickThemeBackground() {
5215 return "";
5216 },
5217 // The layout-style preference was removed from the UI; the binding
5218 // stays because the generated host contract still declares it.
5219 async SetDesktopLayoutStyle(_style: string) {},
5220 async SetDesktopZoomFactor(factor: number) {
5221 mockDesktopZoomFactor = Math.min(2.0, Math.max(0.5, Number.isFinite(factor) ? factor : 1.0));
5222 },
5223 async GetDesktopZoomFactor() {
5224 return mockDesktopZoomFactor;
5225 },
5226 async RestartApplication() {
5227 // no-op in mock
5228 },
5229 async ReportDesktopWebViewReady() {
5230 // no-op in mock
5231 },
5232 async GetDesktopShellStatus() {
5233 return { trayState: "ready", backgroundCloseAvailable: true } as DesktopShellStatusView;
5234 },
5235 async SetAgentParams(temperature: number, maxSteps: number, plannerMaxSteps: number, systemPrompt: string) {
5236 settings.agent = { ...settings.agent, temperature, maxSteps, plannerMaxSteps, systemPrompt };
5237 },
5238 async SetCompactRatio(ratio: number) {
5239 if (!Number.isFinite(ratio)
5240 || ratio < COMPACT_RATIO_MIN_PERCENT / 100
5241 || ratio > COMPACT_RATIO_MAX_PERCENT / 100) {
5242 throw new Error(`compact ratio must be between ${COMPACT_RATIO_MIN_PERCENT / 100} and ${COMPACT_RATIO_MAX_PERCENT / 100}`);
5243 }
5244 settings.agent = { ...settings.agent, compactRatio: ratio };
5245 },
5246 async SetReasoningLanguage(lang: string) {
5247 const normalized = lang === "zh" || lang === "en" ? lang : "auto";
5248 settings.agent = { ...settings.agent, reasoningLanguage: normalized };
5249 },
5250 // ── Heartbeat mock ──
5251 async HeartbeatListTasks() { return mockHeartbeatTasks; },
5252 async HeartbeatReloadTasks() { return mockHeartbeatTasks; },
5253 async HeartbeatSaveTasks(tasks: unknown) { mockHeartbeatTasks = Array.isArray(tasks) ? tasks : []; },
5254 async HeartbeatReloadConfig() { return { revision: mockHeartbeatRevision, etag: `mock-${mockHeartbeatRevision}`, tasks: mockHeartbeatTasks }; },
5255 async HeartbeatSaveConfig(update: unknown) {
5256 const tasks = (update as { tasks?: unknown[] } | null)?.tasks;
5257 mockHeartbeatTasks = Array.isArray(tasks) ? tasks : [];
5258 mockHeartbeatRevision += 1;
5259 return { revision: mockHeartbeatRevision, etag: `mock-${mockHeartbeatRevision}`, tasks: mockHeartbeatTasks };
5260 },
5261 async HeartbeatTriggerNow(_id: string) {},
5262 async HeartbeatGenerateID() { return "mock-" + Date.now().toString(36); },
5263 async ListTasks() { return []; },
5264 async CurrentTaskSessionID() { return ""; },
5265 async ListTasksForSession() { return []; },
5266 async GetTask() { return null; },
5267 async StopTask() { return { schema_version: 1, command: "stop", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5268 async CancelTask() { return { schema_version: 1, command: "cancel", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5269 async ListTasksForTab() { return []; },
5270 ...makeMockTaskCatalogBindings(),
5271 async ListTaskEventsForTab() { return []; },
5272 async StopTaskForTab() { return { schema_version: 1, command: "stop", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5273 async CancelTaskForTab() { return { schema_version: 1, command: "cancel", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5274 async RequeueTaskForTab() { return { schema_version: 1, command: "requeue", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5275 async OpenTaskSessionForTab() { return { schema_version: 1, command: "open_session", task_id: "", accepted: false, idempotent: false, error: { code: "mock", message: "not available in browser mock" } }; },
5276 async SetTrayLocale(_locale: "en" | "zh" | "zh-TW") {},
5277 async SetAutoApproveTools(_on: boolean) {
5278 await this.SetToolApprovalMode("workspace-write");
5279 },
5280 async SetBypass(on: boolean) {
5281 await this.SetAutoApproveTools(on);
5282 },
5283 async Version() {
5284 return "v1.0.0 (browser dev)";
5285 },
5286 async CheckUpdate(channel: string) {
5287 void channel;
5288 // Keep the default browser preview focused on the primary product surface.
5289 // Updater methods remain mocked for explicit updater-flow tests.
5290 return {
5291 available: false,
5292 current: "v1.0.0",
5293 latest: "v1.0.0",
5294 notes: "",
5295 channel: "stable",
5296 canSelfUpdate: false,
5297 manualOnly: true,
5298 installMode: "manual",
5299 manualReason: "browser preview",
5300 downloaded: false,
5301 downloadUrl: "",
5302 assetSize: 0,
5303 };
5304 },
5305 async ApplyUpdateRequest(channel: string, expectedVersion: string, requestId: string) {
5306 void channel;
5307 const selectedChannel = "stable";
5308 const total = 12_345_678;
5309 for (let r = 0; r <= total; r += 1_800_000) {
5310 emitUpdater({ requestId, version: expectedVersion, channel: selectedChannel, phase: "downloading", received: Math.min(r, total), total });
5311 await delay(120);
5312 }
5313 emitUpdater({ requestId, version: expectedVersion, channel: selectedChannel, phase: "verifying", received: total, total });
5314 await delay(300);
5315 emitUpdater({ requestId, version: expectedVersion, channel: selectedChannel, phase: "installing", received: total, total });
5316 await delay(300);
5317 emitUpdater({ requestId, version: expectedVersion, channel: selectedChannel, phase: "relaunching", received: 0, total: 0 });
5318 },
5319 async AbandonPendingUpdate() {},
5320 async OpenDownloadPage() {
5321 if (typeof window !== "undefined") {
5322 window.open("https://reasonix.io/?download=desktop#start", "_blank", "noopener");
5323 }
5324 },
5325 async OpenUserConfigPath() {},
5326 async ReloadUserConfig() {
5327 return { configWarnings: [], configWarningsRevision: 0, configPath: "" };
5328 },
5329 // Dev seam: match the backend's provider-agnostic onboarding predicate.
5330 async NeedsOnboarding() {
5331 return !settings.providers.some((p) => p.models.length > 0 && providerIsConfigured(p));
5332 },
5333 async ConnectKey(apiKey: string) {
5334 if (!apiKey.trim()) throw new Error("key is required");
5335 // Match the production onboarding path: saving a DeepSeek key also
5336 // restores the current official provider template instead of merely
5337 // marking a possibly stale legacy entry as configured.
5338 await this.AddOfficialProviderAccess("deepseek", apiKey);
5339 await delay(300);
5340 return "";
5341 },
5342 async ReportCrash() { await delay(300); },
5343 async RecordUIPerf() {},
5344 // Tab management mocks.
5345 async ListTabs() {
5346 return mockTabs.map((tab) => ({ ...tab }));
5347 },
5348 async OpenProjectTab(workspaceRoot: string, _topicID: string) {
5349 const existing = mockTabs.find((tab) => tab.scope === "project" && tab.workspaceRoot === workspaceRoot && tab.topicId === _topicID);
5350 if (existing) {
5351 const active = { ...existing, active: true, running: mockTopicRunsInScenario(_topicID) };
5352 mockTabs = mockTabs.map((tab) => (tab.id === existing.id ? active : { ...tab, active: false }));
5353 return { ...active };
5354 }
5355 const pruned = restoreMockPrunedTab("project", workspaceRoot, _topicID);
5356 if (pruned) {
5357 const restored = { ...pruned, active: true, running: mockTopicRunsInScenario(_topicID) };
5358 mockTabs = [...mockTabs.map((item) => ({ ...item, active: false })), restored];
5359 return { ...restored };
5360 }
5361 const defaultToolApprovalMode = normalizeToolApprovalMode(settings.defaultToolApprovalMode);
5362 const tab: TabMeta = {
5363 id: "tab_" + Date.now(),
5364 scope: "project",
5365 workspaceRoot,
5366 workspaceName: workspaceRoot.split("/").filter(Boolean).pop() ?? workspaceRoot,
5367 workspacePath: workspaceRoot,
5368 gitBranch: "main",
5369 topicId: _topicID,
5370 topicTitle: topicLabel(_topicID, t("mock.newSession")),
5371 sessionPath: `/mock/sessions/${_topicID}.jsonl`,
5372 sessionGeneration: 1,
5373 projectColor: mockProjectTree.find((node) => node.root === workspaceRoot)?.projectColor,
5374 label: mockModelLabel(settings.defaultModel),
5375 ready: true,
5376 running: mockTopicRunsInScenario(_topicID),
5377 mode: modeWithAutoApproveTools("normal", defaultToolApprovalMode === "danger-full-access"),
5378 collaborationMode: "normal",
5379 toolApprovalMode: defaultToolApprovalMode,
5380 tokenMode: "full",
5381 active: true,
5382 cwd: workspaceRoot,
5383 };
5384 mockTabs = [...mockTabs.map((item) => ({ ...item, active: false })), tab];
5385 return { ...tab };
5386 },
5387 async IsolatedWorktreeAvailability(workspaceRoot: string) {
5388 return workspaceRoot
5389 ? { available: true, repoRoot: workspaceRoot, branch: "main", sourceDirty: false }
5390 : { available: false, reason: "project folder is required" };
5391 },
5392 async DeliveryWorktreeAvailability(workspaceRoot: string) {
5393 return this.IsolatedWorktreeAvailability(workspaceRoot);
5394 },
5395 ...makeMockQualityFloorBindings(() => mockTabs, (next) => { mockTabs = next; }),
5396 async SetAgentPreset(_preset: string) {},
5397 async SetAgentPresetForTab(_tabID: string, _preset: string) {},
5398 async SetTokenMode(_mode: string) {},
5399 async SetTokenModeForTab(_tabID: string, _mode: string) {},
5400 async CreateIsolatedWorktree(workspaceRoot: string) {
5401 if (!workspaceRoot) throw new Error("project folder is required");
5402 const suffix = Date.now().toString(36);
5403 const isolatedRoot = `/mock/reasonix-worktrees/${suffix}/${workspaceRoot.split("/").filter(Boolean).pop() ?? "project"}`;
5404 const topicID = `topic_worktree_${suffix}`;
5405 const tab = await this.OpenProjectTab(isolatedRoot, topicID);
5406 tab.isolatedWorktree = true;
5407 tab.gitBranch = `reasonix/isolated-${suffix}`;
5408 mockTabs = mockTabs.map((candidate) => candidate.id === tab.id ? { ...tab } : candidate);
5409 return {
5410 workspaceRoot: isolatedRoot,
5411 worktreeRoot: isolatedRoot,
5412 sourceRoot: workspaceRoot,
5413 branch: tab.gitBranch,
5414 sourceDirty: false,
5415 tab,
5416 };
5417 },
5418 async CreateDeliveryWorktree(workspaceRoot: string) {
5419 return this.CreateIsolatedWorktree(workspaceRoot);
5420 },
5421 ...makeMockWorktreeMergeBindings(() => mockTabs, (next) => { mockTabs = next; }),
5422 async OpenGlobalTab(_topicID: string) {
5423 const existing = mockTabs.find((tab) => tab.scope === "global" && tab.topicId === _topicID);
5424 if (existing) {
5425 setMockActiveTab(existing.id);
5426 return { ...existing, active: true };
5427 }
5428 const defaultToolApprovalMode = normalizeToolApprovalMode(settings.defaultToolApprovalMode);
5429 const tab: TabMeta = {
5430 id: "tab_" + Date.now(),
5431 scope: "global",
5432 workspaceRoot: globalWorkspaceRoot,
5433 workspaceName: "Global",
5434 workspacePath: globalWorkspaceRoot,
5435 topicId: _topicID,
5436 topicTitle: topicLabel(_topicID, "Global"),
5437 sessionPath: `/mock/sessions/${_topicID}.jsonl`,
5438 label: mockModelLabel(settings.defaultModel),
5439 ready: true,
5440 running: false,
5441 mode: modeWithAutoApproveTools("normal", defaultToolApprovalMode === "danger-full-access"),
5442 collaborationMode: "normal",
5443 toolApprovalMode: defaultToolApprovalMode,
5444 tokenMode: "full",
5445 active: true,
5446 cwd: globalWorkspaceRoot,
5447 };
5448 mockTabs = [...mockTabs.map((item) => ({ ...item, active: false })), tab];
5449 return { ...tab };
5450 },
5451 async OpenTopicSession(scope: string, workspaceRoot: string, topicID: string, sessionPath: string) {
5452 const tab = scope === "project"
5453 ? await this.OpenProjectTab(workspaceRoot, topicID)
5454 : await this.OpenGlobalTab(topicID);
5455 const active = { ...tab, sessionPath };
5456 mockTabs = mockTabs.map((item) => (item.id === tab.id ? active : item));
5457 return { ...active };
5458 },
5459 async EnsureBlankTab(scope: string, workspaceRoot: string) {
5460 const targetScope = scope === "project" && workspaceRoot ? "project" : "global";
5461 const targetRoot = targetScope === "project" ? workspaceRoot : "";
5462 const existing = mockTabs.find((tab) =>
5463 tab.scope === targetScope &&
5464 (targetScope === "global" || tab.workspaceRoot === targetRoot) &&
5465 !tab.running &&
5466 mockTopicIsBlank(tab.topicId)
5467 );
5468 if (existing) {
5469 setMockActiveTab(existing.id);
5470 return { ...existing, active: true };
5471 }
5472 const topic = await this.CreateTopic(targetScope, targetRoot, "");
5473 return targetScope === "global" ? this.OpenGlobalTab(topic.id) : this.OpenProjectTab(targetRoot, topic.id);
5474 },
5475 async ActivateTopic(scope: string, workspaceRoot: string, topicID: string, sessionPath: string) {
5476 const tab = sessionPath
5477 ? await this.OpenTopicSession(scope, workspaceRoot, topicID, sessionPath)
5478 : scope === "project"
5479 ? await this.OpenProjectTab(workspaceRoot, topicID)
5480 : await this.OpenGlobalTab(topicID);
5481 pruneMockTabsTo(tab.id);
5482 return { ...mockTabs[0] };
5483 },
5484 async StartTopicActivation(req: TopicActivationRequest): Promise<TopicActivationTicket> {
5485 // Publish identity first; terminal runtime events arrive asynchronously.
5486 const tab = req.sessionPath
5487 ? await this.OpenTopicSession(req.scope, req.workspaceRoot, req.topicId, req.sessionPath)
5488 : req.scope === "project"
5489 ? await this.OpenProjectTab(req.workspaceRoot, req.topicId)
5490 : await this.OpenGlobalTab(req.topicId);
5491 pruneMockTabsTo(tab.id);
5492 const requestId = req.requestId?.trim() || `mock-act-${++mockTopicActivationCounter}`;
5493 const previous = mockPendingTopicActivation;
5494 mockPendingTopicActivation = { requestId, tabId: tab.id };
5495 if (previous && previous.requestId !== requestId) {
5496 __emitMockTopicActivation({ requestId: previous.requestId, tabId: previous.tabId, phase: "cancelled" });
5497 }
5498 __emitMockTopicActivation({ requestId, tabId: tab.id, phase: "starting" });
5499 const meta = { ...mockTabs[0] };
5500 window.setTimeout(() => {
5501 if (mockPendingTopicActivation?.requestId !== requestId) return;
5502 mockPendingTopicActivation = undefined;
5503 __emitMockTopicActivation({ requestId, tabId: tab.id, phase: "ready" });
5504 }, 0);
5505 return { requestId, tabId: tab.id, meta };
5506 },
5507 async EnsureBlankSurface(scope: string, workspaceRoot: string) {
5508 const tab = await this.EnsureBlankTab(scope, workspaceRoot);
5509 pruneMockTabsTo(tab.id);
5510 return { ...mockTabs[0] };
5511 },
5512 async SetActiveTab(_tabID: string) {
5513 const tab = mockTabs.find((item) => item.id === _tabID);
5514 if (!tab) throw new Error(`tab ${_tabID} not found`);
5515 setMockActiveTab(_tabID);
5516 if (!tab.remote) queueMockTopicRuntime(tab);
5517 },
5518 async ReorderTabs(_tabIDs: string[]) {
5519 const byId = new Map(mockTabs.map((tab) => [tab.id, tab]));
5520 const ordered = _tabIDs.map((id) => byId.get(id)).filter((tab): tab is TabMeta => Boolean(tab));
5521 if (ordered.length === mockTabs.length) mockTabs = ordered;
5522 },
5523 async CloseTab(_tabID: string) {
5524 if (mockTabs.length <= 1) return;
5525 const terminalIDs = mockTerminalSessions
5526 .filter((session) => mockTerminalTabIDs.get(session.id) === _tabID)
5527 .map((session) => session.id);
5528 mockTerminalSessions = mockTerminalSessions.filter((session) => !terminalIDs.includes(session.id));
5529 terminalIDs.forEach((id) => {
5530 mockTerminalOutput.delete(id);
5531 mockTerminalTabIDs.delete(id);
5532 __emitMockTerminalExit({ id, exitCode: 0, removed: true });
5533 });
5534 const wasActive = mockTabs.some((tab) => tab.id === _tabID && tab.active);
5535 mockTabs = mockTabs.filter((tab) => tab.id !== _tabID);
5536 if (wasActive && mockTabs.length > 0 && !mockTabs.some((tab) => tab.active)) {
5537 mockTabs[mockTabs.length - 1] = { ...mockTabs[mockTabs.length - 1], active: true };
5538 }
5539 },
5540 async TerminalWorkspaceForTab(tabID: string) {
5541 const tab = mockTabs.find((candidate) => candidate.id === tabID) ?? mockTabs.find((candidate) => candidate.active);
5542 const sessions = tab ? mockTerminalSessions.filter((session) => mockTerminalTabIDs.get(session.id) === tab.id) : [];
5543 return {
5544 available: true,
5545 readOnly: Boolean(tab?.readOnly),
5546 sessions: sessions.map((session) => ({ ...session })),
5547 shells: [
5548 { id: "default", label: "Default shell" },
5549 { id: "bash", label: "bash" },
5550 { id: "zsh", label: "zsh" },
5551 ],
5552 };
5553 },
5554 async TerminalOutputForTab(tabID: string, sessionID: string) {
5555 if (mockTerminalTabIDs.get(sessionID) !== tabID) return "";
5556 return mockTerminalOutput.get(sessionID) ?? "";
5557 },
5558 async CreateTerminalForTab(tabID: string, relativePath: string, shellID: string) {
5559 const tab = mockTabs.find((candidate) => candidate.id === tabID) ?? mockTabs.find((candidate) => candidate.active);
5560 if (tab?.readOnly) throw new Error("channel session is read-only");
5561 const id = `term-mock-${Date.now()}-${Math.random().toString(16).slice(2)}`;
5562 const session: TerminalSessionView = {
5563 id,
5564 title: shellID || "Default shell",
5565 shell: shellID || "default",
5566 cwd: `${tab?.cwd || cwd}/${relativePath || "."}`.replace(/\/\.\/?$/, ""),
5567 createdAt: Date.now(),
5568 running: true,
5569 };
5570 mockTerminalSessions = [...mockTerminalSessions, session];
5571 mockTerminalOutput.set(id, "Reasonix terminal ready\r\n");
5572 mockTerminalTabIDs.set(id, tabID);
5573 window.setTimeout(() => __emitMockTerminalOutput({ id, data: mockTerminalBytes("Reasonix terminal ready\r\n") }), 0);
5574 return { ...session };
5575 },
5576 async WriteTerminalForTab(_tabID: string, sessionID: string, data: string) {
5577 const session = mockTerminalSessions.find((candidate) => candidate.id === sessionID);
5578 if (!session?.running) throw new Error("terminal session has exited");
5579 mockTerminalOutput.set(sessionID, `${mockTerminalOutput.get(sessionID) ?? ""}${data}`);
5580 window.setTimeout(() => __emitMockTerminalOutput({ id: sessionID, data: mockTerminalBytes(data) }), 0);
5581 },
5582 async ResizeTerminalForTab() {},
5583 async CloseTerminalForTab(_tabID: string, sessionID: string) {
5584 mockTerminalSessions = mockTerminalSessions.filter((session) => session.id !== sessionID);
5585 mockTerminalOutput.delete(sessionID);
5586 mockTerminalTabIDs.delete(sessionID);
5587 __emitMockTerminalExit({ id: sessionID, exitCode: 0, removed: true });
5588 },
5589 async RenameTerminalForTab(_tabID: string, sessionID: string, title: string) {
5590 mockTerminalSessions = mockTerminalSessions.map((session) => session.id === sessionID ? { ...session, title } : session);
5591 },
5592 async ListProjectTree() {
5593 return cloneProjectTree();
5594 },
5595 async RenameProject(workspaceRoot: string, title: string) {
5596 const node = workspaceRoot
5597 ? mockProjectTree.find((item) => item.root === workspaceRoot)
5598 : mockProjectTree.find((item) => item.kind === "global_folder");
5599 if (node) node.label = title.trim() || (node.kind === "global_folder" ? "Global" : node.label);
5600 },
5601 async SetProjectColor(workspaceRoot: string, color: string) {
5602 const node = workspaceRoot
5603 ? mockProjectTree.find((item) => item.root === workspaceRoot)
5604 : mockProjectTree.find((item) => item.kind === "global_folder");
5605 if (!node) return;
5606 node.projectColor = color || undefined;
5607 for (const child of projectChildren(node)) child.projectColor = node.projectColor;
5608 mockTabs = mockTabs.map((tab) =>
5609 (workspaceRoot ? tab.workspaceRoot === workspaceRoot : tab.scope === "global")
5610 ? { ...tab, projectColor: node.projectColor }
5611 : tab,
5612 );
5613 },
5614 async SetProjectPinned(workspaceRoot: string, pinned: boolean) {
5615 setMockProjectPinned(workspaceRoot, pinned);
5616 },
5617 async ReorderProjects(workspaceRoots: string[]) {
5618 const projects = mockProjectTree.filter((node) => node.kind === "project");
5619 const globals = mockProjectTree.filter((node) => node.kind === "global_folder");
5620 if (!workspaceRoots.includes(GLOBAL_PROJECT_ORDER_KEY)) {
5621 if (workspaceRoots.length !== projects.length) return;
5622 const byRoot = new Map(projects.map((node) => [node.root, node]));
5623 const ordered = workspaceRoots.map((root) => byRoot.get(root)).filter((node): node is ProjectNode => Boolean(node));
5624 if (ordered.length !== projects.length) return;
5625 mockProjectTree.splice(0, mockProjectTree.length, ...globals, ...ordered);
5626 return;
5627 }
5628 const byKey = new Map<string, ProjectNode>();
5629 for (const node of projects) {
5630 if (node.root) byKey.set(node.root, node);
5631 }
5632 for (const node of globals) byKey.set(GLOBAL_PROJECT_ORDER_KEY, node);
5633 const seen = new Set<string>();
5634 const ordered: ProjectNode[] = [];
5635 for (const key of workspaceRoots) {
5636 if (seen.has(key)) return;
5637 const node = byKey.get(key);
5638 if (!node) return;
5639 seen.add(key);
5640 ordered.push(node);
5641 }
5642 if (ordered.length !== projects.length + globals.length) return;
5643 mockProjectTree.splice(0, mockProjectTree.length, ...ordered);
5644 },
5645 async CreateTopic(_scope: string, _workspaceRoot: string, title: string) {
5646 const now = Date.now();
5647 const id = "topic_" + now;
5648 const topicTitle = title.trim() || t("mock.newSession");
5649 const parent = _scope === "global"
5650 ? ensureMockGlobalFolder()
5651 : mockProjectTree.find((node) => node.root === _workspaceRoot);
5652 if (parent) {
5653 const global = parent.kind === "global_folder";
5654 parent.children = [{
5655 key: parent.kind === "global_folder" ? "global_topic_" + id : "topic_" + id,
5656 kind: global ? "global_topic" : "topic",
5657 label: topicTitle,
5658 root: parent.root,
5659 topicId: id,
5660 projectColor: parent.projectColor,
5661 createdAt: now,
5662 }, ...projectChildren(parent)];
5663 }
5664 (await import("./topicRemovalMock")).markTopic(mockProjectTree, id, !title.trim());
5665 return { id, title: topicTitle, createdAt: now };
5666 },
5667 async RenameTopic(topicID: string, title: string) {
5668 (await import("./topicRemovalMock")).markTopic(mockProjectTree, topicID, false);
5669 const topic = findMockTopic(topicID);
5670 const nextTitle = title.trim();
5671 if (!topic || !nextTitle) return;
5672 const activePrefix = topic.label?.startsWith("● ") ? "● " : "";
5673 topic.label = `${activePrefix}${nextTitle}`;
5674 mockTabs = mockTabs.map((tab) =>
5675 tab.topicId === topicID ? { ...tab, topicTitle: nextTitle } : tab,
5676 );
5677 },
5678 async AIRenameSession(topicID: string) { return mockAIRenameTarget(mockProjectTree, topicID); },
5679 async AIRenameSessionTarget(selector: SessionSelector): Promise<SessionMutationResult> {
5680 const node = mockSessionTitleTarget(mockProjectTree, selector);
5681 const title = node ? mockAIRenameTarget(mockProjectTree, sessionTitleTarget(node)) : "";
5682 if (node?.topicId && title) {
5683 mockTabs = mockTabs.map((tab) => tab.topicId === node.topicId ? { ...tab, topicTitle: title } : tab);
5684 notifyMockProjectTreeChanged();
5685 }
5686 return { targetKey: sessionTitleTarget(node ?? { key: "", kind: "topic", label: "" }), operationId: `mock-title-${Date.now()}`, committed: true, title, lifecycleGeneration: 1 };
5687 },
5688 async RenameSessionTarget(selector: SessionSelector, title: string): Promise<SessionMutationResult> {
5689 const node = mockSessionTitleTarget(mockProjectTree, selector);
5690 const nextTitle = title.trim();
5691 if (node && nextTitle) {
5692 const activePrefix = node.label?.startsWith("● ") ? "● " : "";
5693 node.label = `${activePrefix}${nextTitle}`;
5694 mockTabs = mockTabs.map((tab) => tab.topicId === node.topicId ? { ...tab, topicTitle: nextTitle } : tab);
5695 notifyMockProjectTreeChanged();
5696 }
5697 return { targetKey: node ? sessionTitleTarget(node) : "", operationId: `mock-title-${Date.now()}`, committed: Boolean(node), title: nextTitle, lifecycleGeneration: 1 };
5698 },
5699 async DeleteTopic(topicID: string) {
5700 deleteMockTopic(topicID);
5701 },
5702 async TrashTopic(topicID: string) {
5703 deleteMockTopic(topicID);
5704 },
5705 async SetTopicPinned(topicID: string, pinned: boolean) {
5706 setMockTopicPinned(topicID, pinned);
5707 },
5708 ...makeMockProjectTreeOrganizationBindings(mockProjectTree),
5709 async SaveWindowState(_state) {
5710 // no-op in browser dev — no real window geometry to persist
5711 },
5712 async ContextPanel(_tabID: string) {
5713 const now = Date.now();
5714 const currency = "¥";
5715 const cost = (usd: number) => currency === "¥" ? Number((usd * 7.15).toFixed(4)) : usd;
5716 return {
5717 usedTokens: 42124,
5718 windowTokens: 128000,
5719 promptTokens: 22134,
5720 completionTokens: 12345,
5721 totalTokens: 34479,
5722 reasoningTokens: 7521,
5723 cacheHitTokens: 87000,
5724 cacheMissTokens: 13000,
5725 sessionCacheHitTokens: 87000,
5726 sessionCacheMissTokens: 13000,
5727 sessionCompletionTokens: 12345,
5728 requestCount: 10,
5729 elapsedMs: 33 * 60 * 1000,
5730 sessionCost: cost(0.018),
5731 sessionCurrency: currency,
5732 sessionCostUsd: cost(0.018),
5733 sessionCostQuote: {
5734 original: { amount: String(cost(0.018)), currency: "CNY" },
5735 selected: { amount: String(cost(0.018)), currency: "CNY" },
5736 estimated: true,
5737 costComplete: true,
5738 displayComplete: true,
5739 complete: true,
5740 displayStatus: "matched",
5741 aggregateMode: "single_currency",
5742 rateBand: "mixed",
5743 },
5744 sources: {
5745 executor: {
5746 promptTokens: 24100,
5747 completionTokens: 8300,
5748 totalTokens: 32400,
5749 reasoningTokens: 5200,
5750 cacheHitTokens: 76000,
5751 cacheMissTokens: 9000,
5752 requestCount: 4,
5753 sessionCost: cost(0.0124),
5754 sessionCurrency: currency,
5755 sessionCostUsd: cost(0.0124),
5756 },
5757 planner: {
5758 promptTokens: 1800,
5759 completionTokens: 600,
5760 totalTokens: 2400,
5761 reasoningTokens: 420,
5762 cacheHitTokens: 3400,
5763 cacheMissTokens: 700,
5764 requestCount: 1,
5765 sessionCost: cost(0.0011),
5766 sessionCurrency: currency,
5767 sessionCostUsd: cost(0.0011),
5768 },
5769 subagent: {
5770 promptTokens: 4200,
5771 completionTokens: 2100,
5772 totalTokens: 6300,
5773 reasoningTokens: 1500,
5774 cacheHitTokens: 6100,
5775 cacheMissTokens: 2100,
5776 requestCount: 2,
5777 sessionCost: cost(0.0032),
5778 sessionCurrency: currency,
5779 sessionCostUsd: cost(0.0032),
5780 },
5781 compaction: {
5782 promptTokens: 2600,
5783 completionTokens: 700,
5784 totalTokens: 3300,
5785 reasoningTokens: 260,
5786 cacheHitTokens: 1100,
5787 cacheMissTokens: 900,
5788 requestCount: 1,
5789 sessionCost: cost(0.0009),
5790 sessionCurrency: currency,
5791 sessionCostUsd: cost(0.0009),
5792 },
5793 classifier: {
5794 promptTokens: 900,
5795 completionTokens: 120,
5796 totalTokens: 1020,
5797 reasoningTokens: 70,
5798 cacheHitTokens: 300,
5799 cacheMissTokens: 250,
5800 requestCount: 1,
5801 sessionCost: cost(0.0003),
5802 sessionCurrency: currency,
5803 sessionCostUsd: cost(0.0003),
5804 },
5805 title: {
5806 promptTokens: 420,
5807 completionTokens: 80,
5808 totalTokens: 500,
5809 reasoningTokens: 20,
5810 cacheHitTokens: 100,
5811 cacheMissTokens: 50,
5812 requestCount: 1,
5813 sessionCost: cost(0.0001),
5814 sessionCurrency: currency,
5815 sessionCostUsd: cost(0.0001),
5816 },
5817 },
5818 mock: true,
5819 readFiles: [
5820 { path: "README.md", turn: 2, time: now - 34 * 60 * 1000 },
5821 { path: "go.mod", turn: 3, time: now - 30 * 60 * 1000 },
5822 { path: "desktop/file.go", turn: 5, time: now - 13 * 60 * 1000, offset: 0, limit: 180 },
5823 { path: "internal/event.go", turn: 6, time: now - 4 * 60 * 1000, offset: 120, limit: 80, truncated: true },
5824 ],
5825 changedFiles: [
5826 { path: t("mock.changedFile1Path"), sources: ["session"], gitStatus: "modified", turns: [5, 6], latestPrompt: t("mock.changedFile1Prompt"), latestTime: now - 2 * 60 * 1000 },
5827 { path: t("mock.changedFile2Path"), sources: ["session"], gitStatus: "added", turns: [6], latestPrompt: t("mock.changedFile2Prompt"), latestTime: now - 60 * 1000 },
5828 ],
5829 };
5830 },
5831 // ── Remote (SSH) mock ──
5832 async RemoteHosts() {
5833 return mockRemoteHosts.slice();
5834 },
5835 async AddRemoteHost(input) {
5836 const view = mockRemoteHostView(input.label, input);
5837 mockRemoteHosts = [...mockRemoteHosts.filter((h) => h.id !== view.id), view];
5838 return view;
5839 },
5840 async UpdateRemoteHost(id, input) {
5841 const previous = mockRemoteHosts.find((h) => h.id === id);
5842 const view = mockRemoteHostView(id, input, previous);
5843 mockRemoteHosts = mockRemoteHosts.map((h) => (h.id === id ? view : h));
5844 return view;
5845 },
5846 async RemoveRemoteHost(id) {
5847 mockRemoteHosts = mockRemoteHosts.filter((h) => h.id !== id);
5848 delete mockRemoteConn[id];
5849 },
5850 async ScanSSHConfig() {
5851 return [
5852 { label: "gpu-box", host: "gpu-box", port: 0, user: "", identityFile: "", proxyJump: "", defaultWorkspace: "", serveInstall: "auto", credentialMode: "remote", useSSHConfig: true, preserveExistingSettings: true },
5853 ];
5854 },
5855 async ConnectRemoteHost(id) {
5856 mockRemoteConn[id] = "connecting";
5857 __emitMockRemote("status", { hostId: id, state: "connecting" });
5858 setTimeout(() => {
5859 mockRemoteConn[id] = "connected";
5860 __emitMockRemote("status", { hostId: id, state: "connected" });
5861 }, 300);
5862 },
5863 async DisconnectRemoteHost(id) {
5864 mockRemoteConn[id] = "stopped";
5865 __emitMockRemote("status", { hostId: id, state: "stopped" });
5866 },
5867 async RemoteConnectionStatuses() {
5868 return Object.entries(mockRemoteConn).map(([hostId, state]) => ({ hostId, state: state as RemoteConnectionStatus["state"] }));
5869 },
5870 async ConfirmRemoteHostKey(hostId, accept) {
5871 mockRemoteConn[hostId] = accept ? "connected" : "stopped";
5872 __emitMockRemote("status", { hostId, state: mockRemoteConn[hostId] });
5873 },
5874 async ConfirmRemoteSecret(hostId, _promptId, _secret, accept) {
5875 mockRemoteConn[hostId] = accept ? "connected" : "stopped";
5876 __emitMockRemote("status", { hostId, state: mockRemoteConn[hostId] });
5877 },
5878 async ListRemoteDir(_hostId, path) {
5879 const base = path.replace(/\/$/, "");
5880 return [
5881 { name: "src", path: `${base}/src`, isDir: true, size: 0, mtimeUnix: 1_700_000_000, symlink: false },
5882 { name: "README.md", path: `${base}/README.md`, isDir: false, size: 1024, mtimeUnix: 1_700_000_500, symlink: false },
5883 ];
5884 },
5885 async ReadRemoteFile(_hostId, path) {
5886 return { path, body: `# Mock remote file\n${path}\n`, size: 40, mtimeUnix: 1_700_000_500, truncated: false, binary: false };
5887 },
5888 async WriteRemoteFile(_hostId, _path, _body, _expectMtimeUnix) {
5889 return { ok: true, conflict: false, newMtimeUnix: 1_700_000_900 };
5890 },
5891 async MkdirRemote() {},
5892 async RenameRemotePath() {},
5893 async DeleteRemotePath() {},
5894 async RemoteForwards(hostId) {
5895 return mockRemoteForwards[hostId] ?? [];
5896 },
5897 async AddRemoteForward(hostId, input) {
5898 const view: RemoteForwardView = { id: `L:${input.localPort}`, hostId, ...input, state: "active" };
5899 mockRemoteForwards[hostId] = [...(mockRemoteForwards[hostId] ?? []), view];
5900 __emitMockRemote("forwards", { hostId, forwards: mockRemoteForwards[hostId] });
5901 return view;
5902 },
5903 async RemoveRemoteForward(hostId, forwardId) {
5904 mockRemoteForwards[hostId] = (mockRemoteForwards[hostId] ?? []).filter((f) => f.id !== forwardId);
5905 __emitMockRemote("forwards", { hostId, forwards: mockRemoteForwards[hostId] });
5906 },
5907 async OpenRemoteWorkspace() {},
5908 async PickRemoteIdentityFile() { return "~/.ssh/id_ed25519"; },
5909 async CheckRemotePlatform() {},
5910 async StopRemoteServer(hostId, workspace) {
5911 __emitMockRemote("server", { hostId, workspace, state: "stopped" });
5912 },
5913 async RemoteServerStatus(hostId, workspace) {
5914 return { hostId, workspace, state: "stopped" };
5915 },
5916 async RemoteServerLogs() {
5917 return "mock serve log line 1\nmock serve log line 2\n";
5918 },
5919 async RemoteLastWorkspace() {
5920 return "~/app";
5921 },
5922 async ScanRemoteLegacyWorkbenchData() {
5923 return { mirrorCount: 0, mirrorBytes: 0, trustFile: false };
5924 },
5925 async ExtensionActions() {
5926 return [];
5927 },
5928 async InvokeExtensionAction() {
5929 return "";
5930 },
5931 async SubmitExtensionForm() {},
5932 async SubmitExtensionFormExact() {}, async ResolveRemoteTabPromptExact() {}, async SubmitRemoteTabExtensionFormExact() {},
5933 ...remoteProjects.bindings,
5934 async CleanRemoteLegacyWorkbenchData() {},
5935 };
5936 }
5937 let mockRemoteHosts: RemoteHostView[] = [
5938 { id: "demo", label: "demo", host: "192.168.1.10", port: 22, user: "dev", identityFile: "", proxyJump: "", defaultWorkspace: "~/app", serveInstall: "auto", credentialMode: "remote", useSSHConfig: false },
5939 ];
5940 const mockRemoteConn: Record<string, RemoteConnectionStatus["state"]> = { demo: "connected" };
5941 const mockRemoteForwards: Record<string, RemoteForwardView[]> = {};
5942
5942 lines TYPESCRIPT