diff --git a/README.md b/README.md index 11d2ffb3778dd..59a5ce92e670a 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ This is a personal fork of [pingdotgg/t3code](https://github.com/pingdotgg/t3cod - **Agent-requested worktree switches.** After creating a worktree, a Codex agent can call `switch_worktree` (Claude follows worktrees on its own; see Worktree-following Claude sessions). T3 waits for the turn, its final checkpoint, any subagents, and any commands or monitors the agent waits on, then moves the thread's checkout; your next message continues the same conversation there. Agents inspect or cancel a pending move with `worktree_switch_status` and `cancel_worktree_switch`, and return to the project checkout with the same switch tool. A new message, archiving, or a failed turn cancels it. -- **Open threads from links.** The desktop app opens `t3code://app//` links (`t3code-dev://` for Dev builds) from other apps and from pages in the built-in browser, whether it is already running or starts from the link. Use `primary` as the environment ID for the desktop's own environment. When tag hiding is off, archived threads open too, with an archived notice and an Unarchive button above the composer. A link to an unknown environment or thread shows a short error instead. Upstream's prompt links (`t3code://new`, `t3code://threads/…`) follow the same rules: each build answers only its own scheme, and a thread link opens in the active split pane. +- **Open threads from links.** The desktop app opens `t3code://app//` links (`t3code-dev://` for Dev builds) from other apps and from pages in the built-in browser, whether it is already running or starts from the link. Use `primary` as the environment ID for the desktop's own environment. When tag hiding is off, archived threads open too, with an archived notice and an Unarchive button above the composer. A link to an unknown environment or thread shows a short error instead. Upstream's links (`t3code://new`, `t3code://threads/…`) follow the same rules: each build answers only its own scheme, and a thread link gets the same checks and opens in the active split pane. - **Archive when done.** Archiving a working thread, from its menu, the command palette, the archive shortcut, mobile, or the `/t3-archive` composer command, waits until the turn, its checkpoint, any subagents, and any commands or monitors the agent waits on finish. Automatic follow-ups such as subagent results don't cancel it; a new message does. A pending archive shows an archive icon on the thread's row, and the same actions cancel it. Archiving an idle thread that has queued messages, including messages held by Stop, always asks first and names the count, even with archive confirmation off; confirming archives it now and discards them. Agents can archive their own thread, or pass `threadId` to archive another one they have read and no longer need, with `archive_thread` (inspected or cancelled with `archive_thread_status` and `cancel_thread_archive`), optionally removing its clean worktree while keeping the branch (never an SP Labs lab). Requests survive restarts. Like a manual archive, it also archives the thread's side chats, and sending a message to an archived thread unarchives it and those side chats first. Agents can use `archive_thread` with `includeDescendants: true` to archive finished child and subagent threads in the same call; active descendants are skipped and reported. Shared-worktree refusals report the blocker count and up to ten thread ids, titles, and states. diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 07fc03cc3b69e..049fd86986497 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -67,7 +67,6 @@ import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "../ssh/DesktopSshPasswordPrompts.ts"; import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts"; import * as DesktopWebLinks from "./DesktopWebLinks.ts"; -import * as DesktopThreadLinks from "./DesktopThreadLinks.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; @@ -141,6 +140,7 @@ const runStubbedDesktop = (stub: StubbedDesktop) => }), Effect.provideService(DesktopClerk.DesktopClerk, { configure: Effect.void, + openThreadLink: () => false, } as DesktopClerk.DesktopClerk["Service"]), Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { selectedStorageBackend: Effect.succeedNone, @@ -234,7 +234,6 @@ const runStubbedDesktop = (stub: StubbedDesktop) => Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopThreadLinks.DesktopThreadLinks, { start: Effect.void }), Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), Layer.mock(ElectronMenu.ElectronMenu, {}), Layer.mock(ElectronShell.ElectronShell, {}), diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 53b5cb58a8e60..9f51b98418e21 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -17,7 +17,6 @@ import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; -import * as DesktopThreadLinks from "./DesktopThreadLinks.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; @@ -338,7 +337,6 @@ const startup = Effect.gen(function* () { const electronApp = yield* ElectronApp.ElectronApp; const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler; - const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks; const clerk = yield* DesktopClerk.DesktopClerk; const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; @@ -428,8 +426,6 @@ const startup = Effect.gen(function* () { yield* bootstrap(backendStarted).pipe( Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)), ); - // After bootstrap so revealing a linked thread never races the first window. - yield* threadLinks.start; }).pipe(Effect.withSpan("desktop.startup")); const scopedProgram = Effect.scoped( diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts index 301be42e5fc76..04ffe5a78954a 100644 --- a/apps/desktop/src/app/DesktopClerk.test.ts +++ b/apps/desktop/src/app/DesktopClerk.test.ts @@ -237,13 +237,24 @@ describe("DesktopClerk", () => { listeners.get("second-instance")?.({}, ["t3", first]); listeners.get("second-instance")?.({}, ["t3", second]); listeners.get("open-url")?.({ preventDefault: () => undefined }, launchPair); + // Fork: a macOS cold start hands the documented `app/` thread link to open-url. + listeners.get("open-url")?.( + { preventDefault: () => undefined }, + "t3code-dev://app/primary/t", + ); assert.deepEqual(received, []); yield* clerk.configure; listeners.get("second-instance")!({}, ["t3", later]); yield* Effect.promise(() => delivered.promise); - assert.deepEqual(received, [launchPair, first, second, later]); + assert.deepEqual(received, [ + launchPair, + "t3code-dev://threads/primary/t", + first, + second, + later, + ]); }).pipe( Effect.scoped, Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)), @@ -445,6 +456,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone" const pairLink = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc"; yield* Effect.gen(function* () { const clerk = yield* DesktopClerk.DesktopClerk; + assert.isFalse(clerk.openThreadLink("t3code-dev://app/primary/thread-3")); yield* clerk.configure; const open = (url: string) => { const event = { preventDefault: vi.fn() }; @@ -461,6 +473,13 @@ it.effect("hands web and app links to the renderer and leaves other links alone" assert.strictEqual(open("t3code://pair"), 0); assert.strictEqual(open("mailto:hello@example.com"), 0); assert.strictEqual(open("t3code-dev://somewhere-else"), 0); + // Fork: the documented `app/` thread link, for this build only, also from previewed pages. + assert.strictEqual(open("t3code-dev://app/env-1/thread-2"), 1); + assert.strictEqual(open("t3code://app/env-1/thread-2"), 0); + assert.isTrue(clerk.openThreadLink("t3code-dev://app/primary/thread-3")); + assert.isFalse(clerk.openThreadLink("t3code-dev://threads/env-1/thread-1")); + assert.isFalse(clerk.openThreadLink("t3code://app/env-1/thread-2")); + assert.isFalse(clerk.openThreadLink("https://example.com/page")); yield* Effect.yieldNow; assert.deepStrictEqual(received, [ "https://example.com/page", @@ -468,6 +487,8 @@ it.effect("hands web and app links to the renderer and leaves other links alone" "t3code-dev://new?prompt=hi", "t3code-dev://threads/env-1/thread-1", pairLink, + "t3code-dev://threads/env-1/thread-2", + "t3code-dev://threads/primary/thread-3", ]); }).pipe( Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)), diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts index d2b07044bd33f..bfa5ae4d74eff 100644 --- a/apps/desktop/src/app/DesktopClerk.ts +++ b/apps/desktop/src/app/DesktopClerk.ts @@ -21,6 +21,7 @@ import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as DesktopUserData from "./DesktopUserData.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import * as DesktopThreadLinks from "./DesktopThreadLinks.ts"; import { openClerkTokenStorage } from "./ClerkTokenStore.ts"; import * as DesktopWebLinks from "./DesktopWebLinks.ts"; @@ -63,6 +64,8 @@ export class DesktopClerk extends Context.Service< | DesktopWebLinks.DesktopWebLinks | Scope.Scope >; + /** Fork: opens this build's `app/` thread link from a previewed page; false before configure. */ + readonly openThreadLink: (url: string) => boolean; } >()("@t3tools/desktop/app/DesktopClerk") {} @@ -138,6 +141,8 @@ export const make = Effect.gen(function* () { yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => { if (handleOpenUrl(url)) event.preventDefault(); }); + const scheme = ElectronProtocol.getDesktopScheme(environment.usesDevelopmentIdentity); + let openThreadLink = (_url: string) => false; yield* Effect.acquireRelease( Effect.try({ @@ -204,7 +209,6 @@ export const make = Effect.gen(function* () { }; const resumeProviderAuth = (value: string | undefined) => { const destination = providerAuthReturnUrl(value); - const scheme = ElectronProtocol.getDesktopScheme(environment.usesDevelopmentIdentity); if (!destination?.startsWith(`${scheme}://app/`)) return false; void runPromise( Effect.gen(function* () { @@ -220,13 +224,14 @@ export const make = Effect.gen(function* () { ); return true; }; - const openAppLink = (value: string | undefined) => { - if (!value) return false; + const openAppLink = (link: string | undefined) => { + if (!link) return false; + // Fork: the documented `app//` form rides upstream's thread links. + const value = DesktopThreadLinks.appThreadLinkAsThreadsLink(link, scheme) ?? link; const promptLink = promptLinkAppPath(value) !== null; if (!promptLink && readPairingAppLink(value) === null) return false; // Fork: prompt and thread links open only in this build's scheme (t3code:// vs // t3code-dev://); pairing links are scheme-agnostic upstream. - const scheme = ElectronProtocol.getDesktopScheme(environment.usesDevelopmentIdentity); if ( promptLink && /^t3code(?:-[a-z]+)?:/i.test(value) && @@ -237,6 +242,8 @@ export const make = Effect.gen(function* () { void runPromise(webLinks.receive(value)); return true; }; + openThreadLink = (url) => + DesktopThreadLinks.appThreadLinkAsThreadsLink(url, scheme) !== null && openAppLink(url); const args = yield* HostProcess.Arguments; args.some((value) => startProviderAuthHandoff(value) || openAppLink(value)); const openWebLink = (url: string) => { @@ -272,6 +279,7 @@ export const make = Effect.gen(function* () { }; for (const argv of pendingSecondInstances.splice(0)) handleSecondInstance(argv); }).pipe(Effect.withSpan("desktop.clerk.configure")), + openThreadLink: (url) => openThreadLink(url), }); }); diff --git a/apps/desktop/src/app/DesktopThreadLinks.test.ts b/apps/desktop/src/app/DesktopThreadLinks.test.ts index 682bf2f159978..71280c40f186f 100644 --- a/apps/desktop/src/app/DesktopThreadLinks.test.ts +++ b/apps/desktop/src/app/DesktopThreadLinks.test.ts @@ -1,47 +1,32 @@ -// @effect-diagnostics nodeBuiltinImport:off -- A Node EventEmitter stands in for Electron's app events. -import * as NodeEvents from "node:events"; - -import type { DesktopThreadLink } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import { vi } from "vite-plus/test"; -import * as ElectronWindow from "../electron/ElectronWindow.ts"; -import { DESKTOP_THREAD_LINK_OPEN_CHANNEL } from "../ipc/channels.ts"; -import * as DesktopWindow from "../window/DesktopWindow.ts"; -import * as DesktopEnvironment from "./DesktopEnvironment.ts"; -import { DesktopThreadLinkReceiver } from "./DesktopThreadLinkReceiver.ts"; import * as DesktopThreadLinks from "./DesktopThreadLinks.ts"; const THREAD_ID = "8f0e2a4c-7a1b-4c3d-9e5f-0123456789ab"; const DEV_LINK = `t3code-dev://app/primary/${THREAD_ID}`; +const rewrite = DesktopThreadLinks.appThreadLinkAsThreadsLink; -function openUrl(app: NodeEvents.EventEmitter, url: string) { - const preventDefault = vi.fn(); - app.emit("open-url", { preventDefault }, url); - return preventDefault; -} - -describe("parseDesktopThreadLink", () => { - it("accepts exactly // on the app host", () => { - assert.deepEqual(DesktopThreadLinks.parseDesktopThreadLink(DEV_LINK, "t3code-dev"), { - environmentId: "primary", - threadId: THREAD_ID, - }); - assert.deepEqual( - DesktopThreadLinks.parseDesktopThreadLink("t3code://app/env-1/thread-1", "t3code"), - { environmentId: "env-1", threadId: "thread-1" }, +describe("appThreadLinkAsThreadsLink", () => { + it("rewrites exactly // on the app host", () => { + assert.strictEqual( + rewrite(DEV_LINK, "t3code-dev"), + `t3code-dev://threads/primary/${THREAD_ID}`, + ); + assert.strictEqual( + rewrite("t3code://app/env-1/thread-1", "t3code"), + "t3code://threads/env-1/thread-1", ); }); it("accepts imported thread ids, literal or percent-encoded", () => { - const expected = { environmentId: "primary", threadId: "import:codex:0199-abc" }; for (const url of [ "t3code-dev://app/primary/import:codex:0199-abc", "t3code-dev://app/primary/import%3Acodex%3A0199-abc", ]) { - assert.deepEqual(DesktopThreadLinks.parseDesktopThreadLink(url, "t3code-dev"), expected); + assert.strictEqual( + rewrite(url, "t3code-dev"), + "t3code-dev://threads/primary/import%3Acodex%3A0199-abc", + ); } }); @@ -69,200 +54,7 @@ describe("parseDesktopThreadLink", () => { `https://app/primary/${THREAD_ID}`, "not a url", ]) { - assert.isNull(DesktopThreadLinks.parseDesktopThreadLink(url, "t3code-dev"), url); + assert.isNull(rewrite(url, "t3code-dev"), url); } }); }); - -describe("DesktopThreadLinkInbox", () => { - it("holds a cold-start open-url until attached and leaves OAuth callbacks alone", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, ["/Applications/T3 Code"]); - - const oauthPreventDefault = openUrl(app, "t3code-dev://app/?code=abc"); - const linkPreventDefault = openUrl(app, DEV_LINK); - assert.strictEqual(oauthPreventDefault.mock.calls.length, 0); - assert.strictEqual(linkPreventDefault.mock.calls.length, 1); - - const delivered: string[] = []; - inbox.attach((url) => delivered.push(url)); - assert.deepEqual(delivered, [DEV_LINK]); - - openUrl(app, "t3code-dev://app/env-2/thread-2"); - assert.deepEqual(delivered, [DEV_LINK, "t3code-dev://app/env-2/thread-2"]); - }); - - it("delivers every link received before attaching, in order", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, []); - openUrl(app, "t3code-dev://app/env-1/thread-1"); - openUrl(app, DEV_LINK); - - const delivered: string[] = []; - inbox.attach((url) => delivered.push(url)); - assert.deepEqual(delivered, ["t3code-dev://app/env-1/thread-1", DEV_LINK]); - }); - - it("reads the first-launch argv and second-instance argv", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, [ - "/opt/T3 Code/t3code", - "--no-sandbox", - DEV_LINK, - ]); - const delivered: string[] = []; - inbox.attach((url) => delivered.push(url)); - assert.deepEqual(delivered, [DEV_LINK]); - - app.emit("second-instance", {}, ["/opt/T3 Code/t3code", "t3code-dev://app/env-2/thread-2"]); - app.emit("second-instance", {}, ["/opt/T3 Code/t3code", "t3code-dev://app/?code=abc"]); - app.emit("second-instance", {}, ["/opt/T3 Code/t3code"]); - assert.deepEqual(delivered, [DEV_LINK, "t3code-dev://app/env-2/thread-2"]); - }); -}); - -describe("receiverLayer", () => { - it.effect("takes only this build's thread links", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, []); - const layer = DesktopThreadLinks.receiverLayer(inbox).pipe( - Layer.provide( - Layer.succeed(DesktopEnvironment.DesktopEnvironment, { - usesDevelopmentIdentity: true, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - ), - ); - - return Effect.gen(function* () { - const receiver = yield* DesktopThreadLinkReceiver; - assert.isTrue(receiver.receive(DEV_LINK)); - assert.isFalse(receiver.receive("t3code://app/env-1/thread-1")); - assert.isFalse(receiver.receive("t3code-dev://app/?code=abc")); - assert.isFalse(receiver.receive("https://example.com/")); - - const delivered: string[] = []; - inbox.attach((url) => delivered.push(url)); - assert.deepEqual(delivered, [DEV_LINK]); - }).pipe(Effect.provide(layer)); - }); -}); - -describe("DesktopThreadLinkQueue", () => { - it("sends the latest link once a renderer is ready", () => { - const queue = new DesktopThreadLinks.DesktopThreadLinkQueue(); - const sent: DesktopThreadLink[] = []; - queue.enqueue({ environmentId: "env-1", threadId: "thread-1" }); - queue.enqueue({ environmentId: "env-2", threadId: "thread-2" }); - queue.setRenderer((link) => sent.push(link)); - queue.enqueue({ environmentId: "env-3", threadId: "thread-3" }); - assert.deepEqual(sent, [ - { environmentId: "env-2", threadId: "thread-2" }, - { environmentId: "env-3", threadId: "thread-3" }, - ]); - }); - - it("keeps a link whose send failed for the next renderer", () => { - const queue = new DesktopThreadLinks.DesktopThreadLinkQueue(); - queue.setRenderer(() => { - throw new Error("renderer gone"); - }); - queue.enqueue({ environmentId: "env-1", threadId: "thread-1" }); - const sent: DesktopThreadLink[] = []; - queue.setRenderer((link) => sent.push(link)); - assert.deepEqual(sent, [{ environmentId: "env-1", threadId: "thread-1" }]); - }); -}); - -describe("DesktopThreadLinks", () => { - it.effect("reveals the window and navigates the renderer once it is ready", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, []); - const webContents = Object.assign(new NodeEvents.EventEmitter(), { - isDestroyed: () => false, - send: vi.fn(), - }); - const activate = vi.fn(); - const layer = DesktopThreadLinks.layer(inbox).pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(DesktopEnvironment.DesktopEnvironment, { - usesDevelopmentIdentity: true, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Layer.succeed(DesktopWindow.DesktopWindow, { - activate: Effect.sync(activate), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents }), - } as unknown as ElectronWindow.ElectronWindow["Service"]), - ), - ), - ); - - return Effect.gen(function* () { - const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks; - // macOS cold start: the link lands before the service starts. - openUrl(app, DEV_LINK); - // A production-scheme link is not this build's. - openUrl(app, "t3code://app/env-1/thread-1"); - yield* threadLinks.start; - yield* Effect.yieldNow; - assert.strictEqual(activate.mock.calls.length, 1); - assert.strictEqual(webContents.send.mock.calls.length, 0); - - yield* threadLinks.setRendererReady(true); - assert.deepEqual(webContents.send.mock.calls, [ - [DESKTOP_THREAD_LINK_OPEN_CHANNEL, { environmentId: "primary", threadId: THREAD_ID }], - ]); - - // A reload or crash drops the renderer; the next link waits for it to be ready again. - for (const [event, payload] of [ - ["did-start-navigation", { isMainFrame: true, isSameDocument: false }], - ["render-process-gone", { reason: "crashed" }], - ] as const) { - const sentBefore = webContents.send.mock.calls.length; - webContents.emit(event, payload); - app.emit("second-instance", {}, ["t3code", `t3code-dev://app/env-2/${event}`]); - assert.strictEqual(webContents.send.mock.calls.length, sentBefore); - yield* threadLinks.setRendererReady(true); - assert.deepEqual(webContents.send.mock.calls[sentBefore], [ - DESKTOP_THREAD_LINK_OPEN_CHANNEL, - { environmentId: "env-2", threadId: event }, - ]); - } - }).pipe(Effect.scoped, Effect.provide(layer)); - }); - - it.effect("reveals the window once while an activation is still running", () => { - const app = new NodeEvents.EventEmitter(); - const inbox = new DesktopThreadLinks.DesktopThreadLinkInbox(app, []); - const activate = vi.fn(); - const layer = DesktopThreadLinks.layer(inbox).pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(DesktopEnvironment.DesktopEnvironment, { - usesDevelopmentIdentity: true, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Layer.succeed(DesktopWindow.DesktopWindow, { - activate: Effect.suspend(() => { - activate(); - return Effect.never; - }), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedNone, - } as unknown as ElectronWindow.ElectronWindow["Service"]), - ), - ), - ); - - return Effect.gen(function* () { - const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks; - yield* threadLinks.start; - openUrl(app, "t3code-dev://app/env-1/thread-1"); - yield* Effect.yieldNow; - openUrl(app, DEV_LINK); - yield* Effect.yieldNow; - assert.strictEqual(activate.mock.calls.length, 1); - }).pipe(Effect.scoped, Effect.provide(layer)); - }); -}); diff --git a/apps/desktop/src/app/DesktopThreadLinks.ts b/apps/desktop/src/app/DesktopThreadLinks.ts index 891ce688b9076..447a4ab578421 100644 --- a/apps/desktop/src/app/DesktopThreadLinks.ts +++ b/apps/desktop/src/app/DesktopThreadLinks.ts @@ -1,27 +1,9 @@ -import type { DesktopThreadLink } from "@t3tools/contracts"; import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Scope from "effect/Scope"; - -import type * as Electron from "electron"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; -import * as ElectronWindow from "../electron/ElectronWindow.ts"; -import { DESKTOP_THREAD_LINK_OPEN_CHANNEL } from "../ipc/channels.ts"; -import * as DesktopWindow from "../window/DesktopWindow.ts"; -import * as DesktopEnvironment from "./DesktopEnvironment.ts"; -import { makeComponentLogger } from "./DesktopObservability.ts"; -import { DesktopThreadLinkReceiver } from "./DesktopThreadLinkReceiver.ts"; // Whitespace, control characters, and path separators cannot be in an id. const INVALID_SEGMENT_CHARACTER = /[\p{C}\s/\\]/u; -const DESKTOP_SCHEMES = [ - ElectronProtocol.getDesktopScheme(false), - ElectronProtocol.getDesktopScheme(true), -]; // Ids are not one charset: imported threads use `import::`. // So each segment is decoded and rejected only for what cannot be an id. @@ -39,11 +21,11 @@ function decodeLinkSegment(segment: string): string | null { } /** - * Parses `://app//`. Everything else is not a - * thread link, including the Clerk OAuth callback at `://app/` and the - * provider sign-in returns under `/settings`, which DesktopClerk routes. + * Fork: rewrites the documented `://app//` form as upstream's + * `://threads/…` link. Everything else is not a thread link, including the Clerk OAuth + * callback at `://app/` and the provider sign-in returns under `/settings`. */ -export function parseDesktopThreadLink(rawUrl: string, scheme: string): DesktopThreadLink | null { +export function appThreadLinkAsThreadsLink(rawUrl: string, scheme: string): string | null { let url: URL; try { url = new URL(rawUrl); @@ -60,202 +42,5 @@ export function parseDesktopThreadLink(rawUrl: string, scheme: string): DesktopT const environmentId = rawEnvironmentId === undefined ? null : decodeLinkSegment(rawEnvironmentId); const threadId = rawThreadId === undefined ? null : decodeLinkSegment(rawThreadId); if (environmentId === null || threadId === null) return null; - return { environmentId, threadId }; -} - -const isThreadLinkCandidate = (url: string) => - DESKTOP_SCHEMES.some((scheme) => parseDesktopThreadLink(url, scheme) !== null); - -/** The last argument that looks like a thread link for either desktop scheme. */ -function findThreadLinkArgument(argv: ReadonlyArray): string | null { - for (let index = argv.length - 1; index >= 0; index -= 1) { - const argument = argv[index]; - if (typeof argument === "string" && isThreadLinkCandidate(argument)) return argument; - } - return null; -} - -/** - * Receives thread links from the OS before the Effect runtime is up. A macOS - * cold start delivers the link as `open-url` right after launch, often while - * layers are still building, so main.ts creates this synchronously. Links wait - * here until the service attaches. - */ -export class DesktopThreadLinkInbox { - readonly #pending: string[] = []; - #deliver: ((url: string) => void) | null = null; - - constructor(app: NodeJS.EventEmitter, argv: ReadonlyArray) { - // Windows and Linux pass a cold-start link as a launch argument. - const launchUrl = findThreadLinkArgument(argv); - if (launchUrl !== null) this.#pending.push(launchUrl); - app.on("open-url", (event: Electron.Event, url: unknown) => { - if (typeof url !== "string" || !isThreadLinkCandidate(url)) return; - event.preventDefault(); - this.#receive(url); - }); - // Windows and Linux route a link for the running app through the argv of - // the second instance, which Clerk's single-instance lock then quits. - app.on("second-instance", (_event: Electron.Event, argv: unknown) => { - const url = Array.isArray(argv) ? findThreadLinkArgument(argv) : null; - if (url !== null) this.#receive(url); - }); - } - - /** Takes a link the app found itself, such as one clicked in the preview browser. */ - receive(url: string): void { - this.#receive(url); - } - - attach(deliver: (url: string) => void): () => void { - this.#deliver = deliver; - for (const url of this.#pending.splice(0)) deliver(url); - return () => { - if (this.#deliver === deliver) this.#deliver = null; - }; - } - - #receive(url: string): void { - if (this.#deliver === null) { - this.#pending.push(url); - return; - } - this.#deliver(url); - } + return `${scheme}://threads/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`; } - -/** Holds the latest link until a renderer can navigate; a newer link replaces an unsent one. */ -export class DesktopThreadLinkQueue { - #pending: DesktopThreadLink | null = null; - #send: ((link: DesktopThreadLink) => void) | null = null; - - enqueue(link: DesktopThreadLink): void { - this.#pending = link; - this.#flush(); - } - - setRenderer(send: ((link: DesktopThreadLink) => void) | null): void { - this.#send = send; - this.#flush(); - } - - #flush(): void { - const link = this.#pending; - const send = this.#send; - if (link === null || send === null) return; - this.#pending = null; - try { - send(link); - } catch { - this.#pending = link; - this.#send = null; - } - } -} - -export class DesktopThreadLinks extends Context.Service< - DesktopThreadLinks, - { - /** Delivers buffered and future links. Run once the main window can be revealed. */ - readonly start: Effect.Effect; - readonly setRendererReady: (ready: boolean) => Effect.Effect; - } ->()("@t3tools/desktop/app/DesktopThreadLinks") {} - -const { logInfo, logWarning } = makeComponentLogger("desktop-thread-links"); - -/** @public */ -export const make = Effect.fn("DesktopThreadLinks.make")(function* (inbox: DesktopThreadLinkInbox) { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const desktopWindow = yield* DesktopWindow.DesktopWindow; - const electronWindow = yield* ElectronWindow.ElectronWindow; - const runPromise = Effect.runPromiseWith(yield* Effect.context()); - const scheme = ElectronProtocol.getDesktopScheme(environment.usesDevelopmentIdentity); - const queue = new DesktopThreadLinkQueue(); - let detachRenderer: (() => void) | null = null; - // Concurrent activations can each find no window and create one. - let revealing = false; - - const clearRenderer = () => { - detachRenderer?.(); - detachRenderer = null; - queue.setRenderer(null); - }; - - const deliver = (url: string) => { - const link = parseDesktopThreadLink(url, scheme); - if (link === null) return; - queue.enqueue(link); - if (revealing) return; - revealing = true; - void runPromise( - logInfo("opening thread link", { ...link }).pipe( - Effect.andThen(desktopWindow.activate), - Effect.catchCause((cause) => - logWarning("failed to reveal the window for a thread link", { cause }), - ), - Effect.ensuring( - Effect.sync(() => { - revealing = false; - }), - ), - ), - ); - }; - - return DesktopThreadLinks.of({ - start: Effect.acquireRelease( - Effect.sync(() => inbox.attach(deliver)), - (detach) => - Effect.sync(() => { - detach(); - clearRenderer(); - }), - ).pipe(Effect.asVoid), - setRendererReady: Effect.fn("DesktopThreadLinks.setRendererReady")(function* (ready) { - clearRenderer(); - if (!ready) return; - const main = yield* electronWindow.main; - if (Option.isNone(main)) return; - const webContents = main.value.webContents; - if (webContents.isDestroyed()) return; - - // A reload or crash drops the renderer's listener without a setReady(false). - // A crashed renderer keeps its webContents, and send() to it fails silently. - const onNavigation = ( - event: Electron.Event, - ) => { - if (event.isMainFrame && !event.isSameDocument) clearRenderer(); - }; - webContents.on("did-start-navigation", onNavigation); - webContents.on("render-process-gone", clearRenderer); - webContents.once("destroyed", clearRenderer); - detachRenderer = () => { - webContents.removeListener("did-start-navigation", onNavigation); - webContents.removeListener("render-process-gone", clearRenderer); - webContents.removeListener("destroyed", clearRenderer); - }; - queue.setRenderer((link) => webContents.send(DESKTOP_THREAD_LINK_OPEN_CHANNEL, link)); - }), - }); -}); - -export const layer = (inbox: DesktopThreadLinkInbox) => - Layer.effect(DesktopThreadLinks, make(inbox)); - -/** Accepts only this app's scheme; a link for the other build keeps its normal navigation. */ -export const receiverLayer = (inbox: DesktopThreadLinkInbox) => - Layer.effect( - DesktopThreadLinkReceiver, - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const scheme = ElectronProtocol.getDesktopScheme(environment.usesDevelopmentIdentity); - return DesktopThreadLinkReceiver.of({ - receive: (url) => { - if (parseDesktopThreadLink(url, scheme) === null) return false; - inbox.receive(url); - return true; - }, - }); - }), - ); diff --git a/apps/desktop/src/app/DesktopWebLinks.test.ts b/apps/desktop/src/app/DesktopWebLinks.test.ts index e4259f66fb5e0..d16639a4f6d74 100644 --- a/apps/desktop/src/app/DesktopWebLinks.test.ts +++ b/apps/desktop/src/app/DesktopWebLinks.test.ts @@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeEvents from "node:events"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -19,6 +20,11 @@ const makeWindow = () => { }, }); const window = { webContents } as unknown as Electron.BrowserWindow; + let current = Option.some(window); + const setOpen = (open: boolean) => { + current = open ? Option.some(window) : Option.none(); + if (!open) webContents.emit("destroyed"); + }; const reload = () => webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); const layer = DesktopWebLinks.layer.pipe( @@ -31,13 +37,13 @@ const makeWindow = () => { Layer.succeed( ElectronWindow.ElectronWindow, ElectronWindow.ElectronWindow.of({ - currentMainOrFirst: Effect.succeedSome(window), + currentMainOrFirst: Effect.sync(() => current), reveal: (target: Electron.BrowserWindow) => Effect.sync(() => void revealed.push(target)), } as unknown as ElectronWindow.ElectronWindow["Service"]), ), ), ); - return { sent, revealed, layer, reload }; + return { sent, revealed, layer, reload, setOpen }; }; describe("DesktopWebLinks", () => { @@ -75,4 +81,28 @@ describe("DesktopWebLinks", () => { assert.deepStrictEqual(sent, ["https://example.com/during-reload"]); }).pipe(Effect.provide(layer)); }); + + // Fork: macOS keeps running with every window closed. + it.effect("opens a window for a link after the last one closed, but not during startup", () => { + const { sent, revealed, layer, setOpen } = makeWindow(); + return Effect.gen(function* () { + const webLinks = yield* DesktopWebLinks.DesktopWebLinks; + setOpen(false); + yield* webLinks.receive("https://example.com/cold-start"); + assert.strictEqual(revealed.length, 0); + + setOpen(true); + yield* webLinks.setRendererReady(true); + assert.deepStrictEqual(sent, ["https://example.com/cold-start"]); + + setOpen(false); + yield* webLinks.receive("https://example.com/after-close"); + assert.deepStrictEqual(sent, ["https://example.com/cold-start"]); + assert.strictEqual(revealed.length, 2); + + setOpen(true); + yield* webLinks.setRendererReady(true); + assert.deepStrictEqual(sent.at(-1), "https://example.com/after-close"); + }).pipe(Effect.provide(layer)); + }); }); diff --git a/apps/desktop/src/app/DesktopWebLinks.ts b/apps/desktop/src/app/DesktopWebLinks.ts index c1932c5ce9055..6254f19136dd5 100644 --- a/apps/desktop/src/app/DesktopWebLinks.ts +++ b/apps/desktop/src/app/DesktopWebLinks.ts @@ -29,6 +29,8 @@ const make = Effect.gen(function* () { const pending: Array = []; let listening: Electron.WebContents | null = null; let detachListening: (() => void) | null = null; + // Fork: macOS runs on with every window closed; after startup a link opens a window again. + let rendererStarted = false; const stopListening = () => { detachListening?.(); @@ -37,9 +39,14 @@ const make = Effect.gen(function* () { }; const flush = Effect.gen(function* () { - if (listening === null || pending.length === 0) return; + if (pending.length === 0) return; const window = yield* electronWindow.currentMainOrFirst; - if (Option.isNone(window) || window.value.webContents !== listening) return; + if (Option.isNone(window) && rendererStarted) { + return yield* desktopWindow.activate.pipe(Effect.ignore); + } + if (listening === null || Option.isNone(window) || window.value.webContents !== listening) { + return; + } if (listening.isDestroyed()) { stopListening(); return; @@ -55,6 +62,7 @@ const make = Effect.gen(function* () { if (listening === webContents) return; stopListening(); listening = webContents; + rendererStarted = true; const onNavigation = ( event: Electron.Event, ) => { diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 0fa6ef8fc692c..4eed053fa5698 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -86,7 +86,6 @@ import { completeLegacyLocalStorage, takeLegacyLocalStorage, } from "./methods/legacyLocalStorage.ts"; -import * as ThreadLinksIpc from "./methods/threadLinks.ts"; import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts"; import { getCliCommandState, @@ -103,7 +102,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(AppActivationIpc.setReady); yield* ipc.handle(AppActivationIpc.complete); yield* ipc.handle(WebLinksIpc.setReady); - yield* ipc.handle(ThreadLinksIpc.setReady); yield* ipc.handleSync(takeLegacyLocalStorage); yield* ipc.handle(completeLegacyLocalStorage); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index f41ecb517470d..136f5f1705b54 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -25,8 +25,6 @@ export const SYNC_HTML_FULLSCREEN_CHANNEL = "desktop:sync-html-fullscreen"; export const DESKTOP_APP_ACTIVATION_READY_CHANNEL = "desktop:app-activation-ready"; export const DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL = "desktop:app-activation-complete"; export const DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL = "desktop:app-activation-request"; -export const DESKTOP_THREAD_LINK_READY_CHANNEL = "desktop:thread-link-ready"; -export const DESKTOP_THREAD_LINK_OPEN_CHANNEL = "desktop:thread-link-open"; export const UPDATE_STATE_CHANNEL = "desktop:update-state"; export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel"; diff --git a/apps/desktop/src/ipc/methods/threadLinks.ts b/apps/desktop/src/ipc/methods/threadLinks.ts deleted file mode 100644 index 8717eef7656a1..0000000000000 --- a/apps/desktop/src/ipc/methods/threadLinks.ts +++ /dev/null @@ -1,16 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import * as DesktopThreadLinks from "../../app/DesktopThreadLinks.ts"; -import * as IpcChannels from "../channels.ts"; -import * as DesktopIpc from "../DesktopIpc.ts"; - -export const setReady = DesktopIpc.makeIpcMethod({ - channel: IpcChannels.DESKTOP_THREAD_LINK_READY_CHANNEL, - payload: Schema.Boolean, - result: Schema.Void, - handler: Effect.fn("desktop.ipc.threadLinks.setReady")(function* (ready) { - const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks; - yield* threadLinks.setRendererReady(ready); - }), -}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 112b909174b63..b146a3dee345e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -64,7 +64,7 @@ import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts"; import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts"; import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts"; -import * as DesktopThreadLinks from "./app/DesktopThreadLinks.ts"; +import { DesktopThreadLinkReceiver } from "./app/DesktopThreadLinkReceiver.ts"; import * as DesktopState from "./app/DesktopState.ts"; import * as DesktopLegacyLocalStorage from "./app/DesktopLegacyLocalStorage.ts"; import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts"; @@ -94,10 +94,6 @@ if (process.argv.includes("--version")) { Electron.app.exit(0); } -// Listens synchronously, before the runtime builds any layer, so a macOS -// cold-start `open-url` cannot fire ahead of its listener. -const threadLinkInbox = new DesktopThreadLinks.DesktopThreadLinkInbox(Electron.app, process.argv); - const layerDesktopEnvironment = Layer.unwrap( Effect.gen(function* () { const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe( @@ -183,7 +179,15 @@ const layerDesktopPreview = PreviewManager.layer.pipe( // IPC needs both services on the same BrowserSession. Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))), Layer.provideMerge(BrowserSession.layer), - Layer.provideMerge(DesktopThreadLinks.receiverLayer(threadLinkInbox)), + // Fork: a thread link clicked in a previewed page opens as one from another app. + Layer.provideMerge( + Layer.effect( + DesktopThreadLinkReceiver, + Effect.map(Effect.service(DesktopClerk.DesktopClerk), (clerk) => ({ + receive: clerk.openThreadLink, + })), + ), + ), Layer.provideMerge(PreviewPasskeys.layer), Layer.provideMerge(PreviewDashlane.layer), Layer.provideMerge(layerDesktopFoundation), @@ -201,9 +205,6 @@ const layerDesktopSnapShot = DesktopSnapShot.layer.pipe( const layerDesktopAppActivation = DesktopAppActivation.layer.pipe( Layer.provide(layerDesktopWindow), ); -const layerDesktopThreadLinks = DesktopThreadLinks.layer(threadLinkInbox).pipe( - Layer.provide(layerDesktopWindow), -); const layerDesktopBackend = DesktopBackendPool.layer.pipe( Layer.provideMerge(DesktopAppIdentity.layer), @@ -227,7 +228,6 @@ const layerDesktopApplication = Layer.mergeAll( DesktopLifecycle.layer, layerDesktopAppActivation, DesktopWebLinks.layer, - layerDesktopThreadLinks, DesktopApplicationMenu.layer, DesktopLinuxUrlHandler.layer, DesktopCliCommand.layer, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index d43d35bd141b0..5f103c88969aa 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -388,19 +388,6 @@ contextBridge.exposeInMainWorld("desktopBridge", { }; }, }, - threadLinks: { - setReady: (ready) => ipcRenderer.invoke(IpcChannels.DESKTOP_THREAD_LINK_READY_CHANNEL, ready), - onOpen: (listener) => { - const wrappedListener = (_event: Electron.IpcRendererEvent, link: unknown) => { - if (typeof link !== "object" || link === null) return; - listener(link as Parameters[0]); - }; - ipcRenderer.on(IpcChannels.DESKTOP_THREAD_LINK_OPEN_CHANNEL, wrappedListener); - return () => { - ipcRenderer.removeListener(IpcChannels.DESKTOP_THREAD_LINK_OPEN_CHANNEL, wrappedListener); - }; - }, - }, preview: { setForwardedShortcuts: (shortcuts) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_FORWARDED_SHORTCUTS_CHANNEL, shortcuts), diff --git a/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx deleted file mode 100644 index 1f57b26202c86..0000000000000 --- a/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; -import type { DesktopThreadLink, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; -import { useRouter } from "@tanstack/react-router"; -import { useEffect, useEffectEvent, useRef } from "react"; - -import { environmentCatalog } from "../../connection/catalog"; -import { - type DesktopThreadLinkResolution, - resolveDesktopThreadLink, -} from "../../desktopThreadLink"; -import { appAtomRegistry } from "../../rpc/atomRegistry"; -import { readThreadShell } from "../../state/entities"; -import { archivedSnapshotAtom } from "../../lib/archivedThreadsState"; -import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment"; -import { environmentShell } from "../../state/shell"; -import { buildThreadRouteParams, resolveThreadRouteRef } from "../../threadRoutes"; -import { openThreadInActivePane } from "../thread-split/threadOpenTarget"; -import { toastManager } from "../ui/toast"; - -// Generous enough for a cold start, where the link waits for the backend and -// the environment's first synchronization. -const THREAD_LIST_TIMEOUT_MS = 30_000; -const ARCHIVE_TIMEOUT_MS = 10_000; - -// A cached snapshot can predate threads created or unarchived elsewhere, so wait until it is live. -function waitForThreadList(environmentId: EnvironmentId): Promise { - const atom = environmentShell.stateValueAtom(environmentId); - return new Promise((resolve) => { - let unsubscribe: (() => void) | null = null; - const finish = (loaded: boolean) => { - clearTimeout(timeout); - unsubscribe?.(); - resolve(loaded); - }; - const timeout = setTimeout(() => finish(false), THREAD_LIST_TIMEOUT_MS); - unsubscribe = appAtomRegistry.subscribe(atom, (state) => { - if (state.status === "live") finish(true); - }); - if (appAtomRegistry.get(atom).status === "live") finish(true); - }); -} - -async function hasArchivedThread(threadRef: ScopedThreadRef): Promise { - const result = await executeAtomQuery( - appAtomRegistry, - archivedSnapshotAtom(threadRef.environmentId), - { - label: "thread link archived lookup", - reportFailure: false, - refresh: true, - signal: AbortSignal.timeout(ARCHIVE_TIMEOUT_MS), - }, - ).catch(() => null); - if (result?._tag !== "Success") return null; - return result.value.threads.some((thread) => thread.id === threadRef.threadId); -} - -const FAILURE_DESCRIPTIONS: Record, string> = { - "environment-not-found": "The link's environment isn't connected to this app.", - "environment-unavailable": "The link's environment isn't reachable right now.", - "thread-not-found": "The thread doesn't exist or was deleted.", -}; - -/** Opens threads from `://app//` links the desktop shell forwards. */ -export function DesktopThreadLinkCoordinator() { - const router = useRouter(); - const threadLinks = window.desktopBridge?.threadLinks; - // Until the catalog loads, every environment (and the primary alias) reads as unknown. - const catalogReady = useAtomValue(environmentCatalog.catalogValueAtom).isReady; - const latestLinkRef = useRef(0); - - const openLink = useEffectEvent(async (link: DesktopThreadLink) => { - const linkId = ++latestLinkRef.current; - const resolution = await resolveDesktopThreadLink(link, { - isKnownEnvironment: (environmentId) => - appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.get(environmentId) - ?.enabled === true, - primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom), - waitForThreadList, - hasActiveThread: (threadRef) => readThreadShell(threadRef) !== null, - hasArchivedThread, - }); - // A newer link, or unmounting, supersedes this one while it was still resolving. - if (linkId !== latestLinkRef.current) return; - if (resolution.kind !== "open") { - toastManager.add({ - type: "error", - title: "Couldn't open thread link", - description: FAILURE_DESCRIPTIONS[resolution.kind], - }); - return; - } - const matches = router.state.matches; - const { threadRef } = resolution; - openThreadInActivePane({ - targetRef: threadRef, - routeThreadRef: resolveThreadRouteRef(matches[matches.length - 1]?.params ?? {}), - navigateToPrimary: () => - router.navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }), - }); - }); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop thread-link IPC - useEffect(() => { - if (threadLinks === undefined || !catalogReady) return; - const unsubscribe = threadLinks.onOpen((link) => void openLink(link)); - void threadLinks.setReady(true).catch(() => undefined); - return () => { - latestLinkRef.current += 1; - void threadLinks.setReady(false).catch(() => undefined); - unsubscribe(); - }; - }, [catalogReady, threadLinks]); - - return null; -} diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx index 3f5cdeffd2c56..9ceacfd571819 100644 --- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx +++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx @@ -31,6 +31,7 @@ import { appAtomRegistry } from "../../rpc/atomRegistry"; import { resolveThreadRouteRef, resolveThreadRouteTarget } from "../../threadRoutes"; import { placeLinkedPrompt } from "../promptLinks/linkedPrompt"; import { openThreadInActivePane } from "../thread-split/threadOpenTarget"; +import { resolveLinkedThread } from "./resolveLinkedThread"; import { useThreadSplitStore } from "../thread-split/threadSplitStore"; import { assetEnvironment } from "../../state/assets"; import { readProject, readThreadShell } from "../../state/entities"; @@ -182,27 +183,33 @@ export function DesktopWebLinkCoordinator() { return threadRef; }; - // Fork: a thread link opens in the active split pane. A primary-pane landing keeps the - // `?prompt=` in the route for ThreadLinkPrompt; any other landing places the prompt here. - const openAppPath = (appPath: string) => { + // Fork: a thread link resolves `primary` and must name a known thread, active or archived, and + // opens in the active split pane. A primary-pane landing keeps the `?prompt=` in the route for + // ThreadLinkPrompt; any other landing places the prompt here. + const openAppPath = async (appPath: string) => { const threadPath = THREAD_APP_PATH.exec(appPath); - const targetRef = threadPath - ? resolveThreadRouteRef({ - environmentId: decodeURIComponent(threadPath[1]!), - threadId: decodeURIComponent(threadPath[2]!), - }) - : null; - if (targetRef === null) { + if (!threadPath) { void router.navigate({ href: appPath }); return; } + const linkEnvironmentId = decodeURIComponent(threadPath[1]!); + const targetRef = await resolveLinkedThread( + linkEnvironmentId, + decodeURIComponent(threadPath[2]!), + ); + if (targetRef === null) return; + // `primary` names the resolved environment in the route. + const href = + targetRef.environmentId === linkEnvironmentId + ? appPath + : `/${encodeURIComponent(targetRef.environmentId)}/${threadPath[2]}${threadPath[3] ?? ""}`; const opened = openThreadInActivePane({ targetRef, routeThreadRef: resolveThreadRouteRef(router.state.matches.at(-1)?.params ?? {}), - navigateToPrimary: () => router.navigate({ href: appPath }), + navigateToPrimary: () => router.navigate({ href }), }); if (opened.plan.kind === "navigate-primary") return; - const parsed = parseThreadLinkPrompt(threadPath?.[3] ?? ""); + const parsed = parseThreadLinkPrompt(threadPath[3] ?? ""); if (!parsed.ok) { reportFailure(appPath, parsed.error); } else if (parsed.value !== null) { @@ -254,7 +261,7 @@ export function DesktopWebLinkCoordinator() { } const appPath = promptLinkAppPath(url); if (appPath !== null) { - openAppPath(appPath); + await openAppPath(appPath); return; } const activeThreadRef = diff --git a/apps/web/src/components/desktop/resolveLinkedThread.ts b/apps/web/src/components/desktop/resolveLinkedThread.ts new file mode 100644 index 0000000000000..5028454b0f0c5 --- /dev/null +++ b/apps/web/src/components/desktop/resolveLinkedThread.ts @@ -0,0 +1,97 @@ +import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; +import type { Atom } from "effect/reactivity"; + +import { environmentCatalog } from "../../connection/catalog"; +import { + type DesktopThreadLinkDependencies, + type DesktopThreadLinkResolution, + resolveDesktopThreadLink, +} from "../../desktopThreadLink"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { readThreadShell } from "../../state/entities"; +import { archivedSnapshotAtom } from "../../lib/archivedThreadsState"; +import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment"; +import { environmentShell } from "../../state/shell"; +import { toastManager } from "../ui/toast"; + +// Generous enough for a cold start, where the link waits for the backend and +// the environment's first synchronization. +const LIST_TIMEOUT_MS = 30_000; +const ARCHIVE_TIMEOUT_MS = 10_000; + +/** Resolves false when the atom does not reach the state in time. */ +function waitFor(atom: Atom.Atom, reached: (value: A) => boolean): Promise { + return new Promise((resolve) => { + let unsubscribe: (() => void) | null = null; + const finish = (done: boolean) => { + clearTimeout(timeout); + unsubscribe?.(); + resolve(done); + }; + const timeout = setTimeout(() => finish(false), LIST_TIMEOUT_MS); + unsubscribe = appAtomRegistry.subscribe(atom, (value) => { + if (reached(value)) finish(true); + }); + if (reached(appAtomRegistry.get(atom))) finish(true); + }); +} + +// A cached snapshot can predate threads created or unarchived elsewhere, so wait until it is live. +const waitForThreadList = (environmentId: EnvironmentId) => + waitFor(environmentShell.stateValueAtom(environmentId), (state) => state.status === "live"); + +async function hasArchivedThread(threadRef: ScopedThreadRef): Promise { + const result = await executeAtomQuery( + appAtomRegistry, + archivedSnapshotAtom(threadRef.environmentId), + { + label: "thread link archived lookup", + reportFailure: false, + refresh: true, + signal: AbortSignal.timeout(ARCHIVE_TIMEOUT_MS), + }, + ).catch(() => null); + if (result?._tag !== "Success") return null; + return result.value.threads.some((thread) => thread.id === threadRef.threadId); +} + +const FAILURE_DESCRIPTIONS: Record, string> = { + "environment-not-found": "The link's environment isn't connected to this app.", + "environment-unavailable": "The link's environment isn't reachable right now.", + "thread-not-found": "The thread doesn't exist or was deleted.", +}; + +const linkDependencies: DesktopThreadLinkDependencies = { + isKnownEnvironment: (id) => + appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.get(id)?.enabled === true, + primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom), + waitForThreadList, + hasActiveThread: (threadRef) => readThreadShell(threadRef) !== null, + hasArchivedThread, +}; + +/** + * Fork: the thread a desktop link names, active or archived, with `primary` standing in for the + * primary environment. Shows a short error and resolves null when there is no such thread. + */ +export async function resolveLinkedThread( + environmentId: string, + threadId: string, +): Promise { + // Until the catalog loads, every environment (and the primary alias) reads as unknown. + const catalogReady = await waitFor( + environmentCatalog.catalogValueAtom, + (catalog) => catalog.isReady, + ); + const resolution: DesktopThreadLinkResolution = catalogReady + ? await resolveDesktopThreadLink({ environmentId, threadId }, linkDependencies) + : { kind: "environment-unavailable" }; + if (resolution.kind === "open") return resolution.threadRef; + toastManager.add({ + type: "error", + title: "Couldn't open thread link", + description: FAILURE_DESCRIPTIONS[resolution.kind], + }); + return null; +} diff --git a/apps/web/src/desktopThreadLink.ts b/apps/web/src/desktopThreadLink.ts index 2bf2a1458fe93..4c723932a6904 100644 --- a/apps/web/src/desktopThreadLink.ts +++ b/apps/web/src/desktopThreadLink.ts @@ -1,14 +1,15 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import type { - DesktopThreadLink, - EnvironmentId, - ScopedThreadRef, - ThreadId, -} from "@t3tools/contracts"; +import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; /** Stands in for the primary environment's id, which tools outside the app cannot know. */ const PRIMARY_ENVIRONMENT_LINK_ALIAS = "primary"; +/** The ids of a desktop thread link, as written: the environment may be `primary`. */ +export interface DesktopThreadLink { + readonly environmentId: string; + readonly threadId: string; +} + export type DesktopThreadLinkResolution = | { readonly kind: "open"; readonly threadRef: ScopedThreadRef } | { readonly kind: "environment-not-found" } diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index dda1868731a90..f4d7d1dfe368c 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -30,7 +30,6 @@ import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstall import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog"; import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator"; import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator"; -import { DesktopThreadLinkCoordinator } from "../components/desktop/DesktopThreadLinkCoordinator"; import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator"; import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive"; import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut"; @@ -196,7 +195,6 @@ function RootRouteBranch() { ) : null} - {primaryEnvironmentAuthenticated ? : null} {isElectron ? : null} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 504dd692effba..a522ac5392bce 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -21,13 +21,6 @@ import type { DesktopAppActivationResponse, } from "./desktopAppActivation.ts"; -/** A `://app//` link the desktop shell forwards to the renderer. */ -export interface DesktopThreadLink { - /** An environment id, or `primary` for the desktop's primary environment. */ - readonly environmentId: string; - readonly threadId: string; -} - export interface ContextMenuItem { id: T; label: string; @@ -1249,11 +1242,6 @@ export interface DesktopBridge { complete: (response: DesktopAppActivationResponse) => Promise; onRequest: (listener: (request: DesktopAppActivationRequest) => void) => () => void; }; - /** Present when the desktop shell forwards thread links opened from other apps. */ - threadLinks?: { - setReady: (ready: boolean) => Promise; - onOpen: (listener: (link: DesktopThreadLink) => void) => () => void; - }; preview: DesktopPreviewBridge; /** On-device dictation through macOS 26 SpeechAnalyzer; absent in older desktop builds. */ appleSpeech?: {