Skip to content

Commit e32814e

Browse files
MahirAbbasclaudejuliusmarminge
authored
fix(web): agent tabs in background threads open in the desktop browser (#19919)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent a8e9484 commit e32814e

5 files changed

Lines changed: 180 additions & 6 deletions

File tree

‎apps/web/src/browser/ElectronBrowserHost.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
1313

1414
import { isElectron } from "~/env";
1515
import { useClientSettingsHydrated } from "~/hooks/useSettings";
16+
import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
1617
import { useActivePreviewSessions } from "~/previewStateStore";
1718
import { previewEnvironment } from "~/state/preview";
1819
import { useEnvironmentScope } from "~/state/session";
@@ -29,6 +30,7 @@ import { previewRuntimeTabId } from "./previewRuntimeTabId";
2930
export function ElectronBrowserHost() {
3031
const previewByThreadKey = useActivePreviewSessions();
3132
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
33+
useDesktopHostedPreviewSessions(primaryEnvironmentId);
3234
const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
3335
const threadRef = parseScopedThreadKey(threadKey);
3436
return threadRef

‎apps/web/src/components/preview/previewSessionSync.browser.test.ts‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ const harness = vi.hoisted(() => ({
2626
events: new Map<string, Atom.Writable<EventResult>>(),
2727
}));
2828

29+
vi.mock("~/env", () => ({ isElectron: true }));
30+
2931
vi.mock("~/state/preview", async () => {
3032
const { AsyncResult, Atom } = await import("effect/reactivity");
3133
return {
@@ -74,7 +76,7 @@ import {
7476
} from "~/previewStateStore";
7577
import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
7678
import { previewEnvironment } from "~/state/preview";
77-
import { usePreviewSession } from "./usePreviewSession";
79+
import { useDesktopHostedPreviewSessions, usePreviewSession } from "./usePreviewSession";
7880

7981
let root: Root | null = null;
8082
let container: HTMLDivElement | null = null;
@@ -107,11 +109,16 @@ const result = (
107109
})),
108110
});
109111

110-
async function mount() {
112+
function DesktopSessionSync() {
113+
useDesktopHostedPreviewSessions(ref.environmentId);
114+
return null;
115+
}
116+
117+
async function mount(Component = SessionSync) {
111118
container = document.body.appendChild(document.createElement("div"));
112119
root = createRoot(container);
113120
await act(async () => {
114-
root!.render(createElement(AppAtomRegistryProvider, null, createElement(SessionSync)));
121+
root!.render(createElement(AppAtomRegistryProvider, null, createElement(Component)));
115122
});
116123
}
117124

@@ -134,6 +141,47 @@ afterEach(async () => {
134141
});
135142

136143
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+
137185
it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
138186
const atom = listAtom();
139187
await mount();

‎apps/web/src/components/preview/usePreviewSession.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
"use client";
22

33
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";
610
import * as Schema from "effect/Schema";
711
import { AsyncResult, Atom } from "effect/reactivity";
812

@@ -11,6 +15,7 @@ import {
1115
readThreadPreviewState,
1216
reconcilePreviewServerSessions,
1317
} from "~/previewStateStore";
18+
import { isElectron } from "~/env";
1419
import { previewEnvironment } from "~/state/preview";
1520

1621
class PreviewSessionThreadKeyParseError extends Schema.TaggedError<PreviewSessionThreadKeyParseError>()(
@@ -94,3 +99,37 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
9499
export function usePreviewSession(threadRef: ScopedThreadRef): void {
95100
useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef)));
96101
}
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‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { WS_METHODS } from "@t3tools/contracts";
2+
import * as Stream from "effect/Stream";
23
import { Atom } from "effect/reactivity";
34

45
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -28,6 +29,8 @@ export function createPreviewEnvironmentAtoms<R, E>(
2829
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
2930
label: "environment-data:preview:events",
3031
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)),
3134
}),
3235
discoveredServers: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
3336
label: "environment-data:preview:discovered-servers",

‎packages/client-runtime/src/state/runtime.test.ts‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it, vi } from "@effect/vitest";
22
import {
33
EnvironmentId,
4+
type PreviewEvent,
45
type TerminalAttachInput,
56
type TerminalAttachStreamEvent,
67
type TerminalMetadataStreamEvent,
@@ -32,6 +33,7 @@ import * as EnvironmentRegistry from "../connection/registry.ts";
3233
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
3334
import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
3435
import type * as RpcSession from "../rpc/session.ts";
36+
import { createPreviewEnvironmentAtoms } from "./preview.ts";
3537
import type { QueryPersistence } from "./queryPersistence.ts";
3638
import { createTerminalEnvironmentAtoms } from "./terminal.ts";
3739
import {
@@ -96,17 +98,21 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
9698
idleTtlMs,
9799
persistence,
98100
initialState,
101+
rpcSession,
99102
isFinal,
100103
}: {
101104
readonly refreshTrigger?: Atom.Atom<unknown>;
102105
readonly isFinal?: (value: A) => boolean;
103106
readonly idleTtlMs?: number;
104107
readonly persistence?: QueryPersistence<A>;
105108
readonly initialState?: SupervisorConnectionState;
109+
readonly rpcSession?: RpcSession.RpcSession;
106110
} = {},
107111
) {
108112
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+
);
110116
const streamGeneration = yield* SubscriptionRef.make(0);
111117
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
112118
target: QUERY_ENVIRONMENT,
@@ -320,6 +326,82 @@ describe("environmentRpcKey", () => {
320326
});
321327
});
322328

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+
323405
describe("finite environment subscription lifecycle", () => {
324406
it.effect(
325407
"exposes early values and settles on the terminal value without waiting for a reconnect",

0 commit comments

Comments
 (0)