返回 DeepSeek-Reasonix
useRemoteSession.ts
根目录 / desktop / frontend / src / lib / useRemoteSession.ts
1 import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2 import { useRuntimeSession } from "./useRuntimeState";
3 import { createLegacyRemotePolicyNoticeTracker } from "./legacyRemotePolicyNotice";
4 import { app, onRemoteTabEvent, onRemoteTabState } from "./bridge";
5 import { createRemoteHydrationOwner } from "./remoteHydrationOwner";
6 import { desktopHost } from "./desktopHost";
7 import { queuedFollowupOutcome } from "./pendingFollowup";
8 import { onRemoteTabUpdated } from "./remoteTabEvents";
9 import { hydrateRemoteTelemetry, loadRemoteStatusSnapshot } from "./remoteTelemetry";
10 import { remoteStatusTakenOver, remoteStatusToAction } from "./remoteStatus";
11 import { isRemoteTakeoverError } from "./remoteErrors";
12 import { useRemoteForkTurn } from "./remoteForkTurn";
13 import { useT } from "./i18n";
14 import type { CancelOutcome } from "./inboxCancel";
15 import type { HistoryMessage } from "./types";
16 import { createTurnSubmissionId, initialState, reducer, type ControllerLiveStore, type HistoryLoadOutcome, type HistoryLoadTrigger, type State } from "./useController";
17 import { isUnknownSubmissionError } from "./localSubmissionState";
18 import { TranscriptSessionFollower } from "./transcriptSessionFollower";
19 import { getTranscriptStore } from "./transcriptStore";
20 import type { NavigateToTurn } from "./historyTurnNavigation";
21 import { historyReplaceAction } from "./sessionTranscriptMode";
22 import { isAuthoritativeRemoteStatus, remoteCheckpoints, remoteComposerState, remoteGoalRuntime, remoteGoalView } from "./remoteStatus";
23 import type { CollaborationMode, CommandInfo, EffortInfo, GoalLifecycleView, GoalRuntime, GoalStatus, QualityFloor, RemoteTabStateValue, TabMeta, ToolApprovalMode, WireEvent } from "./types";
24 import type { RemoteAskAnswer } from "./remoteTypes";
25 import type { ForkTargetView } from "./forkTargets";
26
27
28 // The remote session reuses the local transcript pipeline end to end: serve
29 // frames share the agent event wire form, so they run through the same
30 // reducer that drives local tabs, and /history hydrates through the same
31 // history action. The surface and composer therefore consume exactly the
32 // shapes the local UI consumes.
33
34 // RemoteSessionApi is the surface-facing contract of useRemoteSession.
35 // Last session path mounted per remote tab. Switching sessions inside one tab
36 // keeps the tab-keyed reducer state, so a resident paint must know the mounted
37 // content belongs to a different session before replacing it.
38 const lastPaintedSessionPathByTab = new Map<string, string>();
39
40 export interface RemoteSessionApi {
41 state: RemoteTabStateValue;
42 error: string;
43 transcript: State;
44 liveStore: ControllerLiveStore;
45 hydrated: boolean;
46 /** Content is painted from the resident cache; the authoritative hydrate is still running. */
47 revalidating: boolean;
48 syncMode?: "v2";
49 loadOlderHistory?: (targetTurn?: number, trigger?: HistoryLoadTrigger) => Promise<HistoryLoadOutcome>;
50 loadNewerHistory?: (latest?: boolean, current?: () => boolean) => Promise<HistoryLoadOutcome>;
51 navigateToTurn?: NavigateToTurn;
52 running: boolean;
53 /** The serve's label for the active model, for the composer capsule. */
54 modelLabel: string;
55 commands: CommandInfo[];
56 composerProfile?: {
57 collaborationMode: CollaborationMode;
58 toolApprovalMode: ToolApprovalMode;
59 goal: string;
60 goalStatus?: GoalStatus;
61 qualityFloor: QualityFloor;
62 };
63 goalRuntime?: GoalRuntime;
64 goalView?: GoalLifecycleView;
65 effort?: EffortInfo;
66 /** Changes whenever the tab adopts a new/reconnected Serve session snapshot. */
67 surfaceGeneration: number;
68 promptError: string;
69 submit: (text: string, displayText?: string, choice?: import("./modelApplication").ModelApplicationChoice) => Promise<void>;
70 runManagementCommand: (text: string, rehydrate?: boolean) => Promise<void>;
71 compact: (instructions: string) => Promise<void>;
72 cancelTurn: () => Promise<void>;
73 approve: (callId: string, decision: string) => Promise<void>;
74 resolvePlanDecision: (callId: string, action: "start_execution" | "revise_plan" | "exit_plan", feedback?: string) => Promise<void>;
75 answer: (callId: string, answers: RemoteAskAnswer[]) => Promise<void>;
76 clearExtensionForm: (pluginId: string, surfaceId: string, formInstanceId?: string) => void;
77 rewind: (turn: number, scope: string) => Promise<void>;
78 /** Creates the child session for one turn; returns its id, or undefined with the reason in promptError. */
79 forkTurn: (target: ForkTargetView) => Promise<{ sessionId: string; operationId: string } | undefined>;
80 acknowledgeFork: (operationId: string) => Promise<void>;
81 setModel: (ref: string) => Promise<void>;
82 setEffort: (level: string) => Promise<void>;
83 setQualityFloor: (floor: QualityFloor) => Promise<void>;
84 pauseGoal: () => Promise<void>;
85 resumeGoal: () => Promise<void>;
86 editGoal: (objective: string, maxGoalRounds: number | null) => Promise<void>;
87 steer: (input: string) => Promise<void>;
88 cancelJob: (jobId: string) => Promise<boolean>;
89 drainApprovals: (ids: string[]) => void;
90 retryHydration: () => Promise<void>;
91 }
92
93 export function useRemoteComposer(
94 session: RemoteSessionApi,
95 showToast: (message: string, level: "warn" | "error") => void,
96 ) {
97 const onSend = useCallback(async (displayText: string, submitText = displayText, choice?: import("./modelApplication").ModelApplicationChoice) => {
98 const text = (submitText || displayText).trim();
99 if (!text) return;
100 await session.submit(text, displayText, choice);
101 }, [session, showToast]);
102 const onCancel = useCallback(async (_queuedItemIDs?: string[]): Promise<CancelOutcome> => {
103 void session.cancelTurn().catch((error) => {
104 showToast(error instanceof Error ? error.message : String(error), "error");
105 });
106 return { discardedItemIds: [] };
107 }, [session, showToast]);
108 return { onSend, onCancel };
109 }
110
111 export function useActiveRemoteSession(
112 activeTab: TabMeta | undefined,
113 showToast: (message: string, level: "warn" | "error") => void,
114 ) {
115 const t = useT();
116 const active = Boolean(activeTab?.remote);
117 const session = useRemoteSession(active && activeTab ? activeTab.id : undefined, activeTab?.remoteState, activeTab?.sessionPath);
118 const composer = useRemoteComposer(session, showToast);
119 useEffect(() => {
120 if (!activeTab?.remote || !activeTab.id) return;
121 const legacyQuality = session.transcript.items.some(item => item.kind === "notice" && (item.code === "final_readiness" || item.variant === "delivery"));
122 const key = `${activeTab.id}\u0000${activeTab.sessionPath ?? ""}`;
123 const notice = legacyRemotePolicyNotice(key, session.composerProfile?.qualityFloor, session.goalRuntime?.stopCause, legacyQuality);
124 if (notice) showToast(t(notice), "warn");
125 }, [activeTab?.remote, activeTab?.id, activeTab?.sessionPath, session.composerProfile?.qualityFloor, session.transcript.items, session.goalRuntime?.stopCause, showToast, t]);
126 return { active, session, ready: active && session.state === "ready" && session.hydrated && Boolean(session.composerProfile), ...composer };
127 }
128
129 const legacyRemotePolicyNotice = createLegacyRemotePolicyNoticeTracker();
130
131 export function useRemoteSession(tabId: string | undefined, initial?: RemoteTabStateValue, sessionPath?: string): RemoteSessionApi {
132 const runtimeState = useRuntimeSession(tabId, sessionPath);
133 const [state, setState] = useState<RemoteTabStateValue>(initial === "disconnected" ? "connecting" : (initial ?? "connecting"));
134 const [error, setError] = useState("");
135 const transcript = useSyncExternalStore(
136 useCallback(listener => tabId ? getTranscriptStore().subscribeState(tabId, listener) : () => {}, [tabId]),
137 useCallback(() => (tabId ? getTranscriptStore().states.get(tabId) : undefined) ?? initialState, [tabId]),
138 );
139 const [modelLabel, setModelLabel] = useState("");
140 const [commands, setCommands] = useState<CommandInfo[]>([]);
141 const [composerProfile, setComposerProfile] = useState<RemoteSessionApi["composerProfile"]>();
142 const [goalRuntime, setGoalRuntime] = useState<GoalRuntime>();
143 const [goalView, setGoalView] = useState<GoalLifecycleView>();
144 const [effort, setEffortInfo] = useState<EffortInfo>();
145 const [surfaceGeneration, setSurfaceGeneration] = useState(0);
146 const [promptError, setPromptError] = useState("");
147 const [hydrated, setHydrated] = useState(false);
148 // A resident-cache paint shows the session instantly while the authoritative
149 // hydrate reconciles in the background.
150 const [revalidating, setRevalidating] = useState(false);
151 const cachePaintedRef = useRef(false);
152 const olderRef = useRef<((trigger?: HistoryLoadTrigger) => Promise<HistoryLoadOutcome>) | undefined>(undefined);
153 const navigateRef = useRef<NavigateToTurn | undefined>(undefined);
154 const newerRef = useRef<((latest?: boolean, current?: () => boolean) => Promise<HistoryLoadOutcome>) | undefined>(undefined);
155 const transcriptRef = useRef(transcript);
156 const submitBindingRef = useRef<object>({});
157 const setTranscript = useCallback((update: State | ((state: State) => State)) => {
158 const owned = (tabId ? getTranscriptStore().states.get(tabId) : undefined) ?? initialState;
159 const next = typeof update === "function" ? update(owned) : update;
160 transcriptRef.current = next;
161 if (tabId) getTranscriptStore().setState(tabId, next);
162 }, [tabId]);
163 const { forkTurn, acknowledgeFork, forkTargetsRefreshRef } = useRemoteForkTurn(app, tabId, sessionPath, setTranscript, setPromptError);
164 const liveListenersRef = useRef(new Set<() => void>());
165 const hydratedRef = useRef(false);
166 const hydratingRef = useRef(false);
167 const bufferedEventsRef = useRef<WireEvent[]>([]);
168 // The pre-activation history prime and the follower are never both allowed
169 // to write the resident store. "retired" is terminal for the mounted
170 // identity: it is set the moment the follower publishes its first cut (or
171 // the legacy fallback installs), after which every prime attempt is a no-op.
172 const primeRef = useRef<"idle" | "loading" | "primed" | "retired">("idle");
173 const hydrateRef = useRef<{ tabId: string; run: (force?: boolean) => Promise<void> } | null>(null);
174 const refreshStatusRef = useRef<{ tabId: string; run: () => Promise<void> } | null>(null);
175 const reconcileHistoryRef = useRef<(() => Promise<void>) | null>(null);
176 const activityRevisionRef = useRef(0);
177 const eventTurnIdRef = useRef<string | undefined>(undefined);
178 const runtimeAtActivityRef = useRef(runtimeState.state);
179 // True while the serve reports a local runtime on the host owns this
180 // session; a spectator surface idles with no other status polling, so this
181 // flag also drives a slow reconcile loop below. The ref mirrors the last
182 // observation so the owner-return transition can be detected at the source.
183 const [spectator, setSpectator] = useState(false);
184 const spectatorRef = useRef(false);
185 const noteOwnership = useCallback((takenOver: boolean) => {
186 const wasSpectator = spectatorRef.current;
187 spectatorRef.current = takenOver;
188 setSpectator(takenOver);
189 // Ownership returning is the only path back to the live transcript: the
190 // legacy fallback installed a protocol-1 view whose submit() refuses to
191 // send, and neither the state channel nor the status poll re-attaches the
192 // follower on its own.
193 if (wasSpectator && !takenOver) void hydrateRef.current?.run().catch(() => undefined);
194 }, []);
195
196 useEffect(() => {
197 for (const listener of liveListenersRef.current) listener();
198 }, [transcript]);
199
200 const liveStore = useMemo<ControllerLiveStore>(() => ({
201 subscribe(requestedTabId, listener) {
202 if (!tabId || requestedTabId !== tabId) return () => undefined;
203 liveListenersRef.current.add(listener);
204 return () => liveListenersRef.current.delete(listener);
205 },
206 getSnapshot(requestedTabId) {
207 return requestedTabId === tabId ? transcriptRef.current.live : undefined;
208 },
209 getModelActiveAt(requestedTabId) {
210 return requestedTabId === tabId ? transcriptRef.current.turnModelActiveAt : undefined;
211 },
212 getRateOutputQuarters(requestedTabId) {
213 return requestedTabId === tabId ? transcriptRef.current.turnRateSample?.outputQuarters : undefined;
214 },
215 }), [tabId]);
216
217 const applyRemoteStatus = useCallback((status: unknown) => {
218 if (!isAuthoritativeRemoteStatus(status)) return;
219 const next = remoteComposerState(status);
220 setModelLabel(next.modelLabel);
221 setComposerProfile(next.composerProfile);
222 setGoalRuntime(remoteGoalRuntime(status));
223 setGoalView(remoteGoalView(status));
224 setEffortInfo(next.effort);
225 noteOwnership(remoteStatusTakenOver(status));
226 }, [noteOwnership]);
227
228 useEffect(() => {
229 if (!tabId) return;
230 transcriptRef.current = getTranscriptStore().states.get(tabId) ?? initialState;
231 submitBindingRef.current = {};
232 // Restored shells arrive as disconnected shells. Activation must kick the
233 // backend revive (SetActiveTab → bootstrap) and never park the UI on a
234 // reconnect placeholder — treat them as connecting until ready/error.
235 const revivedFromShell = initial === "disconnected";
236 const mountedState = revivedFromShell ? "connecting" : (initial ?? "connecting");
237 setState(mountedState);
238 setError("");
239 setPromptError("");
240 // The store owns mounted content across reconnects and tab switches.
241 eventTurnIdRef.current = undefined;
242 setModelLabel("");
243 setCommands([]);
244 setComposerProfile(undefined);
245 setGoalRuntime(undefined);
246 setGoalView(undefined);
247 setEffortInfo(undefined);
248 hydratedRef.current = false;
249 hydratingRef.current = false;
250 bufferedEventsRef.current = [];
251 primeRef.current = "idle";
252 spectatorRef.current = false;
253 setSpectator(false);
254 setHydrated(false);
255 cachePaintedRef.current = false;
256 setRevalidating(false);
257 let cancelled = false;
258 let generation = 0;
259 let follower: TranscriptSessionFollower | undefined;
260 const dispatch = (action: import("./useController").Action) => {
261 if (!cancelled) setTranscript(current => reducer(current, action));
262 };
263 // History-first: the persisted canonical window is readable before the
264 // serve activates the runtime, so publish a one-shot durable baseline as
265 // soon as the tab's identity resolves. This is deliberately not a second
266 // live transcript owner — once the runtime is ready, hydrate()'s follower
267 // installs the authoritative protocol-v2 cut and owns everything after it.
268 // Mirrors the local primeReadableHistoryForTab contract.
269 const transcriptHasContent = () => {
270 const mounted = transcriptRef.current;
271 return mounted.items.length > 0 || Boolean(mounted.live?.text || mounted.live?.reasoning);
272 };
273 // Local sessions paint a resident session synchronously before any I/O
274 // (useController's peek path). The remote surface had no such path: every
275 // switch paid the network round trips even for a session whose transcript
276 // was already resident. Paint it, then let hydrate() reconcile.
277 const paintResidentCache = () => {
278 if (!tabId || !sessionPath) return false;
279 const previousPath = lastPaintedSessionPathByTab.get(tabId);
280 lastPaintedSessionPathByTab.set(tabId, sessionPath);
281 // Same session (reconnect) or a restored mount already showing content:
282 // the mounted state is this session's and may be fresher than the cut.
283 if (previousPath === sessionPath || (previousPath === undefined && transcriptHasContent())) return false;
284 const resident = getTranscriptStore().peek(tabId, sessionPath);
285 if (!resident) return false;
286 cachePaintedRef.current = true;
287 setTranscript(current => reducer(current, historyReplaceAction(resident)));
288 hydratedRef.current = true;
289 setHydrated(true);
290 setRevalidating(true);
291 return true;
292 };
293 const primeEarlyHistory = async () => {
294 if (primeRef.current !== "idle") return;
295 // Only a blank transcript may be primed, and the check has to run before
296 // loadLatest: that call bumps the resident session generation (retiring
297 // the follower's in-flight reads) and replaces records before it reads
298 // `current`, so a transcript that already has content must never reach
299 // it. history_replace has no revision guard either — a stale or empty
300 // window landing after the follower's cut would wipe the conversation.
301 if (transcriptHasContent()) { primeRef.current = "retired"; return; }
302 primeRef.current = "loading";
303 // The prime is scoped to this mounted identity and to store ownership,
304 // not to a hydrate generation: hydrate() bumps the generation the moment
305 // it starts, and a follower that then fails or stalls must not have
306 // discarded the only baseline the tab could show.
307 const current = () => !cancelled && primeRef.current === "loading";
308 try {
309 const projection = await getTranscriptStore().loadLatest(tabId, sessionPath ?? "", { current });
310 if (!projection || !current()) return;
311 if (transcriptHasContent()) { primeRef.current = "retired"; return; }
312 primeRef.current = "primed";
313 setTranscript(current => reducer(current, historyReplaceAction(projection)));
314 } catch {
315 // Before the attach handshake lands (or on a legacy serve) the window
316 // read is unavailable. A miss stays non-fatal: the next attach
317 // publication retries, and the ready-time hydration takes over.
318 } finally {
319 if (primeRef.current === "loading") primeRef.current = "idle";
320 }
321 };
322 const refreshStatus = async () => {
323 const ticket = generation;
324 const status = await app.RemoteTabStatus(tabId);
325 if (cancelled || ticket !== generation) return;
326 applyRemoteStatus(status);
327 setTranscript(current => hydrateRemoteTelemetry(current, status));
328 };
329 const hydration = createRemoteHydrationOwner(async () => {
330 const ticket = ++generation;
331 follower?.stop();
332 follower = new TranscriptSessionFollower(tabId, sessionPath ?? "", true, action => {
333 if (cancelled || ticket !== generation) return;
334 // The follower's install cut makes it the store owner (connection
335 // status frames precede it and own nothing); an early history prime
336 // still in flight must not land after that cut.
337 if (action.type === "transcript_v2_snapshot") primeRef.current = "retired";
338 dispatch(action);
339 });
340 if (!cachePaintedRef.current) setHydrated(false);
341 try {
342 await follower.start();
343 const loaded = await loadRemoteStatusSnapshot(tabId, mountedState === "ready" ? 3 : 60,
344 () => cancelled || ticket !== generation, isAuthoritativeRemoteStatus, true);
345 if (!loaded || cancelled || ticket !== generation) return false;
346 const [snapshot, status] = loaded;
347 applyRemoteStatus(status);
348 setCommands(Array.isArray(snapshot.commands) ? snapshot.commands as CommandInfo[] : []);
349 setTranscript(current => hydrateRemoteTelemetry(reducer(current,
350 { type: "checkpoints", checkpoints: remoteCheckpoints(snapshot.checkpoints) }), status));
351 hydratedRef.current = true;
352 setState("ready");
353 setHydrated(true);
354 setError("");
355 cachePaintedRef.current = false;
356 setRevalidating(false);
357 setSurfaceGeneration(value => value + 1);
358 void forkTargetsRefreshRef.current?.();
359 return true;
360 } catch (error) {
361 if (cancelled || ticket !== generation) return false;
362 // The transcript protocol requires the live runtime that owns the
363 // session. Only a session taken over by a local runtime on the serve
364 // host (the Follow request answers 409, or status reports the
365 // take-over) may fall back to the identity/legacy history view; every
366 // other failure keeps its error and waits for the next ready
367 // publication or an explicit retry.
368 const takenOver = isRemoteTakeoverError(error) || await app.RemoteTabStatus(tabId).then(remoteStatusTakenOver, () => false);
369 if (cancelled || ticket !== generation) return false;
370 if (!takenOver) { setError(String(error)); return false; }
371 try {
372 const legacyLoaded = await loadRemoteStatusSnapshot(tabId, mountedState === "ready" ? 3 : 60,
373 () => cancelled || ticket !== generation, isAuthoritativeRemoteStatus, false);
374 if (!legacyLoaded || cancelled || ticket !== generation) return false;
375 const [snapshot, status] = legacyLoaded;
376 const messages = Array.isArray(snapshot.history) ? snapshot.history as HistoryMessage[] : [];
377 const checkpoints = remoteCheckpoints(snapshot.checkpoints);
378 primeRef.current = "retired";
379 applyRemoteStatus(status);
380 setCommands(Array.isArray(snapshot.commands) ? snapshot.commands as CommandInfo[] : []);
381 setTranscript(current => {
382 let next = reducer(current, { type: "history", messages, remote: true });
383 next = reducer(next, { type: "checkpoints", checkpoints });
384 next = reducer(next, remoteStatusToAction(status, Date.now(), next.running));
385 return hydrateRemoteTelemetry(next, status);
386 });
387 hydratedRef.current = true;
388 setState("ready");
389 setHydrated(true);
390 setError("");
391 cachePaintedRef.current = false;
392 setRevalidating(false);
393 setSurfaceGeneration(value => value + 1);
394 void forkTargetsRefreshRef.current?.();
395 return true;
396 } catch (fallbackError) {
397 if (!cancelled && ticket === generation) setError(String(fallbackError));
398 }
399 }
400 return false;
401 });
402 const hydrate = () => hydration.load();
403 const offContent = getTranscriptStore().subscribe(tabId, change => change.projection
404 ? dispatch({ type: "transcript_records", projection: change.projection, confirmedUsers: [] })
405 : dispatch({ type: "history_items_patch", patches: change.patches, expected: change.expected }));
406 navigateRef.current = async (target, current) => (await import("./historyTurnNavigation")).navigateHistoryTurn(tabId, transcriptRef.current, () => cancelled ? undefined : transcriptRef.current, dispatch, target, () => !cancelled && current());
407 olderRef.current = async () => {
408 if (transcriptRef.current.historyOlderLoading) return "empty";
409 dispatch({ type: "history_older_start" });
410 try {
411 const page = await getTranscriptStore().loadOlder(tabId, sessionPath ?? "");
412 if (!page || cancelled) return "empty";
413 if (page.kind === "reload") { await hydrate(); return "loaded"; }
414 if (transcriptRef.current.transcriptProtocol === 2) dispatch({ type: "transcript_records", projection: page, confirmedUsers: [] });
415 else dispatch({ type: "history_prepend", items: page.prependItems, removeIds: page.removeIds,
416 startTurn: page.startTurn, endTurn: page.endTurn, totalTurns: page.totalTurns,
417 hasOlder: page.hasOlder, hasNewer: page.hasNewer, revision: page.revision, digest: page.digest });
418 return "loaded";
419 } catch (error) {
420 dispatch({ type: "history_older_error", error: String(error) });
421 return "empty";
422 }
423 };
424 hydrateRef.current = { tabId, run: hydrate };
425 newerRef.current = async (latest = false, current = () => true) => {
426 if (transcriptRef.current.historyNewerLoading) return "empty";
427 dispatch({ type: "history_newer_start" });
428 try {
429 if (latest) {
430 const projection = await getTranscriptStore().loadLatest(tabId, sessionPath ?? "", { current: () => !cancelled && current() });
431 if (!projection || cancelled) { dispatch({ type: "history_newer_error", error: "" }); return "empty"; }
432 dispatch({ type: "transcript_records", projection: { ...projection, removeIds: [] }, confirmedUsers: [] });
433 return "loaded";
434 }
435 const page = await getTranscriptStore().loadNewer(tabId, sessionPath ?? "");
436 if (!page || cancelled) { dispatch({ type: "history_newer_error", error: "" }); return "empty"; }
437 if (page.kind === "stale") { await hydrate(); return "loaded"; }
438 if (transcriptRef.current.transcriptProtocol === 2) dispatch({ type: "transcript_records", projection: page, confirmedUsers: [] });
439 else dispatch({ type: "history_append", items: page.items,
440 startTurn: page.startTurn, endTurn: page.endTurn, totalTurns: page.totalTurns,
441 hasOlder: page.hasOlder, hasNewer: page.hasNewer, revision: page.revision, digest: page.digest });
442 return "loaded";
443 } catch (error) {
444 dispatch({ type: "history_newer_error", error: String(error) });
445 return "empty";
446 }
447 };
448 refreshStatusRef.current = { tabId, run: refreshStatus };
449 reconcileHistoryRef.current = hydrate;
450 const acceptState: Parameters<typeof onRemoteTabState>[1] = next => {
451 if (cancelled || !hydration.observe(next.hydrationRevision)) return;
452 setState(next.state);
453 setError(next.error ?? "");
454 if (next.state === "ready") void hydration.load(next.hydrationRevision);
455 else {
456 generation++;
457 follower?.stop();
458 setHydrated(false);
459 setRevalidating(false);
460 dispatch({ type: "transcript_connection", status: "disconnected" });
461 }
462 };
463 const offState = onRemoteTabState(tabId, acceptState);
464 // Ownership flips arrive as tab meta updates (an explicit reclaim clears
465 // the pin there before any status poll runs); mirror them into the
466 // spectator flag that drives the reconcile loop below.
467 const offMeta = onRemoteTabUpdated(meta => {
468 if (cancelled || meta?.id !== tabId) return;
469 noteOwnership(Boolean(meta.takenOver));
470 // The attach publication is the reliable "identity live, activation
471 // still in flight" signal — retry the early history read there.
472 void primeEarlyHistory();
473 });
474 // The legacy event channel carries ancillary invalidations only.
475 const offEvent = onRemoteTabEvent(tabId, raw => {
476 const event = raw as WireEvent;
477 if (event.kind === "turn_done") {
478 void refreshStatus().catch(() => undefined);
479 void forkTargetsRefreshRef.current?.();
480 }
481 });
482 if (revivedFromShell) void app.SetActiveTab(tabId).catch(() => undefined);
483 paintResidentCache();
484 void primeEarlyHistory();
485 const refreshHydration = async () => {
486 if (cancelled || !serviceReady) return;
487 const ticket = generation;
488 let next;
489 try { next = await app.RemoteTabHydrationState?.(tabId); } catch { /* Older hosts lack this read. */ }
490 if (cancelled || !serviceReady || generation !== ticket) return;
491 if (next) acceptState(next);
492 else void hydrate();
493 };
494 let serviceGeneration: string | undefined, serviceReady = true;
495 // The shell's desktop:resync read follows reattachment; native states
496 // invalidate the old owner without starting a competing recovery read.
497 const offService = desktopHost().native.onServiceState(({ phase, generation: nextGeneration }) => {
498 const replacing = serviceGeneration && nextGeneration && serviceGeneration !== nextGeneration;
499 serviceGeneration = nextGeneration ?? serviceGeneration;
500 serviceReady = phase === "ready";
501 if (replacing || !serviceReady) {
502 generation++;
503 hydration.reset();
504 follower?.stop(false, "service_stopping");
505 }
506 });
507 const offResync = desktopHost().events.on("desktop:resync", refreshHydration);
508 refreshHydration();
509 return () => {
510 submitBindingRef.current = {};
511 cancelled = true;
512 generation++;
513 follower?.stop();
514 offContent();
515 offState();
516 offMeta();
517 offEvent();
518 offService();
519 offResync();
520 olderRef.current = undefined;
521 navigateRef.current = undefined;
522 newerRef.current = undefined;
523 hydrateRef.current = null;
524 refreshStatusRef.current = null;
525 reconcileHistoryRef.current = null;
526 };
527 }, [applyRemoteStatus, noteOwnership, tabId, sessionPath, setTranscript]);
528
529 // A spectator surface idles with no status traffic: the running watchdog
530 // only reconciles turns, and the read-only composer blocks the sends that
531 // would otherwise refresh status. A stale ownership observation could pin
532 // the takeover banner forever, so poll at a slow cadence until the serve
533 // reports the session free again.
534 useEffect(() => {
535 if (!tabId || state !== "ready" || !spectator) return;
536 const timer = window.setInterval(() => {
537 void refreshStatusRef.current?.run().catch(() => undefined);
538 }, 5_000);
539 return () => window.clearInterval(timer);
540 }, [tabId, state, spectator]);
541
542 const submit = useCallback(async (text: string, displayText = text, choice?: import("./modelApplication").ModelApplicationChoice) => {
543 if (!tabId) return;
544 if (transcriptRef.current.transcriptProtocol !== 2 || transcriptRef.current.transcriptConnection !== "connected") {
545 throw new Error("Transcript v2 is not synchronized. Upgrade Desktop and Serve together, or reconnect.");
546 }
547 const trimmed = text.trim();
548 if (!trimmed) return;
549 // Optimistic user bubble, exactly like the local send path. seq rides
550 // the reducer's counter; the submission id only needs uniqueness.
551 const before = getTranscriptStore().states.get(tabId) ?? initialState;
552 const binding = submitBindingRef.current;
553 const current = () => submitBindingRef.current === binding && getTranscriptStore().states.get(tabId)?.sessionGen === before.sessionGen;
554 const submissions = Object.values(before.localSubmissions);
555 if (submissions.some(item => item.status === "sending" && (item.submitText ?? item.text).trim() === trimmed)) return;
556 const unresolved = submissions.find(item => item.status === "unknown");
557 if(unresolved && (choice || (unresolved.submitText ?? unresolved.text).trim()!==trimmed)) {
558 throw Object.assign(new Error("Confirm the previous submission before sending another message"),{data:{submissionOutcome:"unknown"}});
559 }
560 const submissionId = unresolved?.submissionId ?? createTurnSubmissionId(tabId, before.sessionGen, before.seq, before.meta?.runtime?.epoch);
561 activityRevisionRef.current += 1;
562 runtimeAtActivityRef.current = runtimeState.state;
563 if(!unresolved) setTranscript((s) => reducer(s, { type: "user", text: displayText.trim(), submitText:trimmed, seq: s.seq, submissionId }));
564 try {
565 if (choice) {
566 if (!app.SubmitRemoteTabWithModelApplication) throw new Error("Upgrade Desktop to use model application recovery");
567 await app.SubmitRemoteTabWithModelApplication(tabId, trimmed, submissionId, choice);
568 } else if (app.SubmitRemoteTabWithSubmission) await app.SubmitRemoteTabWithSubmission(tabId, trimmed, submissionId);
569 else await app.SubmitRemoteTab(tabId, trimmed);
570 if (current()) setTranscript(s => reducer(s, { type: "send_confirmed", submissionId }));
571 } catch (e) {
572 // A busy-window submit is durably queued by the desktop. The queue strip
573 // is its representation, so retract the optimistic bubble instead of
574 // reporting a failure; the receipt rides the error for the composer.
575 if (queuedFollowupOutcome(e) !== undefined) {
576 if (current()) setTranscript((s) => reducer(s, { type: "send_queued", submissionId }));
577 throw e;
578 }
579 // Roll the optimistic running flag back — a refused/failed submit must
580 // never leave the pill spinning (same contract as the local send path).
581 const error = `Send failed: ${e instanceof Error ? e.message : String(e)}`;
582 if (current()) setTranscript((s) => reducer(s, { type: isUnknownSubmissionError(e) ? "turn_submit_unknown" : "send_failed", submissionId, error }));
583 throw e;
584 }
585 }, [tabId, runtimeState.state, setTranscript]);
586
587 const runManagementCommand = useCallback(async (text: string, rehydrate = false) => {
588 if (!tabId) return;
589 const trimmed = text.trim();
590 if (!trimmed) return;
591 // Management verbs produce notices/state changes rather than a model
592 // turn, so do not create the optimistic conversational bubble used by
593 // submit(). Refresh the authoritative profile after the command settles.
594 await app.SubmitRemoteTab(tabId, trimmed);
595 if (rehydrate) {
596 const hydration = hydrateRef.current;
597 if (hydration?.tabId === tabId) await hydration.run(true);
598 return;
599 }
600 const current = refreshStatusRef.current;
601 if (current?.tabId === tabId) await current.run();
602 }, [tabId]);
603
604 const cancelTurn = useCallback(async () => {
605 if (!tabId) return;
606 await app.CancelRemoteTab(tabId);
607 }, [tabId]);
608
609 const approve = useCallback(async (callId: string, decision: string) => {
610 if (!tabId) return;
611 setPromptError("");
612 try {
613 await app.ApproveRemoteTab(tabId, callId, decision);
614 setTranscript((s) => s.approval?.id === callId ? { ...s, approval: undefined } : s);
615 } catch (error) {
616 setPromptError(error instanceof Error ? error.message : String(error));
617 throw error;
618 }
619 }, [tabId]);
620
621 const resolvePlanDecision = useCallback(async (
622 callId: string,
623 action: "start_execution" | "revise_plan" | "exit_plan",
624 feedback = "",
625 ) => {
626 if (!tabId) return;
627 setPromptError("");
628 try {
629 await app.ResolveRemoteTabPlanDecision(tabId, callId, action, feedback);
630 setTranscript((s) => s.approval?.id === callId ? { ...s, approval: undefined } : s);
631 } catch (error) {
632 setPromptError(error instanceof Error ? error.message : String(error));
633 throw error;
634 }
635 }, [tabId]);
636
637 const answer = useCallback(async (callId: string, answers: RemoteAskAnswer[]) => {
638 if (!tabId) return;
639 setPromptError("");
640 try {
641 await app.AnswerRemoteTab(tabId, callId, answers);
642 setTranscript((s) => s.ask?.id === callId ? { ...s, ask: undefined } : s);
643 } catch (error) {
644 setPromptError(error instanceof Error ? error.message : String(error));
645 throw error;
646 }
647 }, [tabId]);
648
649 const clearExtensionForm = useCallback((pluginId: string, surfaceId: string, formInstanceId?: string) => {
650 setTranscript((s) => s.extensionForm?.pluginId === pluginId && s.extensionForm.surfaceId === surfaceId &&
651 (!formInstanceId || s.extensionForm.formInstanceId === formInstanceId)
652 ? reducer(s, { type: "clearExtensionForm" }) : s);
653 }, []);
654
655 const retryHydration = useCallback((): Promise<void> => {
656 setError("");
657 const current = hydrateRef.current;
658 if (!current || current.tabId !== tabId) return Promise.resolve();
659 return current.run(true);
660 }, [tabId]);
661
662 const compact = useCallback(async (instructions: string) => {
663 if (!tabId) return;
664 await app.CompactRemoteTab(tabId, instructions);
665 await retryHydration();
666 }, [retryHydration, tabId]);
667
668 const refreshStatus = useCallback((): Promise<void> => {
669 const current = refreshStatusRef.current;
670 if (!current || current.tabId !== tabId) return Promise.resolve();
671 return current.run();
672 }, [tabId]);
673
674 const cancelJob = useCallback(async (jobId: string) => {
675 if (!tabId) return false;
676 try {
677 await app.CancelRemoteTabJobs(tabId, [jobId]);
678 await refreshStatus();
679 return true;
680 } catch (error) {
681 setPromptError(String(error));
682 return false;
683 }
684 }, [refreshStatus, tabId]);
685
686 const rewind = useCallback(async (turn: number, scope: string) => {
687 if (!tabId) return;
688 setPromptError("");
689 try {
690 switch (scope) {
691 // No fork scope: the serve's /fork switches the parent session; forkTurn creates a child instead.
692 case "summ-from":
693 await app.SummarizeRemoteTab(tabId, turn, "from");
694 break;
695 case "summ-upto":
696 await app.SummarizeRemoteTab(tabId, turn, "upto");
697 break;
698 case "code":
699 case "conversation":
700 case "both":
701 await app.RewindRemoteTab(tabId, String(turn), scope);
702 break;
703 default:
704 throw new Error(`Unsupported remote rewind scope: ${scope}`);
705 }
706 await retryHydration();
707 } catch (error) {
708 setPromptError(error instanceof Error ? error.message : String(error));
709 throw error;
710 }
711 }, [retryHydration, tabId]);
712
713 const setEffort = useCallback(async (level: string) => {
714 if (!tabId) return;
715 await app.SetRemoteTabEffort(tabId, level);
716 await refreshStatus();
717 }, [refreshStatus, tabId]);
718
719 const setModel = useCallback(async (ref: string) => {
720 if (!tabId) return;
721 await app.SetRemoteTabModel(tabId, ref);
722 await refreshStatus();
723 }, [refreshStatus, tabId]);
724
725 const setQualityFloor = useCallback(async (floor: QualityFloor) => {
726 if (!tabId) return;
727 // Compatibility only. The new client never asks an old server to change
728 // policy behind the user's back; its next status remains authoritative.
729 if (floor !== "standard" && floor !== "delivery") throw new Error(`Unknown retired execution setting: ${floor}`);
730 await app.SetRemoteTabQualityFloor(tabId, floor);
731 }, [tabId]);
732
733 const pauseGoal = useCallback(async () => {
734 if (!tabId) return;
735 await app.PauseRemoteTabGoal(tabId);
736 await refreshStatus();
737 }, [refreshStatus, tabId]);
738
739 const resumeGoal = useCallback(async () => {
740 if (!tabId) return;
741 await app.ResumeRemoteTabGoal(tabId);
742 await refreshStatus();
743 }, [refreshStatus, tabId]);
744
745 const editGoal = useCallback(async (objective: string, maxGoalRounds: number | null) => {
746 if (!tabId) return;
747 await app.EditRemoteTabGoal(tabId, objective, maxGoalRounds);
748 await refreshStatus();
749 }, [refreshStatus, tabId]);
750
751 const steer = useCallback(async (input: string) => {
752 if (!tabId) return;
753 await app.SteerRemoteTab(tabId, input);
754 }, [tabId]);
755
756 const drainApprovals = useCallback((ids: string[]) => {
757 setTranscript((current) => reducer(current, { type: "approval_drained", ids, epoch: current.promptEpoch }));
758 }, []);
759
760 return {
761 state, error, transcript, liveStore, hydrated, revalidating, syncMode: "v2", navigateToTurn: (target, current) => navigateRef.current?.(target, current) ?? Promise.resolve("cancelled"), loadOlderHistory: (_targetTurn?: number, trigger?: HistoryLoadTrigger) => olderRef.current?.(trigger) ?? Promise.resolve("empty"), loadNewerHistory: (latest = false, current) => newerRef.current?.(latest, current) ?? Promise.resolve("empty"), running: transcript.running, modelLabel, commands,
762 composerProfile, goalRuntime, goalView, effort, surfaceGeneration, promptError, submit, runManagementCommand, compact, cancelTurn,
763 approve, resolvePlanDecision, answer, clearExtensionForm, rewind, forkTurn, acknowledgeFork, setModel, setEffort, setQualityFloor, pauseGoal, resumeGoal, editGoal, steer, cancelJob,
764 drainApprovals, retryHydration,
765 };
766 }
767
767 lines TYPESCRIPT