Skip to content

Commit db8152b

Browse files
fix(mobile): thread prompt links fill a draft only for a thread that shows
A thread link wrote the draft and raised the notice as soon as it was parsed, so a link to an unknown thread left an empty composer behind the "Prompt from a link" notice. The link now waits on the navigation state: it applies once its Thread route is on the stack and the thread has a shell, and drops when the route leaves first, as the unknown-thread screen does when it redirects to a new-thread draft. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7a225f5 commit db8152b

7 files changed

Lines changed: 182 additions & 30 deletions

File tree

‎apps/mobile/src/App.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,10 @@ import {
5454
resolvePendingNewTaskPromptLink,
5555
takeNewTaskPromptLink,
5656
} from "./features/prompt-links/newTaskPromptLink";
57-
import { takeThreadPromptLink } from "./features/prompt-links/threadPromptLink";
57+
import {
58+
resolvePendingThreadPromptLink,
59+
takeThreadPromptLink,
60+
} from "./features/prompt-links/threadPromptLink";
5861
import {
5962
disposeOnFoundationReplace,
6063
type FoundationHotModule,
@@ -139,6 +142,7 @@ function handleNavigationStateChange(state: NavigationState | undefined): void {
139142
recordWorkspaceSelections(state);
140143
presentPendingIncomingShare();
141144
resolvePendingNewTaskPromptLink(state);
145+
resolvePendingThreadPromptLink(state);
142146
if (!state) return;
143147
setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
144148
recordAppShortcutNavigationState(state);

‎apps/mobile/src/features/prompt-links/newTaskPromptLink.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ export function resolvePendingNewTaskPromptLink(state: NavigationState | undefin
109109
if (pendingLink === null) return;
110110
const step = stepPendingPromptLink(pendingLink, {
111111
screenOnStack: findStackRoute(state, NEW_TASK_ROUTE) !== undefined,
112-
shellsSettled: appAtomRegistry.get(shellsSettledAtom),
112+
ready: appAtomRegistry.get(shellsSettledAtom),
113113
});
114114
if (step.pending === null) dropPendingLink();
115115
else pendingLink = step.pending;

‎apps/mobile/src/features/prompt-links/prompt-link-model.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,25 +33,25 @@ describe("stepPendingPromptLink", () => {
3333
const waiting = "repo=t3tools%2Ft3code";
3434

3535
it("drops a link whose screen is missing from the first state after it was parsed", () => {
36-
expect(stepPendingPromptLink(waiting, { screenOnStack: false, shellsSettled: true })).toEqual({
36+
expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: true })).toEqual({
3737
pending: null,
3838
resolve: null,
3939
});
4040
});
4141

42-
it("holds a link on its screen until the shells settle, then resolves it once", () => {
43-
expect(stepPendingPromptLink(waiting, { screenOnStack: true, shellsSettled: false })).toEqual({
42+
it("holds a link on its screen until its target is ready, then resolves it once", () => {
43+
expect(stepPendingPromptLink(waiting, { screenOnStack: true, ready: false })).toEqual({
4444
pending: waiting,
4545
resolve: null,
4646
});
47-
expect(stepPendingPromptLink(waiting, { screenOnStack: true, shellsSettled: true })).toEqual({
47+
expect(stepPendingPromptLink(waiting, { screenOnStack: true, ready: true })).toEqual({
4848
pending: null,
4949
resolve: waiting,
5050
});
5151
});
5252

53-
it("drops a link whose screen was left while the shells were loading", () => {
54-
expect(stepPendingPromptLink(waiting, { screenOnStack: false, shellsSettled: false })).toEqual({
53+
it("drops a link whose screen was left before its target was ready", () => {
54+
expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: false })).toEqual({
5555
pending: null,
5656
resolve: null,
5757
});

‎apps/mobile/src/features/prompt-links/prompt-link-model.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@ export const promptLinkRepositoryName = (repository: PromptLinkRepository) =>
7979
`${repository.owner}/${repository.name}`;
8080

8181
/**
82-
* Advances a parsed link at each navigation state; `resolve` is the search to open. The first
82+
* Advances a parsed link at each navigation state; `resolve` is the link to apply. The first
8383
* state after the parse must hold the link's screen. A link that never lands there, or whose
84-
* screen is left while the shells settle, is dropped so it cannot open on a later visit.
84+
* screen is left before its target is ready, is dropped so it cannot apply on a later visit.
8585
*/
86-
export function stepPendingPromptLink(
87-
search: string,
88-
input: { readonly screenOnStack: boolean; readonly shellsSettled: boolean },
89-
): { readonly pending: string | null; readonly resolve: string | null } {
86+
export function stepPendingPromptLink<Link>(
87+
link: Link,
88+
input: { readonly screenOnStack: boolean; readonly ready: boolean },
89+
): { readonly pending: Link | null; readonly resolve: Link | null } {
9090
if (!input.screenOnStack) return { pending: null, resolve: null };
91-
if (input.shellsSettled) return { pending: null, resolve: search };
92-
return { pending: search, resolve: null };
91+
if (input.ready) return { pending: null, resolve: link };
92+
return { pending: link, resolve: null };
9393
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import type { NavigationState, PartialState } from "@react-navigation/native";
2+
import { Atom } from "effect/reactivity";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
5+
const fixture = vi.hoisted(() => ({
6+
applied: [] as { draftKey: string; text: string }[],
7+
root: undefined as NavigationState | undefined,
8+
}));
9+
10+
vi.mock("../../components/ui/Dialog", () => ({ alert: () => {} }));
11+
vi.mock("./prompt-link-actions", () => ({
12+
applyLinkedPromptToThreadDraft: async (draftKey: string, prompt: { text: string }) => {
13+
fixture.applied.push({ draftKey, text: prompt.text });
14+
},
15+
}));
16+
vi.mock("../../lib/rootNavigation", () => ({
17+
rootNavigationRef: { getRootState: () => fixture.root },
18+
}));
19+
vi.mock("../../state/atom-registry", async () => {
20+
const { AtomRegistry } = await import("effect/reactivity");
21+
return { appAtomRegistry: AtomRegistry.make() };
22+
});
23+
vi.mock("../../state/threads", async () => {
24+
const { Atom } = await import("effect/reactivity");
25+
const shell = Atom.make<object | null>(null);
26+
return { environmentThreadShells: { threadShellAtom: () => shell }, fixtureShell: shell };
27+
});
28+
29+
const { appAtomRegistry } = await import("../../state/atom-registry");
30+
const { fixtureShell } = (await import("../../state/threads")) as unknown as {
31+
fixtureShell: Atom.Writable<object | null>;
32+
};
33+
const { resolvePendingThreadPromptLink, takeThreadPromptLink } = await import("./threadPromptLink");
34+
35+
function setup() {
36+
fixture.applied.length = 0;
37+
fixture.root = undefined;
38+
appAtomRegistry.set(fixtureShell, null);
39+
}
40+
41+
const threadParams = { environmentId: "env-1", threadId: "thread-1" };
42+
43+
function linkedState(): PartialState<NavigationState> {
44+
return { routes: [{ name: "Thread", params: { ...threadParams, prompt: "Fix the bug" } }] };
45+
}
46+
47+
function stack(routes: NavigationState["routes"]): NavigationState {
48+
return {
49+
key: "root",
50+
index: routes.length - 1,
51+
routeNames: routes.map((route) => route.name),
52+
routes,
53+
stale: false,
54+
type: "stack",
55+
};
56+
}
57+
58+
const threadRoute = stack([{ key: "thread", name: "Thread", params: threadParams }]);
59+
60+
describe("takeThreadPromptLink", () => {
61+
it("writes no draft for a thread that never shows", () => {
62+
setup();
63+
takeThreadPromptLink(linkedState());
64+
expect(fixture.applied).toEqual([]);
65+
66+
resolvePendingThreadPromptLink(threadRoute);
67+
// An unknown thread's screen replaces itself with a new-thread draft.
68+
resolvePendingThreadPromptLink(
69+
stack([{ key: "draft", name: "Thread", params: { draft: { draftId: "d" } } }]),
70+
);
71+
appAtomRegistry.set(fixtureShell, { id: "thread-1" });
72+
expect(fixture.applied).toEqual([]);
73+
});
74+
75+
it("fills the draft once the linked thread shows on its screen", () => {
76+
setup();
77+
takeThreadPromptLink(linkedState());
78+
fixture.root = threadRoute;
79+
resolvePendingThreadPromptLink(threadRoute);
80+
expect(fixture.applied).toEqual([]);
81+
82+
appAtomRegistry.set(fixtureShell, { id: "thread-1" });
83+
expect(fixture.applied).toEqual([{ draftKey: expect.any(String), text: "Fix the bug" }]);
84+
appAtomRegistry.set(fixtureShell, { id: "thread-1", title: "renamed" });
85+
expect(fixture.applied).toHaveLength(1);
86+
});
87+
});

‎apps/mobile/src/features/prompt-links/threadPromptLink.ts‎

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,37 @@
11
import * as Dialog from "../../components/ui/Dialog";
22
import type { NavigationState, PartialState } from "@react-navigation/native";
3-
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4-
import { parseThreadLinkPrompt } from "@t3tools/shared/promptLinks";
3+
import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
4+
import { parseThreadLinkPrompt, type LinkedPrompt } from "@t3tools/shared/promptLinks";
55

6+
import { findStackRoute } from "../../lib/appLinking";
7+
import { rootNavigationRef } from "../../lib/rootNavigation";
68
import { scopedThreadKey } from "../../lib/scopedEntities";
9+
import { appAtomRegistry } from "../../state/atom-registry";
10+
import { environmentThreadShells } from "../../state/threads";
711
import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
8-
import { promptLinkNotice, promptLinkSearchFromParams } from "./prompt-link-model";
12+
import {
13+
promptLinkNotice,
14+
promptLinkSearchFromParams,
15+
stepPendingPromptLink,
16+
} from "./prompt-link-model";
917

1018
const THREAD_LINK_KEYS = ["prompt"];
1119

20+
type PendingThreadLink = { readonly ref: ScopedThreadRef; readonly prompt: LinkedPrompt };
21+
1222
function firstString(value: unknown): string | null {
1323
const first = Array.isArray(value) ? value[0] : value;
1424
return typeof first === "string" && first.length > 0 ? first : null;
1525
}
1626

27+
let pendingLink: PendingThreadLink | null = null;
28+
let stopWaitingForThread: (() => void) | null = null;
29+
1730
/**
18-
* `threads/<environment>/<thread>?prompt=…` fills that thread's composer draft.
19-
* The link applies the prompt as it arrives and drops the param, so the thread
20-
* screen never sees it and a later visit cannot apply it again.
31+
* `threads/<environment>/<thread>?prompt=…` fills that thread's composer draft. The param is
32+
* dropped as the link arrives, so the thread screen never sees it and a later visit cannot apply
33+
* it again. The draft is written only once the thread's screen shows a thread that exists: a
34+
* screen for an unknown thread replaces itself with a new-thread draft, which drops the link.
2135
*/
2236
export function takeThreadPromptLink(
2337
state: PartialState<NavigationState> | undefined,
@@ -41,12 +55,51 @@ export function takeThreadPromptLink(
4155
Dialog.alert("Could not open link", parsed.error);
4256
return nextState;
4357
}
58+
dropPendingLink();
4459
if (parsed.value !== null) {
60+
pendingLink = {
61+
ref: { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) },
62+
prompt: parsed.value,
63+
};
64+
}
65+
return nextState;
66+
}
67+
68+
/** Wired to the navigation container's state changes. */
69+
export function resolvePendingThreadPromptLink(state: NavigationState | undefined): void {
70+
if (pendingLink === null) return;
71+
const { ref } = pendingLink;
72+
// Every thread the screen can show gets a shell: for a subagent thread the environment's list
73+
// leaves out, the screen mounts its family, which adds it.
74+
const shellAtom = environmentThreadShells.threadShellAtom(ref);
75+
const step = stepPendingPromptLink(pendingLink, {
76+
screenOnStack:
77+
findStackRoute(
78+
state,
79+
"Thread",
80+
(params) =>
81+
firstString(params?.environmentId) === ref.environmentId &&
82+
firstString(params?.threadId) === ref.threadId,
83+
) !== undefined,
84+
ready: appAtomRegistry.get(shellAtom) !== null,
85+
});
86+
if (step.pending === null) dropPendingLink();
87+
if (step.resolve !== null) {
88+
const { prompt } = step.resolve;
4589
void applyLinkedPromptToThreadDraft(
46-
scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId)),
47-
parsed.value,
48-
promptLinkNotice({ hiddenCharacters: parsed.value.hiddenCharacters }),
90+
scopedThreadKey(ref.environmentId, ref.threadId),
91+
prompt,
92+
promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
4993
);
94+
} else if (step.pending !== null) {
95+
stopWaitingForThread ??= appAtomRegistry.subscribe(shellAtom, (shell) => {
96+
if (shell !== null) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
97+
});
5098
}
51-
return nextState;
99+
}
100+
101+
function dropPendingLink(): void {
102+
pendingLink = null;
103+
stopWaitingForThread?.();
104+
stopWaitingForThread = null;
52105
}

‎apps/mobile/src/lib/appLinking.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,29 @@ export function findLinkedRoute(
6161
}
6262

6363
/**
64-
* The last route named `name` at any depth of a live navigation state, with the key of the
65-
* navigator holding it, so an action can be dispatched as that screen would.
64+
* The last route named `name` (and accepted by `accept`, when given) at any depth of a live
65+
* navigation state, with the key of the navigator holding it, so an action can be dispatched as
66+
* that screen would.
6667
*/
6768
export function findStackRoute(
6869
state: NavigationState | undefined,
6970
name: string,
71+
accept?: (params: Readonly<Record<string, unknown>> | undefined) => boolean,
7072
): { readonly navigatorKey: string; readonly routeKey: string } | undefined {
7173
if (!state) return undefined;
7274
for (let index = state.routes.length - 1; index >= 0; index -= 1) {
7375
const route = state.routes[index]!;
74-
if (route.name === name) return { navigatorKey: state.key, routeKey: route.key };
76+
if (
77+
route.name === name &&
78+
(accept === undefined ||
79+
accept(route.params as Readonly<Record<string, unknown>> | undefined))
80+
) {
81+
return { navigatorKey: state.key, routeKey: route.key };
82+
}
7583
const nested = route.state;
7684
// Mounted navigators always have keys; a partial state from a link has not been mounted yet.
7785
if (typeof nested?.key === "string") {
78-
const found = findStackRoute(nested as NavigationState, name);
86+
const found = findStackRoute(nested as NavigationState, name, accept);
7987
if (found) return found;
8088
}
8189
}

0 commit comments

Comments
 (0)