The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
fix(web): agent tabs in background threads open in the desktop browser (#19919)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Mahir Abbas committed
Oct 20, 2026 at 05:55 UTC
e32814e8f65d0eb36a5d6222c82470582621e357
5 files changed
+180
-6
apps/web/src/browser/ElectronBrowserHost.tsx
+2
@@ -13,6 +13,7 @@ import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
13
14
import { isElectron } from "~/env";
15
import { useClientSettingsHydrated } from "~/hooks/useSettings";
16
+import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
17
import { useActivePreviewSessions } from "~/previewStateStore";
18
import { previewEnvironment } from "~/state/preview";
19
import { useEnvironmentScope } from "~/state/session";
@@ -29,6 +30,7 @@ import { previewRuntimeTabId } from "./previewRuntimeTabId";
30
export function ElectronBrowserHost() {
31
const previewByThreadKey = useActivePreviewSessions();
32
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
33
+ useDesktopHostedPreviewSessions(primaryEnvironmentId);
34
const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
35
const threadRef = parseScopedThreadKey(threadKey);
36
return threadRef
apps/web/src/components/preview/previewSessionSync.browser.test.ts
+51
-3
@@ -26,6 +26,8 @@ const harness = vi.hoisted(() => ({
26
events: new Map<string, Atom.Writable<EventResult>>(),
27
}));
28
29
+vi.mock("~/env", () => ({ isElectron: true }));
30
+
31
vi.mock("~/state/preview", async () => {
32
const { AsyncResult, Atom } = await import("effect/reactivity");
33
return {
@@ -74,7 +76,7 @@ import {
76
} from "~/previewStateStore";
77
import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
78
import { previewEnvironment } from "~/state/preview";
77
-import { usePreviewSession } from "./usePreviewSession";
79
+import { useDesktopHostedPreviewSessions, usePreviewSession } from "./usePreviewSession";
80
81
let root: Root | null = null;
82
let container: HTMLDivElement | null = null;
@@ -107,11 +109,16 @@ const result = (
109
})),
110
});
111
110
-async function mount() {
112
+function DesktopSessionSync() {
113
+ useDesktopHostedPreviewSessions(ref.environmentId);
114
+ return null;
115
+}
116
+
117
+async function mount(Component = SessionSync) {
118
container = document.body.appendChild(document.createElement("div"));
119
root = createRoot(container);
120
await act(async () => {
114
- root!.render(createElement(AppAtomRegistryProvider, null, createElement(SessionSync)));
121
+ root!.render(createElement(AppAtomRegistryProvider, null, createElement(Component)));
122
});
123
}
124
@@ -134,6 +141,47 @@ afterEach(async () => {
141
});
142
143
describe("native preview session synchronization", () => {
144
+ it("discovers and closes a server tab in a background thread without mounting its chat", async () => {
145
+ await mount(DesktopSessionSync);
146
+ expect(readThreadPreviewState(ref).sessions).toEqual({});
147
+ previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
148
+ const events = harness.events.get(ref.environmentId)!;
149
+ const baseline = result(1, ["agent-tab"]);
150
+ const snapshot = baseline.sessions[0]!;
151
+ await act(async () => {
152
+ appAtomRegistry.set(
153
+ events,
154
+ AsyncResult.success({
155
+ type: "opened",
156
+ threadId: ref.threadId,
157
+ tabId: snapshot.tabId,
158
+ snapshot,
159
+ serverEpoch: baseline.serverEpoch,
160
+ revision: baseline.revision,
161
+ createdAt: snapshot.updatedAt,
162
+ }),
163
+ );
164
+ });
165
+ expect(readThreadPreviewState(ref).sessions).toEqual({ "agent-tab": snapshot });
166
+ appAtomRegistry.set(listAtom(), AsyncResult.success(baseline));
167
+ expect(readThreadPreviewState(ref).listLoaded).toBe(true);
168
+ expect(readThreadPreviewState(ref).snapshot).toEqual(snapshot);
169
+
170
+ appAtomRegistry.set(
171
+ events,
172
+ AsyncResult.success({
173
+ type: "closed",
174
+ threadId: ref.threadId,
175
+ tabId: snapshot.tabId,
176
+ serverEpoch: baseline.serverEpoch,
177
+ revision: 2,
178
+ createdAt: snapshot.updatedAt,
179
+ }),
180
+ );
181
+ expect(readThreadPreviewState(ref).sessions).toEqual({});
182
+ expect(readThreadPreviewState(ref).activeTabId).toBeNull();
183
+ });
184
+
185
it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
186
const atom = listAtom();
187
await mount();
apps/web/src/components/preview/usePreviewSession.ts
+41
-2
@@ -1,8 +1,12 @@
1
"use client";
2
3
import { useAtomValue } from "@effect/atom-react";
4
-import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
5
-import type { ScopedThreadRef } from "@t3tools/contracts";
4
+import {
5
+ parseScopedThreadKey,
6
+ scopeThreadRef,
7
+ scopedThreadKey,
8
+} from "@t3tools/client-runtime/environment";
9
+import { type EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
10
import * as Schema from "effect/Schema";
11
import { AsyncResult, Atom } from "effect/reactivity";
12
@@ -11,6 +15,7 @@ import {
15
readThreadPreviewState,
16
reconcilePreviewServerSessions,
17
} from "~/previewStateStore";
18
+import { isElectron } from "~/env";
19
import { previewEnvironment } from "~/state/preview";
20
21
class PreviewSessionThreadKeyParseError extends Schema.TaggedError<PreviewSessionThreadKeyParseError>()(
@@ -94,3 +99,37 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
99
export function usePreviewSession(threadRef: ScopedThreadRef): void {
100
useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef)));
101
}
102
+
103
+const inactiveAtom = Atom.make(() => undefined);
104
+
105
+// Discover background tabs without listing every thread at startup. Retain each
106
+// sync for the host's lifetime so later events still arrive while chat is absent.
107
+const desktopHostedPreviewSyncAtom = Atom.family((environmentId: EnvironmentId) => {
108
+ const eventsAtom = previewEnvironment.events({ environmentId, input: {} });
109
+ return Atom.make((get) => {
110
+ const syncedThreadIds = new Set<string>();
111
+ get.subscribe(
112
+ eventsAtom,
113
+ (result) => {
114
+ if (!AsyncResult.isSuccess(result) || result.value.type === "closed") return;
115
+ const threadId = result.value.threadId;
116
+ if (syncedThreadIds.has(threadId)) return;
117
+ syncedThreadIds.add(threadId);
118
+ get.mount(
119
+ previewSessionSyncAtom(
120
+ scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(threadId))),
121
+ ),
122
+ );
123
+ },
124
+ { immediate: true },
125
+ );
126
+ }).pipe(Atom.withLabel(`preview:desktop-hosted-sync:${environmentId}`));
127
+});
128
+
129
+export function useDesktopHostedPreviewSessions(environmentId: EnvironmentId | null): void {
130
+ useAtomValue(
131
+ isElectron && environmentId !== null
132
+ ? desktopHostedPreviewSyncAtom(environmentId)
133
+ : inactiveAtom,
134
+ );
135
+}
packages/client-runtime/src/state/preview.ts
+3
@@ -1,4 +1,5 @@
1
import { WS_METHODS } from "@t3tools/contracts";
2
+import * as Stream from "effect/Stream";
3
import { Atom } from "effect/reactivity";
4
5
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -28,6 +29,8 @@ export function createPreviewEnvironmentAtoms<R, E>(
29
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
30
label: "environment-data:preview:events",
31
tag: WS_METHODS.subscribePreviewEvents,
32
+ // Stream atoms publish only the last value per chunk; every preview event must arrive.
33
+ transform: (stream) => stream.pipe(Stream.rechunk(1)),
34
}),
35
discoveredServers: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
36
label: "environment-data:preview:discovered-servers",
packages/client-runtime/src/state/runtime.test.ts
+83
-1
@@ -1,6 +1,7 @@
1
import { describe, expect, it, vi } from "@effect/vitest";
2
import {
3
EnvironmentId,
4
+ type PreviewEvent,
5
type TerminalAttachInput,
6
type TerminalAttachStreamEvent,
7
type TerminalMetadataStreamEvent,
@@ -32,6 +33,7 @@ import * as EnvironmentRegistry from "../connection/registry.ts";
33
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34
import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
35
import type * as RpcSession from "../rpc/session.ts";
36
+import { createPreviewEnvironmentAtoms } from "./preview.ts";
37
import type { QueryPersistence } from "./queryPersistence.ts";
38
import { createTerminalEnvironmentAtoms } from "./terminal.ts";
39
import {
@@ -96,6 +98,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
98
idleTtlMs,
99
persistence,
100
initialState,
101
+ rpcSession,
102
isFinal,
103
}: {
104
readonly refreshTrigger?: Atom.Atom<unknown>;
@@ -103,10 +106,13 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
106
readonly idleTtlMs?: number;
107
readonly persistence?: QueryPersistence<A>;
108
readonly initialState?: SupervisorConnectionState;
109
+ readonly rpcSession?: RpcSession.RpcSession;
110
} = {},
111
) {
112
const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
109
- const supervisorSession = yield* SubscriptionRef.make(Option.some(QUERY_RPC_SESSION));
113
+ const supervisorSession = yield* SubscriptionRef.make(
114
+ Option.some(rpcSession ?? QUERY_RPC_SESSION),
115
+ );
116
const streamGeneration = yield* SubscriptionRef.make(0);
117
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
118
target: QUERY_ENVIRONMENT,
@@ -320,6 +326,82 @@ describe("environmentRpcKey", () => {
326
});
327
});
328
329
+describe("preview event subscriptions", () => {
330
+ it.effect("delivers every open and close when RPC events arrive in batches", () =>
331
+ Effect.scoped(
332
+ Effect.gen(function* () {
333
+ const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
334
+ type: "opened",
335
+ threadId,
336
+ tabId: `tab-${index}`,
337
+ serverEpoch: "epoch-1",
338
+ revision: index + 1,
339
+ createdAt: "2026-10-02T00:00:00.000Z",
340
+ snapshot: {
341
+ threadId,
342
+ tabId: `tab-${index}`,
343
+ navStatus: { _tag: "Idle" },
344
+ canGoBack: false,
345
+ canGoForward: false,
346
+ updatedAt: "2026-10-02T00:00:00.000Z",
347
+ },
348
+ }));
349
+ const closed: PreviewEvent[] = opened.map((event, index) => ({
350
+ type: "closed",
351
+ threadId: event.threadId,
352
+ tabId: event.tabId,
353
+ serverEpoch: event.serverEpoch,
354
+ revision: opened.length + index + 1,
355
+ createdAt: event.createdAt,
356
+ }));
357
+ const releaseEvents = yield* Deferred.make<void>();
358
+ // Each iterable is one RPC chunk; separate emissions would hide lost events.
359
+ const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
360
+ Stream.flatMap(() =>
361
+ Stream.fromIterable(opened).pipe(
362
+ Stream.concat(Stream.fromIterable(closed)),
363
+ Stream.concat(Stream.never),
364
+ ),
365
+ ),
366
+ );
367
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
368
+ rpcSession: {
369
+ client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
370
+ } as unknown as RpcSession.RpcSession,
371
+ });
372
+ const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
373
+ environmentId: QUERY_ENVIRONMENT.environmentId,
374
+ input: {},
375
+ });
376
+ const registry = AtomRegistry.make();
377
+ const observed: PreviewEvent[] = [];
378
+ const sawLast = yield* Deferred.make<void>();
379
+ const unsubscribe = registry.subscribe(
380
+ atom,
381
+ (result) => {
382
+ if (!AsyncResult.isSuccess(result)) return;
383
+ observed.push(result.value);
384
+ if (result.value === closed[closed.length - 1]) {
385
+ Deferred.doneUnsafe(sawLast, Exit.void);
386
+ }
387
+ },
388
+ { immediate: true },
389
+ );
390
+ yield* Effect.addFinalizer(() =>
391
+ Effect.sync(() => {
392
+ unsubscribe();
393
+ registry.dispose();
394
+ }),
395
+ );
396
+
397
+ yield* Deferred.succeed(releaseEvents, undefined);
398
+ yield* Deferred.await(sawLast);
399
+ expect(observed).toEqual([...opened, ...closed]);
400
+ }),
401
+ ),
402
+ );
403
+});
404
+
405
describe("finite environment subscription lifecycle", () => {
406
it.effect(
407
"exposes early values and settles on the terminal value without waiting for a reconnect",