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, 14:30 UTC
feat(desktop): add a remote server by clicking its t3code://pair link (#24111)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 27, 2026 at 16:01 UTC
dde3fdb5a6cd73573559de5b0ace0e18d994c7c5
11 files changed
+240
-23
apps/desktop/src/app/DesktopClerk.test.ts
+9
-2
@@ -156,6 +156,7 @@ describe("DesktopClerk", () => {
156
`setPath:userData:${userData}`,
157
"requestSingleInstanceLock",
158
"on:second-instance",
159
+ "on:open-url",
160
"createClerkBridge",
161
]);
162
},
@@ -200,7 +201,7 @@ describe("DesktopClerk", () => {
201
},
202
);
203
203
- it.effect("delivers queued startup links and later links once in arrival order", () => {
204
+ it.effect("delivers each queued startup link once, before later links", () => {
205
storageMock.mockReturnValue(storageAdapter);
206
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
207
const listeners = new Map<string, (...args: unknown[]) => void>();
@@ -208,6 +209,7 @@ describe("DesktopClerk", () => {
209
const first = "t3code://new?prompt=first";
210
const second = "t3code://threads/env-1/thread-1";
211
const later = "t3code://new?prompt=later";
212
+ const launchPair = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
213
const delivered = Promise.withResolvers<void>();
214
const electronApp = {
215
on: (name: string, listener: (...args: unknown[]) => void) =>
@@ -220,13 +222,14 @@ describe("DesktopClerk", () => {
222
const clerk = yield* DesktopClerk.DesktopClerk;
223
listeners.get("second-instance")?.({}, ["t3", first]);
224
listeners.get("second-instance")?.({}, ["t3", second]);
225
+ listeners.get("open-url")?.({ preventDefault: () => undefined }, launchPair);
226
assert.deepEqual(received, []);
227
228
yield* clerk.configure;
229
listeners.get("second-instance")!({}, ["t3", later]);
230
yield* Effect.promise(() => delivered.promise);
231
229
- assert.deepEqual(received, [first, second, later]);
232
+ assert.deepEqual(received, [launchPair, first, second, later]);
233
}).pipe(
234
Effect.scoped,
235
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),
@@ -425,6 +428,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
428
}),
429
} as unknown as ElectronApp.ElectronApp["Service"];
430
const received: Array<string> = [];
431
+ const pairLink = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
432
yield* Effect.gen(function* () {
433
const clerk = yield* DesktopClerk.DesktopClerk;
434
yield* clerk.configure;
@@ -437,6 +441,8 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
441
assert.strictEqual(open("http://localhost:3000/"), 1);
442
assert.strictEqual(open("t3code://new?prompt=hi"), 1);
443
assert.strictEqual(open("t3code://threads/env-1/thread-1"), 1);
444
+ assert.strictEqual(open(pairLink), 1);
445
+ assert.strictEqual(open("t3code://pair"), 0);
446
assert.strictEqual(open("mailto:hello@example.com"), 0);
447
assert.strictEqual(open("t3code://somewhere-else"), 0);
448
yield* Effect.yieldNow;
@@ -445,6 +451,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
451
"http://localhost:3000/",
452
"t3code://new?prompt=hi",
453
"t3code://threads/env-1/thread-1",
454
+ pairLink,
455
]);
456
}).pipe(
457
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),
apps/desktop/src/app/DesktopClerk.ts
+18
-10
@@ -13,6 +13,7 @@ import { receiveCodexAuthCallback, CodexAuthCallbackError } from "./CodexAuthCal
13
import * as ElectronShell from "../electron/ElectronShell.ts";
14
import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
15
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
16
+import { readPairingAppLink } from "@t3tools/shared/remote";
17
import * as HostProcess from "@t3tools/shared/HostProcess";
18
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
19
import * as ElectronApp from "../electron/ElectronApp.ts";
@@ -118,6 +119,15 @@ export const make = Effect.gen(function* () {
119
yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
120
handleSecondInstance(argv);
121
});
122
+ // macOS hands a launch link to open-url, which can fire before configure runs.
123
+ const pendingOpenUrls: Array<string> = [];
124
+ let handleOpenUrl = (url: string) => {
125
+ pendingOpenUrls.push(url);
126
+ return true;
127
+ };
128
+ yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
129
+ if (handleOpenUrl(url)) event.preventDefault();
130
+ });
131
132
yield* Effect.acquireRelease(
133
Effect.try({
@@ -194,7 +204,8 @@ export const make = Effect.gen(function* () {
204
return true;
205
};
206
const openAppLink = (value: string | undefined) => {
197
- if (!value || promptLinkAppPath(value) === null) return false;
207
+ if (!value || (promptLinkAppPath(value) === null && readPairingAppLink(value) === null))
208
+ return false;
209
void runPromise(webLinks.receive(value));
210
return true;
211
};
@@ -205,15 +216,12 @@ export const make = Effect.gen(function* () {
216
void runPromise(webLinks.receive(url));
217
return true;
218
};
208
- yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
209
- if (
210
- startProviderAuthHandoff(url) ||
211
- resumeProviderAuth(url) ||
212
- openWebLink(url) ||
213
- openAppLink(url)
214
- )
215
- event.preventDefault();
216
- });
219
+ handleOpenUrl = (url) =>
220
+ startProviderAuthHandoff(url) ||
221
+ resumeProviderAuth(url) ||
222
+ openWebLink(url) ||
223
+ openAppLink(url);
224
+ for (const url of pendingOpenUrls.splice(0)) handleOpenUrl(url);
225
yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
226
if (!DesktopWebLinks.isWebPageFile(path)) return;
227
event.preventDefault();
apps/server/src/cli/pair.test.ts
+2
@@ -35,6 +35,7 @@ import {
35
import { DevServerNotProxiableError, resolveTailscaleLocalTarget } from "./pair.ts";
36
37
import packageJson from "../../package.json" with { type: "json" };
38
+import { buildPairingAppLink } from "@t3tools/shared/remote";
39
40
const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
41
@@ -213,6 +214,7 @@ describe("t3 pair", () => {
214
215
const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
216
assert.isString(token);
217
+ assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${token}`)}`);
218
219
const listed = yield* captureStdout(
220
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
apps/server/src/cli/pair.ts
+2
@@ -8,6 +8,7 @@ import {
8
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
9
import * as HostProcess from "@t3tools/shared/HostProcess";
10
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
11
+import { buildPairingAppLink } from "@t3tools/shared/remote";
12
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
13
import {
14
buildTailscaleHttpsBaseUrl,
@@ -193,6 +194,7 @@ const formatPairOutput = (input: {
194
renderTerminalQrCode(input.pairingUrl),
195
"",
196
`Pairing URL: ${input.pairingUrl}`,
197
+ `App link: ${buildPairingAppLink(input.pairingUrl)}`,
198
`Token: ${input.token}`,
199
`Expires: ${DateTime.formatIso(input.expiresAt)}`,
200
...input.notes.flatMap((note) => ["", `Note: ${note}`]),
apps/server/src/startupAccess.ts
+2
@@ -3,6 +3,7 @@ import * as NodeOS from "node:os";
3
4
import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification";
5
import { QrCode } from "@t3tools/shared/qrCode";
6
+import { buildPairingAppLink } from "@t3tools/shared/remote";
7
import * as Effect from "effect/Effect";
8
import { HttpServer } from "effect/http";
9
import * as NetAddress from "effect/net/NetAddress";
@@ -186,6 +187,7 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo):
187
`Connection string: ${accessInfo.connectionString}`,
188
`Token: ${accessInfo.token}`,
189
`Pairing URL: ${accessInfo.pairingUrl}`,
190
+ `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`,
191
"",
192
renderTerminalQrCode(accessInfo.pairingUrl),
193
"",
apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
+97
-5
@@ -8,6 +8,9 @@ const state = vi.hoisted(() => ({
8
projects: [] as never[],
9
navigate: vi.fn(async (): Promise<void> => undefined),
10
openScratchProject: vi.fn(async () => null),
11
+ confirm: vi.fn(async (_message: string) => true),
12
+ connectPairing: vi.fn(async (_input: { pairingUrl: string }) => ({ _tag: "Success" })),
13
+ localEnvironmentDisabled: false,
14
}));
15
16
// One connected primary environment that can read pull requests. Its project list and
@@ -20,11 +23,17 @@ vi.mock(import("@tanstack/react-router"), async (original) => ({
23
vi.mock(import("../../state/environments"), async (original) => ({
24
...(await original()),
25
usePrimaryEnvironmentId: () => "local" as EnvironmentId,
23
- usePrimaryEnvironment: (() => ({
24
- environmentId: "local",
25
- connection: { phase: "connected" },
26
- serverConfig: {},
27
- })) as never,
26
+ usePrimaryEnvironment: (() =>
27
+ state.localEnvironmentDisabled
28
+ ? null
29
+ : {
30
+ environmentId: "local",
31
+ connection: { phase: "connected" },
32
+ serverConfig: {},
33
+ }) as never,
34
+}));
35
+vi.mock(import("../../localEnvironment"), () => ({
36
+ isLocalEnvironmentDisabled: () => state.localEnvironmentDisabled,
37
}));
38
vi.mock(import("../../state/server"), async (original) => {
39
const { Atom } = await import("effect/reactivity");
@@ -52,6 +61,25 @@ vi.mock(import("../../hooks/useScratchProject"), async (original) => ({
61
})) as never,
62
}));
63
64
+vi.mock(import("../../confirmDialog"), async (original) => ({
65
+ ...(await original()),
66
+ requestConfirmDialog: state.confirm,
67
+}));
68
+vi.mock(import("../../connection/onboarding"), async (original) => ({
69
+ ...(await original()),
70
+ connectPairing: "connectPairing" as never,
71
+}));
72
+vi.mock(import("../../state/use-atom-command"), async (original) => {
73
+ const actual = await original();
74
+ return {
75
+ ...actual,
76
+ useAtomCommand: ((command: unknown, options: never) =>
77
+ command === "connectPairing"
78
+ ? state.connectPairing
79
+ : actual.useAtomCommand(command as never, options)) as never,
80
+ };
81
+});
82
+
83
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
84
import { allReachableShellsLiveAtom } from "../../state/shell";
85
import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator";
@@ -87,8 +115,13 @@ const pullRequestView = {
115
},
116
};
117
118
+const pairingUrl = "https://vps.example.com/pair#token=ABC123";
119
+const pairLink = `t3code://pair?pairingUrl=${encodeURIComponent(pairingUrl)}`;
120
+
121
function setup() {
122
vi.clearAllMocks();
123
+ state.confirm.mockResolvedValue(true);
124
+ state.localEnvironmentDisabled = false;
125
state.projects = [];
126
appAtomRegistry.set(discoverySettled, false);
127
}
@@ -138,3 +171,62 @@ it("holds a launch PR link until project discovery settles, then opens the PR vi
171
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(pullRequestView);
172
expect(state.openScratchProject).not.toHaveBeenCalled();
173
});
174
+
175
+it("adds the backend from a pairing link after the user confirms its host", async () => {
176
+ setup();
177
+ await using _coordinator = await mount(pairLink);
178
+ await vi.waitFor(() =>
179
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl }),
180
+ );
181
+ expect(state.confirm).toHaveBeenCalledExactlyOnceWith(
182
+ "Add the backend at https://vps.example.com?",
183
+ );
184
+ expect(state.navigate).not.toHaveBeenCalled();
185
+});
186
+
187
+it("does not spend the pairing token when the user declines", async () => {
188
+ setup();
189
+ const otherPairingUrl = "https://other.example.com/pair#token=XYZ789";
190
+ state.confirm.mockResolvedValueOnce(false);
191
+ await using _coordinator = await mount(
192
+ pairLink,
193
+ `t3code://pair?pairingUrl=${encodeURIComponent(otherPairingUrl)}`,
194
+ );
195
+ await vi.waitFor(() => expect(state.connectPairing).toHaveBeenCalled());
196
+ expect(state.confirm).toHaveBeenCalledTimes(2);
197
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl: otherPairingUrl });
198
+});
199
+
200
+it("skips a repeat of a pairing link that already paired", async () => {
201
+ setup();
202
+ const otherPairingUrl = "https://other.example.com/pair#token=XYZ789";
203
+ await using _coordinator = await mount(
204
+ pairLink,
205
+ pairLink,
206
+ `t3code://pair?pairingUrl=${encodeURIComponent(otherPairingUrl)}`,
207
+ );
208
+ await vi.waitFor(() =>
209
+ expect(state.connectPairing).toHaveBeenLastCalledWith({ pairingUrl: otherPairingUrl }),
210
+ );
211
+ expect(state.confirm).toHaveBeenCalledTimes(2);
212
+ expect(state.connectPairing.mock.calls).toEqual([
213
+ [{ pairingUrl }],
214
+ [{ pairingUrl: otherPairingUrl }],
215
+ ]);
216
+});
217
+
218
+it("pairs with Local environment disabled, where there is no primary environment to wait for", async () => {
219
+ setup();
220
+ state.localEnvironmentDisabled = true;
221
+ await using _coordinator = await mount(pairLink);
222
+ await vi.waitFor(() =>
223
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl }),
224
+ );
225
+});
226
+
227
+it("does not hold a PR link for project discovery that never settles with Local environment disabled", async () => {
228
+ setup();
229
+ state.localEnvironmentDisabled = true;
230
+ await using _coordinator = await mount(pullRequestUrl);
231
+ await vi.waitFor(() => expect(state.openScratchProject).toHaveBeenCalledOnce());
232
+});
apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
+68
-5
@@ -1,16 +1,23 @@
1
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import {
3
+ isAtomCommandInterrupted,
4
+ squashAtomCommandFailure,
5
+} from "@t3tools/client-runtime/state/runtime";
6
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
7
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
8
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
9
+import { readPairingAppLink, resolveRemotePairingTarget } from "@t3tools/shared/remote";
10
import { useRouter } from "@tanstack/react-router";
11
import * as Effect from "effect/Effect";
12
import { AtomRegistry } from "effect/reactivity";
13
import * as Stream from "effect/Stream";
10
-import { useEffect, useEffectEvent, useRef } from "react";
14
+import { useEffect, useEffectEvent, useRef, useState } from "react";
15
16
import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview";
17
import { isPreviewAvailableFor } from "../../browser/previewRuntime";
18
+import { requestConfirmDialog } from "../../confirmDialog";
19
+import { connectPairing } from "../../connection/onboarding";
20
+import { isLocalEnvironmentDisabled } from "../../localEnvironment";
21
import { useComposerDraftStore } from "../../composerDraftStore";
22
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
23
import { useScratchProject } from "../../hooks/useScratchProject";
@@ -82,19 +89,62 @@ export function DesktopWebLinkCoordinator() {
89
reportFailure: false,
90
refresh: true,
91
});
92
+ const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
93
const httpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironment?.environmentId ?? null);
94
const queueRef = useRef(Promise.resolve());
95
+ const pairedUrlsRef = useRef(new Set<string>());
96
const webLinks = window.desktopBridge?.webLinks;
97
+ // A sync IPC read; the setting only changes across a relaunch.
98
+ const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
99
+ // With Local environment disabled there is no primary to wait for, so links run against the
100
+ // saved remote environments instead of waiting forever.
101
const ready =
102
webLinks !== undefined &&
90
- primaryEnvironment?.connection.phase === "connected" &&
91
- primaryEnvironment.serverConfig !== null;
103
+ (localEnvironmentDisabled ||
104
+ (primaryEnvironment?.connection.phase === "connected" &&
105
+ primaryEnvironment.serverConfig !== null));
106
107
const reportFailure = (url: string, description = url) =>
108
toastManager.add(
109
stackedThreadToast({ type: "error", title: "Could not open the link", description }),
110
);
111
112
+ const reportPairingFailure = (error: unknown) =>
113
+ toastManager.add(
114
+ stackedThreadToast({
115
+ type: "error",
116
+ title: "Could not add backend",
117
+ description: error instanceof Error ? error.message : "Failed to add backend.",
118
+ }),
119
+ );
120
+
121
+ // Any page can open a pairing link, so the user confirms the host before its one-time token is spent.
122
+ const pairFromLink = async (pairingUrl: string) => {
123
+ // A repeated click would only ask again and then fail on the spent one-time token.
124
+ if (pairedUrlsRef.current.has(pairingUrl)) return;
125
+ // The origin keeps the scheme visible, so a plain HTTP backend is not mistaken for HTTPS.
126
+ let origin: string;
127
+ try {
128
+ origin = new URL(resolveRemotePairingTarget({ pairingUrl }).httpBaseUrl).origin;
129
+ } catch (error) {
130
+ reportPairingFailure(error);
131
+ return;
132
+ }
133
+ const confirmed = (await requestConfirmDialog(`Add the backend at ${origin}?`)) ?? false;
134
+ if (!confirmed) return;
135
+ const result = await connectPairingEnvironment({ pairingUrl });
136
+ if (result._tag === "Failure") {
137
+ if (!isAtomCommandInterrupted(result)) reportPairingFailure(squashAtomCommandFailure(result));
138
+ return;
139
+ }
140
+ pairedUrlsRef.current.add(pairingUrl);
141
+ toastManager.add({
142
+ type: "success",
143
+ title: "Backend added",
144
+ description: "The environment is saved and will reconnect on app startup.",
145
+ });
146
+ };
147
+
148
const startThread = async (url: string): Promise<ScopedThreadRef | null> => {
149
const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null);
150
if (environmentId === null) {
@@ -114,6 +164,11 @@ export function DesktopWebLinkCoordinator() {
164
};
165
166
const openLink = useEffectEvent(async (url: string) => {
167
+ const pairingUrl = readPairingAppLink(url);
168
+ if (pairingUrl !== null) {
169
+ await pairFromLink(pairingUrl);
170
+ return;
171
+ }
172
const appPath = promptLinkAppPath(url);
173
if (appPath !== null) {
174
await router.navigate({ href: appPath });
@@ -121,6 +176,11 @@ export function DesktopWebLinkCoordinator() {
176
}
177
if (openChangeRequest(externalClick, url)) return;
178
const isFile = url.startsWith("file:");
179
+ // Only this machine's environment serves files, so fail before starting a thread.
180
+ if (isFile && httpBaseUrl === null) {
181
+ reportFailure(url);
182
+ return;
183
+ }
184
const routeParams = router.state.matches.at(-1)?.params ?? {};
185
const threadRef =
186
threadShowingBrowser(
@@ -154,8 +214,11 @@ export function DesktopWebLinkCoordinator() {
214
// A connected server publishes its config before its project snapshot, so a PR link
215
// delivered at launch would miss its project and fall through to the browser. Hold PR
216
// links, and only those, until discovery settles; an ordinary link never waits for it.
217
+ // Discovery never settles without the local environment, so those links do not wait.
218
const hold =
158
- openPullRequestsInApp && sourceControlClients.parseChangeRequestUrl(url) !== null
219
+ openPullRequestsInApp &&
220
+ !localEnvironmentDisabled &&
221
+ sourceControlClients.parseChangeRequestUrl(url) !== null
222
? projectsSettled()
223
: Promise.resolve();
224
void hold.then(() => {
apps/web/src/routes/__root.tsx
+5
-1
@@ -143,6 +143,8 @@ function RootRouteBranch() {
143
const pathname = useLocation({ select: (location) => location.pathname });
144
const { authGateState } = Route.useRouteContext();
145
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
146
+ // A sync IPC read; the setting only changes across a relaunch.
147
+ const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
148
// Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
149
const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
150
if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
@@ -195,7 +197,9 @@ function RootRouteBranch() {
197
hostedStatic={authGateState.status === "hosted-static"}
198
>
199
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
198
- {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
200
+ {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
201
+ <DesktopWebLinkCoordinator />
202
+ ) : null}
203
{isElectron ? <RunningThreadKeepAlive /> : null}
204
<RelayClientInstallDialog />
205
<ConnectOnboardingDialog />
docs/user/remote-access.md
+4
@@ -58,6 +58,10 @@ in the receiving app. Connection settings are under **Settings → Environments*
58
on web and desktop and **Settings → Environments** on mobile. A loopback address
59
such as `127.0.0.1` reaches only the device opening the link.
60
61
+On a computer with the desktop app, you can open the printed `t3code://pair`
62
+app link instead. The desktop app asks you to confirm the server address, then
63
+adds it.
64
+
65
Pairing authorizes that device for future connections. Use a fresh one-time link
66
for each new device; you do not need the original token to reconnect. Links
67
created in Settings can only be copied from the client that created them while
packages/shared/src/remote.test.ts
+18
@@ -1,6 +1,8 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
import {
4
+ buildPairingAppLink,
5
+ readPairingAppLink,
6
RemoteBackendUrlMissingError,
7
RemotePairingTokenMissingError,
8
RemotePairingUrlInvalidError,
@@ -141,4 +143,20 @@ describe("remote", () => {
143
}),
144
);
145
});
146
+
147
+ it("round-trips pairing urls through app links on every channel scheme", () => {
148
+ const pairingUrl = "https://vps.example.com/pair#token=ABC123";
149
+ const appLink = buildPairingAppLink(pairingUrl);
150
+ expect(appLink.startsWith("t3code://pair?")).toBe(true);
151
+ expect(readPairingAppLink(appLink)).toBe(pairingUrl);
152
+ expect(readPairingAppLink(appLink.replace("t3code:", "t3code-dev:"))).toBe(pairingUrl);
153
+ expect(readPairingAppLink("t3code://pair")).toBeNull();
154
+ expect(readPairingAppLink(appLink.replace("//pair?", "//pair/other?"))).toBeNull();
155
+ expect(
156
+ readPairingAppLink(`t3code://threads?pairingUrl=${encodeURIComponent(pairingUrl)}`),
157
+ ).toBeNull();
158
+ expect(
159
+ readPairingAppLink(`https://pair?pairingUrl=${encodeURIComponent(pairingUrl)}`),
160
+ ).toBeNull();
161
+ });
162
});
packages/shared/src/remote.ts
+15
@@ -3,6 +3,8 @@ import * as Schema from "effect/Schema";
3
const PAIRING_TOKEN_PARAM = "token";
4
const HOSTED_PAIRING_HOST_PARAM = "host";
5
const HOSTED_PAIRING_LABEL_PARAM = "label";
6
+const PAIRING_APP_LINK_PARAM = "pairingUrl";
7
+const APP_LINK_PROTOCOL = /^t3code(?:-[a-z]+)?:$/;
8
const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
9
10
export const readHashParams = (url: URL): URLSearchParams =>
@@ -185,6 +187,19 @@ export const readHostedPairingRequest = (url: URL): HostedPairingRequest | null
187
};
188
};
189
190
+/** Wraps a pairing URL in the `t3code://pair` link that desktop opens and mobile scans. */
191
+export const buildPairingAppLink = (pairingUrl: string): string =>
192
+ `t3code://pair?${new URLSearchParams([[PAIRING_APP_LINK_PARAM, pairingUrl]])}`;
193
+
194
+/** Reads the pairing URL from a `t3code://pair` link on any app channel scheme. */
195
+export const readPairingAppLink = (value: string): string | null => {
196
+ if (!URL.canParse(value)) return null;
197
+ const url = new URL(value);
198
+ if (!APP_LINK_PROTOCOL.test(url.protocol) || url.host !== "pair") return null;
199
+ if (url.pathname !== "" && url.pathname !== "/") return null;
200
+ return url.searchParams.get(PAIRING_APP_LINK_PARAM)?.trim() || null;
201
+};
202
+
203
export const resolveRemotePairingTarget = (input: {
204
readonly pairingUrl?: string;
205
readonly host?: string;