Skip to content

Commit 78abcda

Browse files
fix: each OS link gets its own thread, and none is lost to a reload
- New-thread requests accept fresh, which never reuses an empty draft. The link handler uses it, so two links opened before typing get two threads. A draft with an open page also survives being displaced, since its composer is empty but the page is the work. - Link delivery is tied to the page that said it is listening. Starting a new page or losing the renderer ends it, so links that arrive during a reload wait for the new page instead of being sent to nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 08db5a3 commit 78abcda

7 files changed

Lines changed: 132 additions & 18 deletions

File tree

‎apps/desktop/src/app/DesktopWebLinks.test.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron webContents.
12
import { assert, describe, it } from "@effect/vitest";
3+
import * as NodeEvents from "node:events";
24
import * as Effect from "effect/Effect";
35
import * as Layer from "effect/Layer";
46
import * as Option from "effect/Option";
@@ -10,14 +12,16 @@ import * as DesktopWebLinks from "./DesktopWebLinks.ts";
1012
const makeWindow = () => {
1113
const sent: Array<string> = [];
1214
const revealed: Array<unknown> = [];
13-
const window = {
14-
webContents: {
15-
isDestroyed: () => false,
16-
send: (channel: string, url: string) => {
17-
if (channel === WEB_LINK_OPEN_CHANNEL) sent.push(url);
18-
},
15+
const webContents = Object.assign(new NodeEvents.EventEmitter(), {
16+
isDestroyed: () => false,
17+
send: (channel: string, url: string) => {
18+
if (channel === WEB_LINK_OPEN_CHANNEL) sent.push(url);
1919
},
20-
} as unknown as Electron.BrowserWindow;
20+
});
21+
const window = { webContents } as unknown as Electron.BrowserWindow;
22+
/** The web app starts loading a new page, as a reload does. */
23+
const reload = () =>
24+
webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false });
2125
const layer = DesktopWebLinks.layer.pipe(
2226
Layer.provide(
2327
Layer.succeed(
@@ -29,7 +33,7 @@ const makeWindow = () => {
2933
),
3034
),
3135
);
32-
return { sent, revealed, layer };
36+
return { sent, revealed, layer, reload };
3337
};
3438

3539
describe("DesktopWebLinks", () => {
@@ -63,4 +67,19 @@ describe("DesktopWebLinks", () => {
6367
assert.strictEqual(sent.length, 3);
6468
}).pipe(Effect.provide(layer));
6569
});
70+
71+
it.effect("holds links that arrive while the web app reloads until it listens again", () => {
72+
const { sent, layer, reload } = makeWindow();
73+
return Effect.gen(function* () {
74+
const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
75+
yield* webLinks.setRendererReady(true);
76+
// The old page never says it stopped; the reload itself ends its listening.
77+
reload();
78+
yield* webLinks.receive("https://example.com/during-reload");
79+
assert.deepStrictEqual(sent, []);
80+
81+
yield* webLinks.setRendererReady(true);
82+
assert.deepStrictEqual(sent, ["https://example.com/during-reload"]);
83+
}).pipe(Effect.provide(layer));
84+
});
6685
});

‎apps/desktop/src/app/DesktopWebLinks.ts‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,29 +31,62 @@ export class DesktopWebLinks extends Context.Service<
3131
const make = Effect.gen(function* () {
3232
const electronWindow = yield* ElectronWindow.ElectronWindow;
3333
const pending: Array<string> = [];
34-
let rendererReady = false;
34+
/** The page that said it is listening; a reload or crash replaces it, and it must say so again. */
35+
let listening: Electron.WebContents | null = null;
36+
let detachListening: (() => void) | null = null;
37+
38+
const stopListening = () => {
39+
detachListening?.();
40+
detachListening = null;
41+
listening = null;
42+
};
3543

3644
const flush = Effect.gen(function* () {
37-
if (!rendererReady || pending.length === 0) return;
45+
if (listening === null || pending.length === 0) return;
3846
const window = yield* electronWindow.currentMainOrFirst;
39-
if (Option.isNone(window) || window.value.webContents.isDestroyed()) return;
40-
for (const url of pending.splice(0)) {
41-
window.value.webContents.send(WEB_LINK_OPEN_CHANNEL, url);
47+
if (Option.isNone(window) || window.value.webContents !== listening) return;
48+
if (listening.isDestroyed()) {
49+
stopListening();
50+
return;
4251
}
52+
for (const url of pending.splice(0)) listening.send(WEB_LINK_OPEN_CHANNEL, url);
4353
yield* electronWindow.reveal(window.value);
4454
});
4555

56+
const startListening = Effect.gen(function* () {
57+
const window = yield* electronWindow.currentMainOrFirst;
58+
if (Option.isNone(window) || window.value.webContents.isDestroyed()) return;
59+
const webContents = window.value.webContents;
60+
if (listening === webContents) return;
61+
stopListening();
62+
listening = webContents;
63+
// Links that arrive while a new page loads wait for it to listen again.
64+
const onNavigation = (
65+
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
66+
) => {
67+
if (event.isMainFrame && !event.isSameDocument) stopListening();
68+
};
69+
webContents.on("did-start-navigation", onNavigation);
70+
webContents.on("render-process-gone", stopListening);
71+
webContents.once("destroyed", stopListening);
72+
detachListening = () => {
73+
webContents.removeListener("did-start-navigation", onNavigation);
74+
webContents.removeListener("render-process-gone", stopListening);
75+
webContents.removeListener("destroyed", stopListening);
76+
};
77+
});
78+
4679
return DesktopWebLinks.of({
4780
receive: (url) =>
4881
Effect.suspend(() => {
4982
pending.push(url);
5083
return flush;
5184
}).pipe(Effect.withSpan("DesktopWebLinks.receive")),
5285
setRendererReady: (ready) =>
53-
Effect.suspend(() => {
54-
rendererReady = ready;
55-
return flush;
56-
}).pipe(Effect.withSpan("DesktopWebLinks.setRendererReady")),
86+
(ready ? startListening : Effect.sync(stopListening)).pipe(
87+
Effect.andThen(flush),
88+
Effect.withSpan("DesktopWebLinks.setRendererReady"),
89+
),
5790
});
5891
});
5992

‎apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ export function DesktopWebLinkCoordinator() {
3232
if (environmentId === null) return;
3333
const project = await openScratchProject(environmentId, "Could not open the link");
3434
if (!project) return;
35-
const opened = await openThread(scopeProjectRef(project.environmentId, project.id));
35+
// Each link is its own thread, even before the user types in the last one.
36+
const opened = await openThread(scopeProjectRef(project.environmentId, project.id), {
37+
fresh: true,
38+
});
3639
if (!opened) return;
3740
const threadRef = scopeThreadRef(project.environmentId, opened.threadId);
3841
useRightPanelStore.getState().requestMaximize(threadRef);

‎apps/web/src/composerDraftStore.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ import {
8989
type TerminalContextDraft,
9090
} from "./lib/terminalContext";
9191
import { createDeferredStorage } from "./lib/storage";
92+
import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "./previewStateStore";
9293

9394
function makeImage(input: {
9495
id: string;
@@ -1467,6 +1468,27 @@ describe("composerDraftStore project draft thread mapping", () => {
14671468
expect(draftByKey(draftId)).toBeUndefined();
14681469
});
14691470

1471+
it("keeps a draft with an open page when remapping a project to a new draft thread", () => {
1472+
const store = useComposerDraftStore.getState();
1473+
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
1474+
// A link another app opened: the composer is empty, but the page is not.
1475+
applyPreviewServerSnapshot(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId), {
1476+
threadId,
1477+
tabId: "tab-link",
1478+
navStatus: { _tag: "Success", url: "https://example.com/", title: "Example" },
1479+
canGoBack: false,
1480+
canGoForward: false,
1481+
updatedAt: "2026-10-09T00:00:00.000Z",
1482+
});
1483+
try {
1484+
store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId });
1485+
1486+
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.threadId).toBe(threadId);
1487+
} finally {
1488+
resetPreviewStateForTests();
1489+
}
1490+
});
1491+
14701492
it("keeps invested composer drafts alive unmapped when remapping a project to a new draft thread", () => {
14711493
const store = useComposerDraftStore.getState();
14721494
store.setProjectDraftThreadId(projectRef, draftId, { threadId });

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { DeepMutable } from "effect/Types";
4040
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
4141
import { useMemo } from "react";
4242
import { getLocalStorageItem } from "./hooks/useLocalStorage";
43+
import { readThreadPreviewState } from "./previewStateStore";
4344
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
4445
import {
4546
DEFAULT_INTERACTION_MODE,
@@ -1556,6 +1557,10 @@ function getComposerDraftState(
15561557
return state.draftsByThreadKey[threadKey] ?? null;
15571558
}
15581559

1560+
function draftThreadHasOpenPreview(ref: ScopedThreadRef): boolean {
1561+
return Object.keys(readThreadPreviewState(ref).sessions).length > 0;
1562+
}
1563+
15591564
function isComposerThreadKeyInUse(mappings: Record<string, string>, threadKey: string): boolean {
15601565
return Object.values(mappings).includes(threadKey);
15611566
}
@@ -2792,6 +2797,14 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
27922797
!isDraftThreadPromoting(previousDraftThread) &&
27932798
!composerDraftHasUserContent(
27942799
state.draftsByThreadKey[previousThreadKeyForLogicalProject],
2800+
) &&
2801+
// A draft holding an open page, such as one started for a link
2802+
// another app opened, is work in progress even with an empty composer.
2803+
!(
2804+
previousDraftThread !== undefined &&
2805+
draftThreadHasOpenPreview(
2806+
scopeThreadRef(previousDraftThread.environmentId, previousDraftThread.threadId),
2807+
)
27952808
)
27962809
) {
27972810
delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];

‎apps/web/src/hooks/useHandleNewThread.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,3 +287,18 @@ describe.each([
287287
},
288288
);
289289
});
290+
291+
it("starts a new draft for fresh requests even when an empty one could be reused", async () => {
292+
testState.reset({
293+
draftId: "draft-existing",
294+
environmentId: "environment-ssh",
295+
promotedTo: null,
296+
threadId: "thread-existing",
297+
});
298+
const projectRef = { environmentId: "environment-ssh", projectId: "project-remote" } as never;
299+
const pendingOpen = useNewThreadHandler()(projectRef, { fresh: true });
300+
testState.completeProjectFileRead(null);
301+
302+
// A page another app opened is its own thread, not the one the last page took.
303+
expect(await pendingOpen).toEqual({ draftId: "draft-delayed", threadId: "thread-delayed" });
304+
});

‎apps/web/src/hooks/useHandleNewThread.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ export function useNewThreadHandler() {
7272
envMode?: DraftThreadEnvMode;
7373
startFromOrigin?: boolean;
7474
replace?: boolean;
75+
/**
76+
* Always start a new draft, even when the project has an empty one to
77+
* reuse. For work that is not typed into the composer, such as a page
78+
* opened from another app, which would otherwise land in the same draft.
79+
*/
80+
fresh?: boolean;
7581
},
7682
// Which draft the thread ended up in, so a caller that has something to put in it — a
7783
// prepared checkout, a task to write — addresses that one rather than looking the project
@@ -189,6 +195,7 @@ export function useNewThreadHandler() {
189195
// fresh draft instead — the remap in the store preserves invested
190196
// drafts rather than deleting them.
191197
const emptyStoredDraftThread =
198+
!options?.fresh &&
192199
reusableStoredDraftThread &&
193200
!composerDraftHasUserContent(getComposerDraft(reusableStoredDraftThread.draftId))
194201
? reusableStoredDraftThread
@@ -327,6 +334,7 @@ export function useNewThreadHandler() {
327334
}
328335

329336
if (
337+
!options?.fresh &&
330338
latestActiveDraftThread &&
331339
currentRouteTarget?.kind === "draft" &&
332340
latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
@@ -370,6 +378,7 @@ export function useNewThreadHandler() {
370378
// reuse the winner instead, like the synchronous path above does.
371379
const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
372380
if (
381+
!options?.fresh &&
373382
racedDraft &&
374383
// Only a draft REGISTERED during the await counts as a raced
375384
// winner. An invested draft this invocation deliberately declined

0 commit comments

Comments
 (0)