Skip to content

Commit 5fe7568

Browse files
t3dotggclaude
andauthored
feat: open T3 Code from a link with a prompt ready to send (#18454)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 48595c7 commit 5fe7568

37 files changed

Lines changed: 2325 additions & 39 deletions

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ it.effect.each(["startup", "open-url"] as const)(
396396
}).pipe(Effect.scoped),
397397
);
398398

399-
it.effect("hands a web link to the renderer and leaves other links alone", () =>
399+
it.effect("hands web and app links to the renderer and leaves other links alone", () =>
400400
Effect.gen(function* () {
401401
storageMock.mockReturnValue(storageAdapter);
402402
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
@@ -420,10 +420,19 @@ it.effect("hands a web link to the renderer and leaves other links alone", () =>
420420
// macOS hands the default browser every web link.
421421
assert.strictEqual(open("https://example.com/page"), 1);
422422
assert.strictEqual(open("http://localhost:3000/"), 1);
423+
// Prompt and thread links ride the same queue; the renderer routes them in the app.
424+
assert.strictEqual(open("t3code://new?prompt=hi"), 1);
425+
assert.strictEqual(open("t3code://threads/env-1/thread-1"), 1);
423426
// Anything else is not a web page; Electron keeps its own handling.
424427
assert.strictEqual(open("mailto:[email protected]"), 0);
428+
assert.strictEqual(open("t3code://somewhere-else"), 0);
425429
yield* Effect.yieldNow;
426-
assert.deepStrictEqual(received, ["https://example.com/page", "http://localhost:3000/"]);
430+
assert.deepStrictEqual(received, [
431+
"https://example.com/page",
432+
"http://localhost:3000/",
433+
"t3code://new?prompt=hi",
434+
"t3code://threads/env-1/thread-1",
435+
]);
427436
}).pipe(
428437
Effect.provide(layerDesktopClerk(true, [], "darwin")),
429438
Effect.provideService(HostProcess.Arguments, ["t3"]),

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { codexAuthDeliveryUrl, readCodexAuthHandoff } from "@t3tools/shared/code
1212
import { receiveCodexAuthCallback, CodexAuthCallbackError } from "./CodexAuthCallback.ts";
1313
import * as ElectronShell from "../electron/ElectronShell.ts";
1414
import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
15+
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
1516
import * as HostProcess from "@t3tools/shared/HostProcess";
1617
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
1718
import * as ElectronApp from "../electron/ElectronApp.ts";
@@ -188,16 +189,28 @@ export const make = Effect.gen(function* () {
188189
);
189190
return true;
190191
};
192+
// Prompt links and thread links (`t3code://new?…`, `t3code://threads/…`) reach the
193+
// renderer through the same queue as web links; it routes them in the app.
194+
const openAppLink = (value: string | undefined) => {
195+
if (!value || promptLinkAppPath(value) === null) return false;
196+
void runPromise(webLinks.receive(value));
197+
return true;
198+
};
191199
const args = yield* HostProcess.Arguments;
192-
args.some((value) => startProviderAuthHandoff(value));
200+
args.some((value) => startProviderAuthHandoff(value) || openAppLink(value));
193201
// As the default browser, macOS hands T3 Code every web link through the same event.
194202
const openWebLink = (url: string) => {
195203
if (!DesktopWebLinks.isWebLink(url)) return false;
196204
void runPromise(webLinks.receive(url));
197205
return true;
198206
};
199207
yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
200-
if (startProviderAuthHandoff(url) || resumeProviderAuth(url) || openWebLink(url))
208+
if (
209+
startProviderAuthHandoff(url) ||
210+
resumeProviderAuth(url) ||
211+
openWebLink(url) ||
212+
openAppLink(url)
213+
)
201214
event.preventDefault();
202215
});
203216
// A browser opens HTML files too, which macOS hands over by path.
@@ -207,7 +220,12 @@ export const make = Effect.gen(function* () {
207220
void runPromise(webLinks.receive(NodeURL.pathToFileURL(path).href));
208221
});
209222
yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
210-
if (argv?.some((value) => startProviderAuthHandoff(value) || resumeProviderAuth(value)))
223+
if (
224+
argv?.some(
225+
(value) =>
226+
startProviderAuthHandoff(value) || resumeProviderAuth(value) || openAppLink(value),
227+
)
228+
)
211229
return;
212230
void runPromise(
213231
Effect.gen(function* () {

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ export const isWebPageFile = (path: string) => /\.x?html?$/i.test(path);
1818

1919
/**
2020
* Web links and HTML files macOS opens with T3 Code once it is the default
21-
* browser. Files arrive as file:// URLs. They can
21+
* browser, plus `t3code://` prompt and thread links on every platform. Files
22+
* arrive as file:// URLs. They can
2223
* arrive before the app is ready (the link that launched it) or while the web
2324
* app reloads, so they wait until the renderer says it is listening.
2425
*/

‎apps/mobile/src/components/CopyTextButton.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ export const CopyTextButton = memo(function CopyTextButton(props: {
1010
readonly accessibilityLabel: string;
1111
readonly text: string;
1212
readonly onCopy?: () => Promise<void>;
13+
/** Lets a long-press menu wrap the button (`ControlPillMenu` injects it on Android). */
14+
readonly onLongPress?: () => void;
1315
readonly tintColor?: ColorValue;
1416
readonly copiedTintColor?: ColorValue;
1517
readonly backgroundColor?: ColorValue;
@@ -35,6 +37,7 @@ export const CopyTextButton = memo(function CopyTextButton(props: {
3537
accessibilityLabel={copied ? "Copied" : props.accessibilityLabel}
3638
disabled={props.text.length === 0}
3739
hitSlop={8}
40+
onLongPress={props.onLongPress}
3841
onPress={async () => {
3942
try {
4043
if (props.onCopy) await props.onCopy();

‎apps/mobile/src/features/projects/AddProjectDestinationRoute.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ type AddProjectDestinationRouteParams = {
77
readonly remoteUrl?: string | string[];
88
readonly repositoryTitle?: string | string[];
99
readonly repositoryName?: string | string[];
10+
/** A prompt link's prompt, for the draft the clone opens. */
11+
readonly prompt?: string | string[];
1012
};
1113

1214
export function AddProjectDestinationRoute({

‎apps/mobile/src/features/projects/AddProjectScreen.tsx‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ import {
8585
useSavedRemoteConnections,
8686
} from "../../state/use-remote-environment-registry";
8787
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
88+
import {
89+
createNewTaskDraft,
90+
setComposerDraftText,
91+
waitForComposerDraftsLoaded,
92+
} from "../../state/use-composer-drafts";
8893

8994
interface EnvironmentOption {
9095
readonly environmentId: EnvironmentId;
@@ -676,13 +681,31 @@ export function AddProjectSourceScreen() {
676681

677682
function openNewTaskDraft(
678683
navigation: { dispatch: (action: ReturnType<typeof CommonActions.reset>) => void },
679-
params: { environmentId: EnvironmentId; projectId: ProjectId; title: string; cloning?: "1" },
684+
params: {
685+
environmentId: EnvironmentId;
686+
projectId: ProjectId;
687+
title: string;
688+
cloning?: "1";
689+
draftId?: string;
690+
},
680691
) {
681692
navigation.dispatch(
682693
CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }),
683694
);
684695
}
685696

697+
/** A new task draft in the project, holding a prompt link's prompt. */
698+
async function draftWithPrompt(
699+
environmentId: EnvironmentId,
700+
projectId: ProjectId,
701+
prompt: string,
702+
): Promise<string> {
703+
await waitForComposerDraftsLoaded();
704+
const draftId = createNewTaskDraft({ environmentId, projectId });
705+
setComposerDraftText(draftId, prompt);
706+
return draftId;
707+
}
708+
686709
function useCreateProject(environment: EnvironmentOption | null) {
687710
const navigation = useNavigation();
688711
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
@@ -1302,6 +1325,7 @@ export function AddProjectDestinationScreen(props: {
13021325
readonly remoteUrl?: string | string[];
13031326
readonly repositoryTitle?: string | string[];
13041327
readonly repositoryName?: string | string[];
1328+
readonly prompt?: string | string[];
13051329
}) {
13061330
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
13071331
reportFailure: false,
@@ -1323,6 +1347,7 @@ export function AddProjectDestinationScreen(props: {
13231347
const createProject = useCreateProject(environment);
13241348
const remoteUrl = stringParam(props.remoteUrl);
13251349
const repositoryTitle = stringParam(props.repositoryTitle);
1350+
const prompt = stringParam(props.prompt);
13261351
// A lookup derives this from "owner/repo", a pasted clone URL from its own
13271352
// last segment. Older links without the param keep the browsed folder.
13281353
// Trim once here: the path input and the folder-list filter must compare the
@@ -1394,6 +1419,13 @@ export function AddProjectDestinationScreen(props: {
13941419
projectId,
13951420
title,
13961421
cloning: "1",
1422+
...(prompt
1423+
? // Without its prompt the draft still opens on the cloned project.
1424+
await draftWithPrompt(environment.environmentId, projectId, prompt).then(
1425+
(draftId) => ({ draftId }),
1426+
() => ({}),
1427+
)
1428+
: {}),
13971429
});
13981430
}
13991431
}
@@ -1424,6 +1456,7 @@ export function AddProjectDestinationScreen(props: {
14241456
isSubmitting,
14251457
navigation,
14261458
pathInput,
1459+
prompt,
14271460
remoteUrl,
14281461
startProjectClone,
14291462
]);
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { buildNewThreadLink, type LinkedPrompt } from "@t3tools/shared/promptLinks";
2+
import { Alert } from "react-native";
3+
4+
import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
5+
import {
6+
getComposerDraftSnapshot,
7+
setComposerDraftText,
8+
waitForComposerDraftsLoaded,
9+
} from "../../state/use-composer-drafts";
10+
import { linkedThreadDraftAction } from "./prompt-link-model";
11+
12+
/** Shows the one notice a prompt link owes the user, built with `promptLinkNotice`. */
13+
export function showPromptLinkNotice(notice: string): void {
14+
Alert.alert("Prompt from a link", notice);
15+
}
16+
17+
/**
18+
* Puts a linked prompt into an existing thread's composer draft. An empty composer is filled;
19+
* typed text is replaced only when the user says so. The notice rides in the same alert, so a
20+
* link never stacks two dialogs.
21+
*/
22+
export async function applyLinkedPromptToThreadDraft(
23+
draftKey: string,
24+
prompt: LinkedPrompt,
25+
notice: string,
26+
): Promise<void> {
27+
try {
28+
await waitForComposerDraftsLoaded();
29+
} catch {
30+
Alert.alert("Could not open link", "Drafts could not be loaded, so the prompt was not added.");
31+
return;
32+
}
33+
const action = linkedThreadDraftAction(getComposerDraftSnapshot(draftKey).text, prompt.text);
34+
if (action !== "ask") {
35+
if (action === "fill") setComposerDraftText(draftKey, prompt.text);
36+
showPromptLinkNotice(notice);
37+
return;
38+
}
39+
Alert.alert("Linked prompt ready. Replace draft?", notice, [
40+
{ text: "Keep mine", style: "cancel" },
41+
{ text: "Replace", onPress: () => setComposerDraftText(draftKey, prompt.text) },
42+
]);
43+
}
44+
45+
/** Copies a shareable link that opens a new task with this prompt. Used by sent user messages. */
46+
export async function copyPromptLink(prompt: string): Promise<void> {
47+
if (!(await tryCopyTextWithHaptic(buildNewThreadLink({ prompt }), { target: "prompt link" }))) {
48+
Alert.alert("Could not copy", "Try again.");
49+
}
50+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { parseNewThreadLink } from "@t3tools/shared/promptLinks";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import {
5+
latestThreadEnvironmentIds,
6+
linkedThreadDraftAction,
7+
promptLinkNotice,
8+
promptLinkScratchEnvironmentId,
9+
promptLinkSearchFromParams,
10+
} from "./prompt-link-model";
11+
12+
describe("promptLinkSearchFromParams", () => {
13+
it("round-trips decoded route params into the shared parser", () => {
14+
const search = promptLinkSearchFromParams({
15+
prompt: "Fix the bug & add tests = done?",
16+
repo: ["pingdotgg/t3code", "ignored/second"],
17+
provider: "codex",
18+
screen: "NewTask",
19+
});
20+
21+
expect(parseNewThreadLink(search ?? "")).toEqual({
22+
ok: true,
23+
value: {
24+
kind: "new",
25+
prompt: { text: "Fix the bug & add tests = done?", hiddenCharacters: 0 },
26+
repository: { owner: "pingdotgg", name: "t3code" },
27+
provider: "codex",
28+
model: null,
29+
},
30+
});
31+
});
32+
33+
it("is null for routes without a prompt link", () => {
34+
expect(promptLinkSearchFromParams({ incomingShareId: "share-1" })).toBeNull();
35+
expect(promptLinkSearchFromParams(undefined)).toBeNull();
36+
});
37+
});
38+
39+
describe("promptLinkNotice", () => {
40+
it("replaces the plain notice with the hidden character warning", () => {
41+
expect(promptLinkNotice({ hiddenCharacters: 0 })).toBe(
42+
"This prompt came from a link. Read it before you send.",
43+
);
44+
expect(promptLinkNotice({ hiddenCharacters: 2, modelUnavailable: true })).toBe(
45+
"This prompt had hidden characters, it may be malicious. They were removed. Read it before you send.\n\nThe requested model is not available, so your default is used.",
46+
);
47+
});
48+
});
49+
50+
describe("linkedThreadDraftAction", () => {
51+
it("fills an empty composer and asks before replacing typed text", () => {
52+
expect(linkedThreadDraftAction(" \n", "Do it")).toBe("fill");
53+
expect(linkedThreadDraftAction("Do it", "Do it")).toBe("keep");
54+
expect(linkedThreadDraftAction("My notes", "Do it")).toBe("ask");
55+
});
56+
});
57+
58+
describe("promptLinkScratchEnvironmentId", () => {
59+
it("prefers the most recently active machine that offers threads without a project", () => {
60+
expect(promptLinkScratchEnvironmentId(["a", "b", "c"], ["c", "b"])).toBe("b");
61+
expect(promptLinkScratchEnvironmentId(["a"], ["c"])).toBe("c");
62+
expect(promptLinkScratchEnvironmentId(["a"], [])).toBeNull();
63+
});
64+
});
65+
66+
describe("latestThreadEnvironmentIds", () => {
67+
it("orders machines by their latest thread", () => {
68+
expect(
69+
latestThreadEnvironmentIds([
70+
{ environmentId: "a", updatedAt: "2026-01-02T00:00:00.000Z" },
71+
{ environmentId: "b", updatedAt: "2026-01-03T00:00:00.000Z" },
72+
{ environmentId: "a", updatedAt: "2026-01-04T00:00:00.000Z" },
73+
]),
74+
).toEqual(["a", "b"]);
75+
});
76+
});

0 commit comments

Comments
 (0)