@devries-cameron20 / t3code-1 / commits / 52925f9e98
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(mobile): prompt links resolve when the link is parsed, not from screen effects (#25820)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 02:49 UTC 52925f9e9895f0155f54a43087c15dc486fa182b
13 files changed +904 -421
apps/mobile/src/App.tsx
+17 -3
@@ -51,6 +51,14 @@ import { OverlayPortalHost } from "./components/ui/OverlayPortal";
51 import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
52 import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
53 import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
54 +import {
55 + resolvePendingNewTaskPromptLink,
56 + takeNewTaskPromptLink,
57 +} from "./features/prompt-links/newTaskPromptLink";
58 +import {
59 + resolvePendingThreadPromptLink,
60 + takeThreadPromptLink,
61 +} from "./features/prompt-links/threadPromptLink";
62 import {
63 disposeOnFoundationReplace,
64 type FoundationHotModule,
@@ -93,9 +101,13 @@ const linkingConfig = {
101
102 function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
103 return takeScheduledTaskNewLink(
96 - restoreSettingsLinkState(
97 - restoreDraftLinkState(getStateFromPath(path, options), path),
98 - settingsLinkPage(),
104 + takeNewTaskPromptLink(
105 + takeThreadPromptLink(
106 + restoreSettingsLinkState(
107 + restoreDraftLinkState(getStateFromPath(path, options), path),
108 + settingsLinkPage(),
109 + ),
110 + ),
111 ),
112 );
113 }
@@ -130,6 +142,8 @@ const Navigation = createStaticNavigation(RootStack);
142 function handleNavigationStateChange(state: NavigationState | undefined): void {
143 recordWorkspaceSelections(state);
144 presentPendingIncomingShare();
145 + resolvePendingNewTaskPromptLink(state);
146 + resolvePendingThreadPromptLink(state);
147 if (!state) return;
148 setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
149 recordAppShortcutNavigationState(state);
apps/mobile/src/features/prompt-links/newTaskPromptLink.ts new
+420
@@ -0,0 +1,420 @@
1 +import * as Dialog from "../../components/ui/Dialog";
2 +import {
3 + StackActions,
4 + type NavigationState,
5 + type PartialState,
6 + type StackActionType,
7 +} from "@react-navigation/native";
8 +import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
9 +import {
10 + findPromptLinkProjects,
11 + findPromptLinkPullRequestThread,
12 + resolvePromptLinkModelSelection,
13 +} from "@t3tools/client-runtime/prompt-links";
14 +import {
15 + executeAtomQuery,
16 + isAtomCommandInterrupted,
17 + runAtomCommand,
18 + squashAtomCommandFailure,
19 +} from "@t3tools/client-runtime/state/runtime";
20 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
21 +import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
22 +import {
23 + parseNewThreadLink,
24 + type LinkedPrompt,
25 + type PromptLinkPullRequest,
26 + type PromptLinkRepository,
27 +} from "@t3tools/shared/promptLinks";
28 +import { Atom, type AsyncResult } from "effect/reactivity";
29 +
30 +import { findLinkedRoute, findStackRoute, updateLinkedRoute } from "../../lib/appLinking";
31 +import { rootNavigationRef } from "../../lib/rootNavigation";
32 +import { scopedThreadKey } from "../../lib/scopedEntities";
33 +import { appAtomRegistry } from "../../state/atom-registry";
34 +import { environmentProjects, projectEnvironment } from "../../state/projects";
35 +import { composerPullRequests } from "../../state/pull-requests";
36 +import { environmentServerConfigsAtom } from "../../state/server";
37 +import { environmentThreadShells } from "../../state/threads";
38 +import {
39 + createNewTaskDraft,
40 + setComposerDraftText,
41 + updateComposerDraftSettings,
42 + waitForComposerDraftsLoaded,
43 +} from "../../state/use-composer-drafts";
44 +import { workspaceConnections, workspaceStateAtom } from "../../state/workspace";
45 +import { applyLinkedPromptToThreadDraft, showPromptLinkNotice } from "./prompt-link-actions";
46 +import {
47 + latestThreadEnvironmentIds,
48 + promptLinkNotice,
49 + promptLinkRepositoryName,
50 + promptLinkScratchEnvironmentId,
51 + promptLinkSearchFromParams,
52 + stepPendingPromptLink,
53 + withoutPromptLinkParams,
54 +} from "./prompt-link-model";
55 +
56 +// Found at any depth, both in the parsed link and on the live stack, so the two never disagree on
57 +// whether the link has landed.
58 +const NEW_TASK_ROUTE = "NewTaskProject";
59 +const NEW_TASK_ROUTES = [NEW_TASK_ROUTE];
60 +
61 +type LinkedDraftRequest = {
62 + readonly prompt: LinkedPrompt | null;
63 + readonly provider: string | null;
64 + readonly model: string | null;
65 + readonly pullRequest: PromptLinkPullRequest | null;
66 +};
67 +
68 +// A cold launch from a link has no projects or threads yet. Matching then would offer to clone a
69 +// repository the user already has.
70 +const shellsSettledAtom = Atom.make((get) => {
71 + const workspace = get(workspaceStateAtom);
72 + return !(
73 + workspace.isLoadingConnections ||
74 + workspace.hasPendingShellSnapshot ||
75 + // A machine still connecting may hold the repository or thread. One that keeps failing to
76 + // reconnect has settled offline, and must not hold every link.
77 + workspace.connectingEnvironments.some(
78 + (environment) =>
79 + environment.connectionState === "connecting" || environment.connectionError === null,
80 + )
81 + );
82 +}).pipe(Atom.withLabel("mobile:prompt-link-shells-settled"));
83 +
84 +let pendingLink: string | null = null;
85 +let stopWaitingForShells: (() => void) | null = null;
86 +
87 +/**
88 + * `new?prompt=…&repo=…` drops its params as it arrives, so the screen never sees them and each
89 + * opening resolves once. It resolves when its screen is on the navigation state that follows and
90 + * the shells have settled; a newer link replaces one still waiting.
91 + */
92 +export function takeNewTaskPromptLink(
93 + state: PartialState<NavigationState> | undefined,
94 +): PartialState<NavigationState> | undefined {
95 + const route = findLinkedRoute(state, NEW_TASK_ROUTES);
96 + const search = promptLinkSearchFromParams(
97 + route?.params as Readonly<Record<string, unknown>> | undefined,
98 + );
99 + if (search === null) return state;
100 + pendingLink = search;
101 + return updateLinkedRoute(state, NEW_TASK_ROUTES, (linked) => ({
102 + ...linked,
103 + params: withoutPromptLinkParams(linked.params),
104 + }));
105 +}
106 +
107 +/** Wired to the navigation container's state changes. */
108 +export function resolvePendingNewTaskPromptLink(state: NavigationState | undefined): void {
109 + if (pendingLink === null) return;
110 + const step = stepPendingPromptLink(pendingLink, {
111 + // A screen pushed above New task (such as Add project) drops the link, so it never lands
112 + // over the wrong screen.
113 + screenOnStack: findStackRoute(state, NEW_TASK_ROUTE)?.focused === true,
114 + ready: appAtomRegistry.get(shellsSettledAtom),
115 + });
116 + if (step.pending === null) dropPendingLink();
117 + else pendingLink = step.pending;
118 + if (step.resolve !== null) resolveLink(step.resolve);
119 + else if (step.pending !== null) {
120 + stopWaitingForShells ??= appAtomRegistry.subscribe(shellsSettledAtom, (settled) => {
121 + if (settled) resolvePendingNewTaskPromptLink(rootNavigationRef.getRootState());
122 + });
123 + }
124 +}
125 +
126 +function dropPendingLink(): void {
127 + pendingLink = null;
128 + stopWaitingForShells?.();
129 + stopWaitingForShells = null;
130 +}
131 +
132 +/** Dispatches as the new-task screen would, so `replace` swaps that screen out. */
133 +function dispatchFromNewTask(action: StackActionType): void {
134 + const root = rootNavigationRef.getRootState();
135 + const screen = findStackRoute(root, NEW_TASK_ROUTE);
136 + const target = screen?.navigatorKey ?? root?.key;
137 + rootNavigationRef.dispatch({
138 + ...action,
139 + ...(target ? { target } : {}),
140 + ...(screen ? { source: screen.routeKey } : {}),
141 + });
142 +}
143 +
144 +function runQuery<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
145 + return executeAtomQuery(appAtomRegistry, atom, {
146 + label: atom.label?.[0] ?? "atom query",
147 + reportFailure: false,
148 + });
149 +}
150 +
151 +function writeDraft(
152 + draftKey: string,
153 + environmentId: EnvironmentId,
154 + request: LinkedDraftRequest,
155 +): boolean {
156 + if (request.prompt) setComposerDraftText(draftKey, request.prompt.text);
157 + if (request.provider === null) return false;
158 + const resolved = resolvePromptLinkModelSelection(
159 + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.providers ?? [],
160 + { provider: request.provider, model: request.model },
161 + );
162 + if (resolved) updateComposerDraftSettings(draftKey, { modelSelection: resolved.selection });
163 + return resolved?.exact !== true;
164 +}
165 +
166 +function openThread(
167 + thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId },
168 + prompt: LinkedDraftRequest["prompt"],
169 +) {
170 + dispatchFromNewTask(
171 + StackActions.replace("Thread", {
172 + environmentId: String(thread.environmentId),
173 + threadId: String(thread.id),
174 + }),
175 + );
176 + if (prompt) {
177 + void applyLinkedPromptToThreadDraft(
178 + scopedThreadKey(thread.environmentId, thread.id),
179 + prompt,
180 + promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
181 + );
182 + }
183 +}
184 +
185 +// A pull request's thread can be an older settled thread no shell holds, so ask every
186 +// connected environment with the repository. A lookup on another one would wait forever.
187 +async function findServerPullRequestThread(
188 + projects: ReadonlyArray<EnvironmentProject>,
189 + pullRequest: PromptLinkPullRequest,
190 +) {
191 + const connected = new Set(
192 + appAtomRegistry
193 + .get(workspaceConnections.environmentsAtom)
194 + .filter((environment) => environment.connectionState === "connected")
195 + .map((environment) => environment.environmentId),
196 + );
197 + const lookups = projects
198 + .filter((project) => connected.has(project.environmentId))
199 + .map(async (project) => {
200 + const linked = await runQuery(
201 + composerPullRequests.linkedThreadsUncached({
202 + environmentId: project.environmentId,
203 + input: {
204 + projectId: project.id,
205 + repository: promptLinkRepositoryName(pullRequest),
206 + number: pullRequest.number,
207 + },
208 + }),
209 + );
210 + const thread =
211 + linked._tag === "Success"
212 + ? linked.value.threads.find((candidate) => candidate.archivedAt === null)
213 + : undefined;
214 + return thread && { environmentId: project.environmentId, id: thread.id };
215 + });
216 + // The most recent project wins without waiting for the lookups after it.
217 + for (const lookup of lookups) {
218 + const thread = await lookup;
219 + if (thread) return thread;
220 + }
221 + return undefined;
222 +}
223 +
224 +async function openProjectDraft(project: EnvironmentProject, request: LinkedDraftRequest) {
225 + try {
226 + await waitForComposerDraftsLoaded();
227 + } catch {
228 + Dialog.alert("Could not open link", "Drafts could not be loaded, so the prompt was not added.");
229 + return;
230 + }
231 + const draftKey = createNewTaskDraft({
232 + environmentId: project.environmentId,
233 + projectId: project.id,
234 + });
235 + let pullRequestUnavailable: number | null = null;
236 + if (request.pullRequest) {
237 + const detail = await runQuery(
238 + composerPullRequests.detail({
239 + environmentId: project.environmentId,
240 + input: {
241 + projectId: project.id,
242 + repository: promptLinkRepositoryName(request.pullRequest),
243 + number: request.pullRequest.number,
244 + },
245 + }),
246 + );
247 + if (detail._tag === "Success") {
248 + updateComposerDraftSettings(draftKey, {
249 + workspaceSelection: {
250 + mode: "worktree",
251 + branch: detail.value.headBranch,
252 + worktreePath: null,
253 + startFromOrigin: false,
254 + pullRequestReference: detail.value.url,
255 + },
256 + });
257 + } else {
258 + pullRequestUnavailable = request.pullRequest.number;
259 + }
260 + }
261 + const modelUnavailable = writeDraft(draftKey, project.environmentId, request);
262 + dispatchFromNewTask(
263 + StackActions.push("Thread", {
264 + draft: {
265 + draftId: draftKey,
266 + title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
267 + },
268 + }),
269 + );
270 + if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {
271 + showPromptLinkNotice(
272 + promptLinkNotice({
273 + hiddenCharacters: request.prompt?.hiddenCharacters ?? 0,
274 + modelUnavailable,
275 + pullRequestUnavailable,
276 + }),
277 + );
278 + }
279 +}
280 +
281 +async function openScratchDraft(request: LinkedDraftRequest) {
282 + const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
283 + const environmentId = promptLinkScratchEnvironmentId(
284 + latestThreadEnvironmentIds(appAtomRegistry.get(environmentThreadShells.threadShellsAtom)),
285 + appAtomRegistry
286 + .get(workspaceConnections.environmentsAtom)
287 + .filter(
288 + (environment) =>
289 + availableScratchWorkspaceRoot(
290 + environment.connectionState,
291 + serverConfigs.get(environment.environmentId),
292 + ) !== null,
293 + )
294 + .map((environment) => environment.environmentId),
295 + );
296 + if (environmentId === null) {
297 + Dialog.alert(
298 + "Could not start without a project",
299 + "No connected environment offers threads without a project.",
300 + );
301 + return;
302 + }
303 + const result = await runAtomCommand(
304 + appAtomRegistry,
305 + projectEnvironment.openScratch,
306 + { environmentId, input: {} },
307 + { reportFailure: false },
308 + );
309 + if (result._tag === "Failure") {
310 + if (!isAtomCommandInterrupted(result)) {
311 + const error = squashAtomCommandFailure(result);
312 + Dialog.alert(
313 + "Could not start without a project",
314 + error instanceof Error
315 + ? error.message
316 + : "The folder for threads without a project could not be created.",
317 + );
318 + }
319 + return;
320 + }
321 + await openProjectDraft(result.value, { ...request, pullRequest: null });
322 +}
323 +
324 +function cloneRepository(repository: PromptLinkRepository, request: LinkedDraftRequest) {
325 + // The clone screen lets the user pick another environment before cloning.
326 + const environmentId =
327 + appAtomRegistry.get(environmentProjects.projectsAtom)[0]?.environmentId ??
328 + appAtomRegistry.get(workspaceConnections.environmentsAtom)[0]?.environmentId ??
329 + null;
330 + if (environmentId === null) {
331 + Dialog.alert("Could not clone", "Connect an environment first.");
332 + return;
333 + }
334 + const prompt =
335 + request.pullRequest === null &&
336 + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
337 + .projectCloneTracking === true
338 + ? request.prompt
339 + : null;
340 + const name = promptLinkRepositoryName(repository);
341 + dispatchFromNewTask(
342 + StackActions.push("AddProjectDestination", {
343 + environmentId,
344 + remoteUrl: `https://github.com/${name}.git`,
345 + repositoryTitle: name,
346 + repositoryName: repository.name,
347 + ...(prompt ? { prompt: prompt.text } : {}),
348 + }),
349 + );
350 + if (!request.prompt) return;
351 + showPromptLinkNotice(
352 + [
353 + promptLinkNotice({
354 + hiddenCharacters: request.prompt.hiddenCharacters,
355 + modelUnavailable: prompt !== null && request.provider !== null,
356 + }),
357 + prompt
358 + ? "The prompt opens in a new task once the clone starts."
359 + : "Open the link again after the clone to get the prompt.",
360 + ].join("\n\n"),
361 + );
362 +}
363 +
364 +function resolveLink(linkSearch: string) {
365 + const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
366 + const parsed = parseNewThreadLink(linkSearch);
367 + if (!parsed.ok) {
368 + Dialog.alert("Could not open link", parsed.error);
369 + return;
370 + }
371 + const link = parsed.value;
372 + const request: LinkedDraftRequest =
373 + link.kind === "new"
374 + ? { prompt: link.prompt, provider: link.provider, model: link.model, pullRequest: null }
375 + : { prompt: link.prompt, provider: null, model: null, pullRequest: link.pullRequest };
376 +
377 + if (link.kind === "pull-request") {
378 + const thread = findPromptLinkPullRequestThread(threads, link.pullRequest);
379 + if (thread) {
380 + openThread(thread, link.prompt);
381 + return;
382 + }
383 + }
384 +
385 + const repository = link.kind === "new" ? link.repository : link.pullRequest;
386 + if (repository === null) {
387 + void openScratchDraft(request);
388 + return;
389 + }
390 + const lastActivity = new Map<string, string>();
391 + for (const thread of threads) {
392 + const key = `${thread.environmentId}:${thread.projectId}`;
393 + if (thread.updatedAt > (lastActivity.get(key) ?? "")) lastActivity.set(key, thread.updatedAt);
394 + }
395 + const activityOf = (project: EnvironmentProject) =>
396 + lastActivity.get(`${project.environmentId}:${project.id}`) ?? "";
397 + const projects = findPromptLinkProjects(
398 + [...appAtomRegistry.get(environmentProjects.projectsAtom)].sort((left, right) =>
399 + activityOf(right).localeCompare(activityOf(left)),
400 + ),
401 + repository,
402 + );
403 + const project = projects[0];
404 + if (project) {
405 + const { pullRequest } = request;
406 + void (async () => {
407 + const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest));
408 + if (thread) openThread(thread, request.prompt);
409 + else await openProjectDraft(project, request);
410 + })();
411 + return;
412 + }
413 + Dialog.alert(`You don't have ${promptLinkRepositoryName(repository)}`, undefined, [
414 + { text: "Cancel", style: "cancel" },
415 + ...(request.prompt
416 + ? [{ text: "Use without project", onPress: () => void openScratchDraft(request) }]
417 + : []),
418 + { text: "Clone", onPress: () => cloneRepository(repository, request) },
419 + ]);
420 +}
apps/mobile/src/features/prompt-links/prompt-link-model.test.ts
+42 -1
@@ -1,7 +1,11 @@
1 import { parseNewThreadLink } from "@t3tools/shared/promptLinks";
2 import { describe, expect, it } from "vite-plus/test";
3
4 -import { promptLinkSearchFromParams } from "./prompt-link-model";
4 +import {
5 + promptLinkSearchFromParams,
6 + stepPendingPromptLink,
7 + withoutPromptLinkParams,
8 +} from "./prompt-link-model";
9
10 describe("promptLinkSearchFromParams", () => {
11 it("round-trips decoded route params into the shared parser", () => {
@@ -24,3 +28,40 @@ describe("promptLinkSearchFromParams", () => {
28 });
29 });
30 });
31 +
32 +describe("stepPendingPromptLink", () => {
33 + const waiting = "repo=t3tools%2Ft3code";
34 +
35 + it("drops a link whose screen is missing from the first state after it was parsed", () => {
36 + expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: true })).toEqual({
37 + pending: null,
38 + resolve: null,
39 + });
40 + });
41 +
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({
44 + pending: waiting,
45 + resolve: null,
46 + });
47 + expect(stepPendingPromptLink(waiting, { screenOnStack: true, ready: true })).toEqual({
48 + pending: null,
49 + resolve: waiting,
50 + });
51 + });
52 +
53 + it("drops a link whose screen was left before its target was ready", () => {
54 + expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: false })).toEqual({
55 + pending: null,
56 + resolve: null,
57 + });
58 + });
59 +});
60 +
61 +describe("withoutPromptLinkParams", () => {
62 + it("keeps the route's other params", () => {
63 + expect(withoutPromptLinkParams({ prompt: "hi", repo: "a/b", incomingShareId: "1" })).toEqual({
64 + incomingShareId: "1",
65 + });
66 + });
67 +});
apps/mobile/src/features/prompt-links/prompt-link-model.ts
+20 -2
@@ -17,8 +17,12 @@ export function promptLinkSearchFromParams(
17 return search.size > 0 ? search.toString() : null;
18 }
19
20 -export function clearedPromptLinkParams(keys: ReadonlyArray<string> = PROMPT_LINK_PARAM_KEYS) {
21 - return Object.fromEntries(keys.map((key) => [key, undefined]));
20 +export function withoutPromptLinkParams(params: object | undefined): Record<string, unknown> {
21 + return Object.fromEntries(
22 + Object.entries(params ?? {}).filter(
23 + ([key]) => !(PROMPT_LINK_PARAM_KEYS as ReadonlyArray<string>).includes(key),
24 + ),
25 + );
26 }
27
28 export function promptLinkNotice(input: {
@@ -73,3 +77,17 @@ export function latestThreadEnvironmentIds<Id extends string>(
77
78 export const promptLinkRepositoryName = (repository: PromptLinkRepository) =>
79 `${repository.owner}/${repository.name}`;
80 +
81 +/**
82 + * Advances a parsed link at each navigation state; `resolve` is the link to apply. The first
83 + * state after the parse must hold the link's screen. A link that never lands there, or whose
84 + * screen is left before its target is ready, is dropped so it cannot apply on a later visit.
85 + */
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 } {
90 + if (!input.screenOnStack) return { pending: null, resolve: null };
91 + if (input.ready) return { pending: null, resolve: link };
92 + return { pending: link, resolve: null };
93 +}
apps/mobile/src/features/prompt-links/threadPromptLink.test.ts new
+144
@@ -0,0 +1,144 @@
1 +import type { NavigationState, PartialState } from "@react-navigation/native";
2 +import * as Option from "effect/Option";
3 +import { AsyncResult, Atom } from "effect/reactivity";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 +
6 +const fixture = vi.hoisted(() => ({
7 + applied: [] as { draftKey: string; text: string }[],
8 + root: undefined as NavigationState | undefined,
9 + detailOpens: 0,
10 +}));
11 +
12 +vi.mock("../../components/ui/Dialog", () => ({ alert: () => {} }));
13 +vi.mock("./prompt-link-actions", () => ({
14 + applyLinkedPromptToThreadDraft: async (draftKey: string, prompt: { text: string }) => {
15 + fixture.applied.push({ draftKey, text: prompt.text });
16 + },
17 +}));
18 +vi.mock("../../lib/rootNavigation", () => ({
19 + rootNavigationRef: { getRootState: () => fixture.root },
20 +}));
21 +vi.mock("../../state/atom-registry", async () => {
22 + const { AtomRegistry } = await import("effect/reactivity");
23 + return { appAtomRegistry: AtomRegistry.make() };
24 +});
25 +vi.mock("../../state/threads", async () => {
26 + const { AsyncResult, Atom } = await import("effect/reactivity");
27 + const Option = await import("effect/Option");
28 + const shell = Atom.make<object | null>(null);
29 + const detailSource = Atom.make(AsyncResult.success({ data: Option.none() }));
30 + // Computing the real detail atom opens the thread's server stream.
31 + const detail = Atom.make((get) => {
32 + fixture.detailOpens += 1;
33 + return get(detailSource);
34 + });
35 + return {
36 + environmentThreadShells: { threadShellAtom: () => shell },
37 + environmentThreads: { stateAtom: () => detail },
38 + fixtureShell: shell,
39 + fixtureDetail: detail,
40 + fixtureDetailSource: detailSource,
41 + };
42 +});
43 +
44 +const { appAtomRegistry } = await import("../../state/atom-registry");
45 +const { fixtureDetail, fixtureDetailSource, fixtureShell } =
46 + (await import("../../state/threads")) as unknown as {
47 + fixtureShell: Atom.Writable<object | null>;
48 + fixtureDetail: Atom.Atom<unknown>;
49 + fixtureDetailSource: Atom.Writable<AsyncResult.AsyncResult<{ data: Option.Option<object> }>>;
50 + };
51 +const { resolvePendingThreadPromptLink, takeThreadPromptLink } = await import("./threadPromptLink");
52 +
53 +function setup() {
54 + fixture.applied.length = 0;
55 + fixture.root = undefined;
56 + appAtomRegistry.reset();
57 + appAtomRegistry.set(fixtureShell, null);
58 + appAtomRegistry.set(fixtureDetailSource, AsyncResult.success({ data: Option.none() }));
59 + fixture.detailOpens = 0;
60 +}
61 +
62 +const loadedDetail = AsyncResult.success({ data: Option.some({}) });
63 +
64 +const threadParams = { environmentId: "env-1", threadId: "thread-1" };
65 +
66 +function linkedState(prompt = "Fix the bug"): PartialState<NavigationState> {
67 + return { routes: [{ name: "Thread", params: { ...threadParams, prompt } }] };
68 +}
69 +
70 +function stack(routes: NavigationState["routes"]): NavigationState {
71 + return {
72 + key: "root",
73 + index: routes.length - 1,
74 + routeNames: routes.map((route) => route.name),
75 + routes,
76 + stale: false,
77 + type: "stack",
78 + };
79 +}
80 +
81 +const threadRoute = stack([{ key: "thread", name: "Thread", params: threadParams }]);
82 +
83 +describe("takeThreadPromptLink", () => {
84 + it("writes no draft for a thread that never shows", () => {
85 + setup();
86 + takeThreadPromptLink(linkedState());
87 + expect(fixture.applied).toEqual([]);
88 +
89 + resolvePendingThreadPromptLink(threadRoute);
90 + // An unknown thread's screen replaces itself with a new-thread draft.
91 + resolvePendingThreadPromptLink(
92 + stack([{ key: "draft", name: "Thread", params: { draft: { draftId: "d" } } }]),
93 + );
94 + appAtomRegistry.set(fixtureShell, { id: "thread-1" });
95 + expect(fixture.applied).toEqual([]);
96 + });
97 +
98 + it("fills the draft once the linked thread shows on its screen", () => {
99 + setup();
100 + takeThreadPromptLink(linkedState());
101 + fixture.root = threadRoute;
102 + resolvePendingThreadPromptLink(threadRoute);
103 + expect(fixture.applied).toEqual([]);
104 +
105 + appAtomRegistry.set(fixtureShell, { id: "thread-1" });
106 + expect(fixture.applied).toEqual([{ draftKey: expect.any(String), text: "Fix the bug" }]);
107 + appAtomRegistry.set(fixtureShell, { id: "thread-1", title: "renamed" });
108 + expect(fixture.applied).toHaveLength(1);
109 + });
110 +
111 + it("fills the draft of an archived thread its screen shows from detail", () => {
112 + setup();
113 + takeThreadPromptLink(linkedState());
114 + fixture.root = threadRoute;
115 + // Archived threads have no shell; the open screen subscribes to their detail instead.
116 + using _screen = { [Symbol.dispose]: appAtomRegistry.mount(fixtureDetail) };
117 + resolvePendingThreadPromptLink(threadRoute);
118 + expect(fixture.applied).toEqual([]);
119 +
120 + appAtomRegistry.set(fixtureDetailSource, loadedDetail);
121 + expect(fixture.applied).toEqual([{ draftKey: expect.any(String), text: "Fix the bug" }]);
122 + });
123 +
124 + it("opens no detail for a thread no screen has loaded", () => {
125 + setup();
126 + takeThreadPromptLink(linkedState());
127 + fixture.root = threadRoute;
128 + resolvePendingThreadPromptLink(threadRoute);
129 + appAtomRegistry.set(fixtureDetailSource, loadedDetail);
130 + expect(fixture.detailOpens).toBe(0);
131 + expect(fixture.applied).toEqual([]);
132 + resolvePendingThreadPromptLink(stack([{ key: "home", name: "Home" }]));
133 + });
134 +
135 + it("drops an earlier link to the thread when a newer one is invalid", () => {
136 + setup();
137 + takeThreadPromptLink(linkedState());
138 + takeThreadPromptLink(linkedState("\u200b"));
139 + fixture.root = threadRoute;
140 + resolvePendingThreadPromptLink(threadRoute);
141 + appAtomRegistry.set(fixtureShell, { id: "thread-1" });
142 + expect(fixture.applied).toEqual([]);
143 + });
144 +});
apps/mobile/src/features/prompt-links/threadPromptLink.ts new
+128
@@ -0,0 +1,128 @@
1 +import * as Dialog from "../../components/ui/Dialog";
2 +import type { NavigationState, PartialState } from "@react-navigation/native";
3 +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
4 +import { parseThreadLinkPrompt, type LinkedPrompt } from "@t3tools/shared/promptLinks";
5 +import * as Option from "effect/Option";
6 +import { AsyncResult } from "effect/reactivity";
7 +
8 +import { findStackRoute } from "../../lib/appLinking";
9 +import { rootNavigationRef } from "../../lib/rootNavigation";
10 +import { scopedThreadKey } from "../../lib/scopedEntities";
11 +import { appAtomRegistry } from "../../state/atom-registry";
12 +import { environmentThreadShells, environmentThreads } from "../../state/threads";
13 +import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
14 +import {
15 + promptLinkNotice,
16 + promptLinkSearchFromParams,
17 + stepPendingPromptLink,
18 +} from "./prompt-link-model";
19 +
20 +const THREAD_LINK_KEYS = ["prompt"];
21 +
22 +type PendingThreadLink = { readonly ref: ScopedThreadRef; readonly prompt: LinkedPrompt };
23 +
24 +function firstString(value: unknown): string | null {
25 + const first = Array.isArray(value) ? value[0] : value;
26 + return typeof first === "string" && first.length > 0 ? first : null;
27 +}
28 +
29 +let pendingLink: PendingThreadLink | null = null;
30 +let stopWaitingForShell: (() => void) | null = null;
31 +let stopWaitingForDetail: (() => void) | null = null;
32 +
33 +/**
34 + * `threads/<environment>/<thread>?prompt=…` fills that thread's composer draft. The param is
35 + * dropped as the link arrives, so the thread screen never sees it and a later visit cannot apply
36 + * it again. The draft is written only once the thread's screen shows a thread that exists: a
37 + * screen for an unknown thread replaces itself with a new-thread draft, which drops the link.
38 + */
39 +export function takeThreadPromptLink(
40 + state: PartialState<NavigationState> | undefined,
41 +): PartialState<NavigationState> | undefined {
42 + if (!state) return state;
43 + const index = state.routes.findIndex((route) => route.name === "Thread");
44 + const route = state.routes[index];
45 + const params = route?.params as Readonly<Record<string, unknown>> | undefined;
46 + const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS);
47 + if (!route || !params || search === null) return state;
48 + // A newer link replaces a waiting one even when it turns out to be invalid.
49 + dropPendingLink();
50 + const { prompt: _prompt, ...rest } = params;
51 + const routes = state.routes.slice();
52 + routes[index] = { ...route, params: rest };
53 + const nextState = { ...state, routes };
54 +
55 + const environmentId = firstString(params.environmentId);
56 + const threadId = firstString(params.threadId);
57 + if (environmentId === null || threadId === null) return nextState;
58 + const parsed = parseThreadLinkPrompt(search);
59 + if (!parsed.ok) {
60 + Dialog.alert("Could not open link", parsed.error);
61 + return nextState;
62 + }
63 + if (parsed.value !== null) {
64 + pendingLink = {
65 + ref: { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) },
66 + prompt: parsed.value,
67 + };
68 + }
69 + return nextState;
70 +}
71 +
72 +/** Wired to the navigation container's state changes. */
73 +export function resolvePendingThreadPromptLink(state: NavigationState | undefined): void {
74 + if (pendingLink === null) return;
75 + const { ref } = pendingLink;
76 + // A subagent thread the environment's list leaves out gets a shell once the screen mounts its
77 + // family. An archived thread never does; the screen shows it from its detail.
78 + const shellAtom = environmentThreadShells.threadShellAtom(ref);
79 + const detailAtom = environmentThreads.stateAtom(ref.environmentId, ref.threadId);
80 + // Read detail only while the screen holds it: opening it here for an unknown thread would keep
81 + // retrying with no screen to close it.
82 + const screenHoldsDetail = appAtomRegistry.getNodes().has(detailAtom);
83 + const step = stepPendingPromptLink(pendingLink, {
84 + screenOnStack:
85 + findStackRoute(
86 + state,
87 + "Thread",
88 + (params) =>
89 + firstString(params?.environmentId) === ref.environmentId &&
90 + firstString(params?.threadId) === ref.threadId,
91 + ) !== undefined,
92 + ready:
93 + appAtomRegistry.get(shellAtom) !== null ||
94 + (screenHoldsDetail && detailLoaded(appAtomRegistry.get(detailAtom))),
95 + });
96 + if (step.pending === null) dropPendingLink();
97 + if (step.resolve !== null) {
98 + const { prompt } = step.resolve;
99 + void applyLinkedPromptToThreadDraft(
100 + scopedThreadKey(ref.environmentId, ref.threadId),
101 + prompt,
102 + promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
103 + );
104 + } else if (step.pending !== null) {
105 + stopWaitingForShell ??= appAtomRegistry.subscribe(shellAtom, (shell) => {
106 + if (shell !== null) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
107 + });
108 + if (screenHoldsDetail) {
109 + stopWaitingForDetail ??= appAtomRegistry.subscribe(detailAtom, (detail) => {
110 + if (detailLoaded(detail)) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
111 + });
112 + }
113 + }
114 +}
115 +
116 +function detailLoaded(
117 + result: AsyncResult.AsyncResult<{ readonly data: Option.Option<unknown> }, unknown>,
118 +): boolean {
119 + return Option.isSome(Option.flatMap(AsyncResult.value(result), (state) => state.data));
120 +}
121 +
122 +function dropPendingLink(): void {
123 + pendingLink = null;
124 + stopWaitingForShell?.();
125 + stopWaitingForShell = null;
126 + stopWaitingForDetail?.();
127 + stopWaitingForDetail = null;
128 +}
apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts deleted
-348
@@ -1,348 +0,0 @@
1 -import * as Dialog from "../../components/ui/Dialog";
2 -import { StackActions, useNavigation } from "@react-navigation/native";
3 -import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
4 -import {
5 - findPromptLinkProjects,
6 - findPromptLinkPullRequestThread,
7 - resolvePromptLinkModelSelection,
8 -} from "@t3tools/client-runtime/prompt-links";
9 -import {
10 - isAtomCommandInterrupted,
11 - squashAtomCommandFailure,
12 -} from "@t3tools/client-runtime/state/runtime";
13 -import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
14 -import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
15 -import {
16 - parseNewThreadLink,
17 - type LinkedPrompt,
18 - type PromptLinkPullRequest,
19 - type PromptLinkRepository,
20 -} from "@t3tools/shared/promptLinks";
21 -import { useEffect, useEffectEvent, useRef } from "react";
22 -
23 -import { scopedThreadKey } from "../../lib/scopedEntities";
24 -import { useServerConfigs, useThreadShells } from "../../state/entities";
25 -import { projectEnvironment } from "../../state/projects";
26 -import { composerPullRequests } from "../../state/pull-requests";
27 -import { useAtomCommand } from "../../state/use-atom-command";
28 -import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
29 -import {
30 - createNewTaskDraft,
31 - setComposerDraftText,
32 - updateComposerDraftSettings,
33 - waitForComposerDraftsLoaded,
34 -} from "../../state/use-composer-drafts";
35 -import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
36 -import { useWorkspaceState } from "../../state/workspace";
37 -import { useNewTaskFlow } from "../threads/new-task-flow-provider";
38 -import { applyLinkedPromptToThreadDraft, showPromptLinkNotice } from "./prompt-link-actions";
39 -import {
40 - clearedPromptLinkParams,
41 - promptLinkNotice,
42 - promptLinkRepositoryName,
43 - latestThreadEnvironmentIds,
44 - promptLinkScratchEnvironmentId,
45 - promptLinkSearchFromParams,
46 -} from "./prompt-link-model";
47 -
48 -type LinkedDraftRequest = {
49 - readonly prompt: LinkedPrompt | null;
50 - readonly provider: string | null;
51 - readonly model: string | null;
52 - readonly pullRequest: PromptLinkPullRequest | null;
53 -};
54 -
55 -export function usePromptLinkResolver(params: Readonly<Record<string, unknown>> | undefined) {
56 - const navigation = useNavigation();
57 - const flow = useNewTaskFlow();
58 - const { state: catalogState } = useWorkspaceState();
59 - const threads = useThreadShells();
60 - const serverConfigs = useServerConfigs();
61 - const { connectedEnvironments } = useRemoteConnectionStatus();
62 - const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
63 - const loadPullRequest = useAtomQueryRunner(composerPullRequests.detail, {
64 - reportFailure: false,
65 - });
66 - const loadLinkedThreads = useAtomQueryRunner(composerPullRequests.linkedThreadsUncached, {
67 - reportFailure: false,
68 - });
69 - const search = promptLinkSearchFromParams(params);
70 - // Wait for cold-launch shells or existing repositories may be offered for cloning.
71 - const waitingForShells =
72 - catalogState.isLoadingConnections ||
73 - catalogState.hasPendingShellSnapshot ||
74 - // Connecting machines may hold the target; persistently offline ones must not block every link.
75 - catalogState.connectingEnvironments.some(
76 - (environment) =>
77 - environment.connectionState === "connecting" || environment.connectionError === null,
78 - );
79 -
80 - const writeDraft = (
81 - draftKey: string,
82 - environmentId: EnvironmentId,
83 - request: LinkedDraftRequest,
84 - ): boolean => {
85 - if (request.prompt) setComposerDraftText(draftKey, request.prompt.text);
86 - if (request.provider === null) return false;
87 - const resolved = resolvePromptLinkModelSelection(
88 - serverConfigs.get(environmentId)?.providers ?? [],
89 - { provider: request.provider, model: request.model },
90 - );
91 - if (resolved) updateComposerDraftSettings(draftKey, { modelSelection: resolved.selection });
92 - return resolved?.exact !== true;
93 - };
94 -
95 - const openThread = (
96 - thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId },
97 - prompt: LinkedDraftRequest["prompt"],
98 - ) => {
99 - (navigation.getParent() ?? navigation).dispatch(
100 - StackActions.replace("Thread", {
101 - environmentId: String(thread.environmentId),
102 - threadId: String(thread.id),
103 - }),
104 - );
105 - if (prompt) {
106 - void applyLinkedPromptToThreadDraft(
107 - scopedThreadKey(thread.environmentId, thread.id),
108 - prompt,
109 - promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
110 - );
111 - }
112 - };
113 -
114 - // A pull request's thread can be an older settled thread no shell holds, so ask every
115 - // connected environment with the repository. A lookup on another one would wait forever.
116 - const findServerPullRequestThread = async (
117 - projects: ReadonlyArray<EnvironmentProject>,
118 - pullRequest: PromptLinkPullRequest,
119 - ) => {
120 - const connected = new Set(
121 - connectedEnvironments
122 - .filter((environment) => environment.connectionState === "connected")
123 - .map((environment) => environment.environmentId),
124 - );
125 - const lookups = projects
126 - .filter((project) => connected.has(project.environmentId))
127 - .map(async (project) => {
128 - const linked = await loadLinkedThreads({
129 - environmentId: project.environmentId,
130 - input: {
131 - projectId: project.id,
132 - repository: promptLinkRepositoryName(pullRequest),
133 - number: pullRequest.number,
134 - },
135 - });
136 - const thread =
137 - linked._tag === "Success"
138 - ? linked.value.threads.find((candidate) => candidate.archivedAt === null)
139 - : undefined;
140 - return thread && { environmentId: project.environmentId, id: thread.id };
141 - });
142 - // The most recent project wins without waiting for the lookups after it.
143 - for (const lookup of lookups) {
144 - const thread = await lookup;
145 - if (thread) return thread;
146 - }
147 - return undefined;
148 - };
149 -
150 - const openProjectDraft = async (project: EnvironmentProject, request: LinkedDraftRequest) => {
151 - try {
152 - await waitForComposerDraftsLoaded();
153 - } catch {
154 - Dialog.alert(
155 - "Could not open link",
156 - "Drafts could not be loaded, so the prompt was not added.",
157 - );
158 - return;
159 - }
160 - const draftKey = createNewTaskDraft({
161 - environmentId: project.environmentId,
162 - projectId: project.id,
163 - });
164 - let pullRequestUnavailable: number | null = null;
165 - if (request.pullRequest) {
166 - const detail = await loadPullRequest({
167 - environmentId: project.environmentId,
168 - input: {
169 - projectId: project.id,
170 - repository: promptLinkRepositoryName(request.pullRequest),
171 - number: request.pullRequest.number,
172 - },
173 - });
174 - if (detail._tag === "Success") {
175 - updateComposerDraftSettings(draftKey, {
176 - workspaceSelection: {
177 - mode: "worktree",
178 - branch: detail.value.headBranch,
179 - worktreePath: null,
180 - startFromOrigin: false,
181 - pullRequestReference: detail.value.url,
182 - },
183 - });
184 - } else {
185 - pullRequestUnavailable = request.pullRequest.number;
186 - }
187 - }
188 - const modelUnavailable = writeDraft(draftKey, project.environmentId, request);
189 - navigation.dispatch(
190 - StackActions.push("Thread", {
191 - draft: {
192 - draftId: draftKey,
193 - title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
194 - },
195 - }),
196 - );
197 - if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {
198 - showPromptLinkNotice(
199 - promptLinkNotice({
200 - hiddenCharacters: request.prompt?.hiddenCharacters ?? 0,
201 - modelUnavailable,
202 - pullRequestUnavailable,
203 - }),
204 - );
205 - }
206 - };
207 -
208 - const openScratchDraft = async (request: LinkedDraftRequest) => {
209 - const environmentId = promptLinkScratchEnvironmentId(
210 - latestThreadEnvironmentIds(threads),
211 - connectedEnvironments
212 - .filter(
213 - (environment) =>
214 - availableScratchWorkspaceRoot(
215 - environment.connectionState,
216 - serverConfigs.get(environment.environmentId),
217 - ) !== null,
218 - )
219 - .map((environment) => environment.environmentId),
220 - );
221 - if (environmentId === null) {
222 - Dialog.alert(
223 - "Could not start without a project",
224 - "No connected environment offers threads without a project.",
225 - );
226 - return;
227 - }
228 - const result = await openScratch({ environmentId, input: {} });
229 - if (result._tag === "Failure") {
230 - if (!isAtomCommandInterrupted(result)) {
231 - const error = squashAtomCommandFailure(result);
232 - Dialog.alert(
233 - "Could not start without a project",
234 - error instanceof Error
235 - ? error.message
236 - : "The folder for threads without a project could not be created.",
237 - );
238 - }
239 - return;
240 - }
241 - await openProjectDraft(result.value, { ...request, pullRequest: null });
242 - };
243 -
244 - const cloneRepository = (repository: PromptLinkRepository, request: LinkedDraftRequest) => {
245 - const environmentId =
246 - flow.selectedEnvironmentId ?? connectedEnvironments[0]?.environmentId ?? null;
247 - if (environmentId === null) {
248 - Dialog.alert("Could not clone", "Connect an environment first.");
249 - return;
250 - }
251 - const prompt =
252 - request.pullRequest === null &&
253 - serverConfigs.get(environmentId)?.environment.capabilities.projectCloneTracking === true
254 - ? request.prompt
255 - : null;
256 - const name = promptLinkRepositoryName(repository);
257 - navigation.dispatch(
258 - StackActions.push("AddProjectDestination", {
259 - environmentId,
260 - remoteUrl: `https://github.com/${name}.git`,
261 - repositoryTitle: name,
262 - repositoryName: repository.name,
263 - ...(prompt ? { prompt: prompt.text } : {}),
264 - }),
265 - );
266 - if (!request.prompt) return;
267 - showPromptLinkNotice(
268 - [
269 - promptLinkNotice({
270 - hiddenCharacters: request.prompt.hiddenCharacters,
271 - modelUnavailable: prompt !== null && request.provider !== null,
272 - }),
273 - prompt
274 - ? "The prompt opens in a new task once the clone starts."
275 - : "Open the link again after the clone to get the prompt.",
276 - ].join("\n\n"),
277 - );
278 - };
279 -
280 - const resolveLink = useEffectEvent((linkSearch: string) => {
281 - const parsed = parseNewThreadLink(linkSearch);
282 - if (!parsed.ok) {
283 - Dialog.alert("Could not open link", parsed.error);
284 - return;
285 - }
286 - const link = parsed.value;
287 - const request: LinkedDraftRequest =
288 - link.kind === "new"
289 - ? { prompt: link.prompt, provider: link.provider, model: link.model, pullRequest: null }
290 - : { prompt: link.prompt, provider: null, model: null, pullRequest: link.pullRequest };
291 -
292 - if (link.kind === "pull-request") {
293 - const thread = findPromptLinkPullRequestThread(threads, link.pullRequest);
294 - if (thread) {
295 - openThread(thread, link.prompt);
296 - return;
297 - }
298 - }
299 -
300 - const repository = link.kind === "new" ? link.repository : link.pullRequest;
301 - if (repository === null) {
302 - void openScratchDraft(request);
303 - return;
304 - }
305 - const lastActivity = new Map<string, string>();
306 - for (const thread of threads) {
307 - const key = `${thread.environmentId}:${thread.projectId}`;
308 - if (thread.updatedAt > (lastActivity.get(key) ?? "")) lastActivity.set(key, thread.updatedAt);
309 - }
310 - const activityOf = (project: EnvironmentProject) =>
311 - lastActivity.get(`${project.environmentId}:${project.id}`) ?? "";
312 - const projects = findPromptLinkProjects(
313 - flow.projectScopes
314 - .flatMap((scope) => scope.projects)
315 - .sort((left, right) => activityOf(right).localeCompare(activityOf(left))),
316 - repository,
317 - );
318 - const project = projects[0];
319 - if (project) {
320 - const { pullRequest } = request;
321 - void (async () => {
322 - const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest));
323 - if (thread) openThread(thread, request.prompt);
324 - else await openProjectDraft(project, request);
325 - })();
326 - return;
327 - }
328 - Dialog.alert(`You don't have ${promptLinkRepositoryName(repository)}`, undefined, [
329 - { text: "Cancel", style: "cancel" },
330 - ...(request.prompt
331 - ? [{ text: "Use without project", onPress: () => void openScratchDraft(request) }]
332 - : []),
333 - { text: "Clone", onPress: () => cloneRepository(repository, request) },
334 - ]);
335 - });
336 -
337 - const handledSearchRef = useRef<string | null>(null);
338 - useEffect(() => {
339 - if (search === null) {
340 - handledSearchRef.current = null;
341 - return;
342 - }
343 - if (waitingForShells || handledSearchRef.current === search) return;
344 - handledSearchRef.current = search;
345 - navigation.setParams(clearedPromptLinkParams());
346 - resolveLink(search);
347 - }, [navigation, search, waitingForShells]);
348 -}
apps/mobile/src/features/prompt-links/useThreadPromptLink.ts deleted
-42
@@ -1,42 +0,0 @@
1 -import * as Dialog from "../../components/ui/Dialog";
2 -import { useNavigation } from "@react-navigation/native";
3 -import { parseThreadLinkPrompt } from "@t3tools/shared/promptLinks";
4 -import { useEffect, useRef } from "react";
5 -
6 -import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
7 -import {
8 - clearedPromptLinkParams,
9 - promptLinkNotice,
10 - promptLinkSearchFromParams,
11 -} from "./prompt-link-model";
12 -
13 -const THREAD_LINK_KEYS = ["prompt"];
14 -
15 -export function useThreadPromptLink(
16 - params: Readonly<Record<string, unknown>> | undefined,
17 - threadDraftKey: string | null,
18 -) {
19 - const navigation = useNavigation();
20 - const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS);
21 - const handledSearchRef = useRef<string | null>(null);
22 - useEffect(() => {
23 - if (search === null) {
24 - handledSearchRef.current = null;
25 - return;
26 - }
27 - if (threadDraftKey === null || handledSearchRef.current === search) return;
28 - handledSearchRef.current = search;
29 - navigation.setParams(clearedPromptLinkParams(THREAD_LINK_KEYS));
30 - const parsed = parseThreadLinkPrompt(search);
31 - if (!parsed.ok) {
32 - Dialog.alert("Could not open link", parsed.error);
33 - return;
34 - }
35 - if (parsed.value === null) return;
36 - void applyLinkedPromptToThreadDraft(
37 - threadDraftKey,
38 - parsed.value,
39 - promptLinkNotice({ hiddenCharacters: parsed.value.hiddenCharacters }),
40 - );
41 - }, [navigation, search, threadDraftKey]);
42 -}
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
-2
@@ -33,7 +33,6 @@ import { useRemoteConnectionStatus } from "../../state/use-remote-environment-re
33 import type { WorkspaceState } from "../../state/workspaceModel";
34 import { useWorkspaceState } from "../../state/workspace";
35
36 -import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";
36 import { useIncomingShare } from "../sharing/IncomingShareProvider";
37 import { useNewTaskFlow } from "./new-task-flow-provider";
38 import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
@@ -159,7 +158,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
158 const isFocused = useIsFocused();
159 const insets = useSafeAreaInsets();
160 const { getShare, releaseShareReservation } = useIncomingShare();
162 - usePromptLinkResolver(route.params);
161 const routeShareId = Array.isArray(route.params?.incomingShareId)
162 ? route.params.incomingShareId[0]
163 : route.params?.incomingShareId;
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
-2
@@ -95,7 +95,6 @@ import {
95 type ThreadInspectorMode,
96 } from "./thread-inspector-content-stack";
97 import { threadRouteIsHydrating } from "./thread-route-hydration";
98 -import { useThreadPromptLink } from "../prompt-links/useThreadPromptLink";
98 import { ThreadHeader } from "./ThreadHeader";
99 import {
100 useAndroidWorkspaceBack,
@@ -265,7 +264,6 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
264 ? null
265 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
266 const selectedThreadDetailState = useSelectedThreadDetailState();
268 - useThreadPromptLink(params, routeThreadKey);
267 const withInspectorHeader = (content: ReactNode) => (
268 <>
269 {props.inspectorPresentation ? (
apps/mobile/src/lib/appLinking.test.ts
+66 -1
@@ -1,6 +1,13 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { findLinkedRoute, restoreDraftLinkState, shouldHandleAppLink } from "./appLinking";
3 +import type { NavigationState } from "@react-navigation/native";
4 +import {
5 + findLinkedRoute,
6 + findStackRoute,
7 + restoreDraftLinkState,
8 + shouldHandleAppLink,
9 + updateLinkedRoute,
10 +} from "./appLinking";
11
12 describe("shouldHandleAppLink", () => {
13 it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(
@@ -113,4 +120,62 @@ describe("nested link routes", () => {
120 });
121 expect(findLinkedRoute(settingsLink, ["ConnectionsNew"])).toBeUndefined();
122 });
123 +
124 + it("rewrites a nested route without touching the rest of the state", () => {
125 + const next = updateLinkedRoute(settingsLink, ["SettingsEnvironmentNew"], (route) => ({
126 + ...route,
127 + params: { pairingUrl: "x" },
128 + }));
129 + expect(findLinkedRoute(next, ["SettingsEnvironmentNew"])?.params).toEqual({ pairingUrl: "x" });
130 + expect(next?.routes[0]).toBe(settingsLink.routes[0]);
131 + expect(updateLinkedRoute(settingsLink, ["ConnectionsNew"], (route) => route)).toBe(
132 + settingsLink,
133 + );
134 + });
135 +});
136 +
137 +describe("findStackRoute", () => {
138 + const stack = (key: string, routes: NavigationState["routes"]) =>
139 + ({
140 + key,
141 + index: routes.length - 1,
142 + routeNames: routes.map((route) => route.name),
143 + routes,
144 + stale: false,
145 + type: "stack",
146 + }) as NavigationState;
147 +
148 + it("finds a nested screen with the navigator that holds it", () => {
149 + const root = stack("root", [
150 + { key: "home", name: "Home" },
151 + {
152 + key: "settings",
153 + name: "Settings",
154 + state: stack("settings-stack", [{ key: "new-task", name: "NewTaskProject" }]),
155 + },
156 + ]);
157 + expect(findStackRoute(root, "NewTaskProject")).toEqual({
158 + navigatorKey: "settings-stack",
159 + routeKey: "new-task",
160 + focused: true,
161 + });
162 + });
163 +
164 + it("reports whether the screen is its navigator's focused route", () => {
165 + const covered = stack("root", [
166 + { key: "new-task", name: "NewTaskProject" },
167 + { key: "add-project", name: "AddProject" },
168 + ]);
169 + expect(findStackRoute(covered, "NewTaskProject")?.focused).toBe(false);
170 + expect(findStackRoute(covered, "AddProject")?.focused).toBe(true);
171 + });
172 +
173 + it("prefers the top-most screen and reports a missing one", () => {
174 + const root = stack("root", [
175 + { key: "first", name: "NewTaskProject" },
176 + { key: "second", name: "NewTaskProject" },
177 + ]);
178 + expect(findStackRoute(root, "NewTaskProject")?.routeKey).toBe("second");
179 + expect(findStackRoute(root, "Thread")).toBeUndefined();
180 + });
181 });
apps/mobile/src/lib/appLinking.ts
+55
@@ -59,3 +59,58 @@ export function findLinkedRoute(
59 }
60 return undefined;
61 }
62 +
63 +/**
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. `focused` says whether it is that navigator's current route.
67 + */
68 +export function findStackRoute(
69 + state: NavigationState | undefined,
70 + name: string,
71 + accept?: (params: Readonly<Record<string, unknown>> | undefined) => boolean,
72 +):
73 + | { readonly navigatorKey: string; readonly routeKey: string; readonly focused: boolean }
74 + | undefined {
75 + if (!state) return undefined;
76 + for (let index = state.routes.length - 1; index >= 0; index -= 1) {
77 + const route = state.routes[index]!;
78 + if (
79 + route.name === name &&
80 + (accept === undefined ||
81 + accept(route.params as Readonly<Record<string, unknown>> | undefined))
82 + ) {
83 + return { navigatorKey: state.key, routeKey: route.key, focused: index === state.index };
84 + }
85 + const nested = route.state;
86 + // Mounted navigators always have keys; a partial state from a link has not been mounted yet.
87 + if (typeof nested?.key === "string") {
88 + const found = findStackRoute(nested as NavigationState, name, accept);
89 + if (found) return found;
90 + }
91 + }
92 + return undefined;
93 +}
94 +
95 +/** Rewrites the first route named one of `names`, keeping every untouched branch of the state. */
96 +export function updateLinkedRoute(
97 + state: LinkState | undefined,
98 + names: ReadonlyArray<string>,
99 + update: (route: LinkRoute) => LinkRoute,
100 +): LinkState | undefined {
101 + if (!state) return state;
102 + for (const [index, route] of state.routes.entries()) {
103 + let next: LinkRoute | undefined;
104 + if (names.includes(route.name)) next = update(route);
105 + else if (isLinkState(route.state)) {
106 + const nested = updateLinkedRoute(route.state, names, update);
107 + if (nested !== route.state) next = { ...route, state: nested };
108 + }
109 + if (next) {
110 + const routes = state.routes.slice();
111 + routes[index] = next;
112 + return { ...state, routes };
113 + }
114 + }
115 + return state;
116 +}
apps/mobile/src/state/workspace.ts
+12 -20
@@ -1,5 +1,4 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import { useMemo } from "react";
2 import { Atom } from "effect/reactivity";
3
4 import { environmentShell, environmentShellSummaryAtom } from "./shell";
@@ -36,26 +35,19 @@ export function useConnectionsReady() {
35 return useAtomValue(workspaceConnections.isReadyAtom);
36 }
37
39 -export function useWorkspaceState() {
40 - const isReady = useConnectionsReady();
41 - const networkStatus = useAtomValue(environmentCatalog.networkStatusValueAtom);
42 - const projectedEnvironments = useWorkspaceEnvironments();
43 - const shellSummary = useAtomValue(environmentShellSummaryAtom);
44 - const hasSyncingConnectedEnvironment = useAtomValue(hasSyncingConnectedEnvironmentAtom);
45 - const state = useMemo(
46 - () =>
47 - projectWorkspaceState({
48 - isReady,
49 - networkStatus,
50 - environments: projectedEnvironments,
51 - shellSummary,
52 - hasSyncingConnectedEnvironment,
53 - }),
54 - [isReady, networkStatus, projectedEnvironments, shellSummary, hasSyncingConnectedEnvironment],
55 - );
38 +export const workspaceStateAtom = Atom.make((get) =>
39 + projectWorkspaceState({
40 + isReady: get(workspaceConnections.isReadyAtom),
41 + networkStatus: get(environmentCatalog.networkStatusValueAtom),
42 + environments: get(workspaceConnections.environmentsAtom),
43 + shellSummary: get(environmentShellSummaryAtom),
44 + hasSyncingConnectedEnvironment: get(hasSyncingConnectedEnvironmentAtom),
45 + }),
46 +).pipe(Atom.withLabel("mobile:workspace-state"));
47
48 +export function useWorkspaceState() {
49 return {
58 - environments: projectedEnvironments,
59 - state,
50 + environments: useWorkspaceEnvironments(),
51 + state: useAtomValue(workspaceStateAtom),
52 };
53 }