Skip to content
TypeScript

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

Julius Marminge52925f9e9895
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 1443544d946..8eefa558273 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -51,6 +51,14 @@ import { OverlayPortalHost } from "./components/ui/OverlayPortal";
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
+import {
+ resolvePendingNewTaskPromptLink,
+ takeNewTaskPromptLink,
+} from "./features/prompt-links/newTaskPromptLink";
+import {
+ resolvePendingThreadPromptLink,
+ takeThreadPromptLink,
+} from "./features/prompt-links/threadPromptLink";
import {
disposeOnFoundationReplace,
type FoundationHotModule,
@@ -93,9 +101,13 @@ const linkingConfig = {
function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
return takeScheduledTaskNewLink(
- restoreSettingsLinkState(
- restoreDraftLinkState(getStateFromPath(path, options), path),
- settingsLinkPage(),
+ takeNewTaskPromptLink(
+ takeThreadPromptLink(
+ restoreSettingsLinkState(
+ restoreDraftLinkState(getStateFromPath(path, options), path),
+ settingsLinkPage(),
+ ),
+ ),
),
);
}
@@ -130,6 +142,8 @@ const Navigation = createStaticNavigation(RootStack);
function handleNavigationStateChange(state: NavigationState | undefined): void {
recordWorkspaceSelections(state);
presentPendingIncomingShare();
+ resolvePendingNewTaskPromptLink(state);
+ resolvePendingThreadPromptLink(state);
if (!state) return;
setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
recordAppShortcutNavigationState(state);
diff --git a/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts
new file mode 100644
index 00000000000..4028e6f5691
--- /dev/null
+++ b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts
@@ -0,0 +1,420 @@
+import * as Dialog from "../../components/ui/Dialog";
+import {
+ StackActions,
+ type NavigationState,
+ type PartialState,
+ type StackActionType,
+} from "@react-navigation/native";
+import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
+import {
+ findPromptLinkProjects,
+ findPromptLinkPullRequestThread,
+ resolvePromptLinkModelSelection,
+} from "@t3tools/client-runtime/prompt-links";
+import {
+ executeAtomQuery,
+ isAtomCommandInterrupted,
+ runAtomCommand,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import {
+ parseNewThreadLink,
+ type LinkedPrompt,
+ type PromptLinkPullRequest,
+ type PromptLinkRepository,
+} from "@t3tools/shared/promptLinks";
+import { Atom, type AsyncResult } from "effect/reactivity";
+
+import { findLinkedRoute, findStackRoute, updateLinkedRoute } from "../../lib/appLinking";
+import { rootNavigationRef } from "../../lib/rootNavigation";
+import { scopedThreadKey } from "../../lib/scopedEntities";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentProjects, projectEnvironment } from "../../state/projects";
+import { composerPullRequests } from "../../state/pull-requests";
+import { environmentServerConfigsAtom } from "../../state/server";
+import { environmentThreadShells } from "../../state/threads";
+import {
+ createNewTaskDraft,
+ setComposerDraftText,
+ updateComposerDraftSettings,
+ waitForComposerDraftsLoaded,
+} from "../../state/use-composer-drafts";
+import { workspaceConnections, workspaceStateAtom } from "../../state/workspace";
+import { applyLinkedPromptToThreadDraft, showPromptLinkNotice } from "./prompt-link-actions";
+import {
+ latestThreadEnvironmentIds,
+ promptLinkNotice,
+ promptLinkRepositoryName,
+ promptLinkScratchEnvironmentId,
+ promptLinkSearchFromParams,
+ stepPendingPromptLink,
+ withoutPromptLinkParams,
+} from "./prompt-link-model";
+
+// Found at any depth, both in the parsed link and on the live stack, so the two never disagree on
+// whether the link has landed.
+const NEW_TASK_ROUTE = "NewTaskProject";
+const NEW_TASK_ROUTES = [NEW_TASK_ROUTE];
+
+type LinkedDraftRequest = {
+ readonly prompt: LinkedPrompt | null;
+ readonly provider: string | null;
+ readonly model: string | null;
+ readonly pullRequest: PromptLinkPullRequest | null;
+};
+
+// A cold launch from a link has no projects or threads yet. Matching then would offer to clone a
+// repository the user already has.
+const shellsSettledAtom = Atom.make((get) => {
+ const workspace = get(workspaceStateAtom);
+ return !(
+ workspace.isLoadingConnections ||
+ workspace.hasPendingShellSnapshot ||
+ // A machine still connecting may hold the repository or thread. One that keeps failing to
+ // reconnect has settled offline, and must not hold every link.
+ workspace.connectingEnvironments.some(
+ (environment) =>
+ environment.connectionState === "connecting" || environment.connectionError === null,
+ )
+ );
+}).pipe(Atom.withLabel("mobile:prompt-link-shells-settled"));
+
+let pendingLink: string | null = null;
+let stopWaitingForShells: (() => void) | null = null;
+
+/**
+ * `new?prompt=…&repo=…` drops its params as it arrives, so the screen never sees them and each
+ * opening resolves once. It resolves when its screen is on the navigation state that follows and
+ * the shells have settled; a newer link replaces one still waiting.
+ */
+export function takeNewTaskPromptLink(
+ state: PartialState<NavigationState> | undefined,
+): PartialState<NavigationState> | undefined {
+ const route = findLinkedRoute(state, NEW_TASK_ROUTES);
+ const search = promptLinkSearchFromParams(
+ route?.params as Readonly<Record<string, unknown>> | undefined,
+ );
+ if (search === null) return state;
+ pendingLink = search;
+ return updateLinkedRoute(state, NEW_TASK_ROUTES, (linked) => ({
+ ...linked,
+ params: withoutPromptLinkParams(linked.params),
+ }));
+}
+
+/** Wired to the navigation container's state changes. */
+export function resolvePendingNewTaskPromptLink(state: NavigationState | undefined): void {
+ if (pendingLink === null) return;
+ const step = stepPendingPromptLink(pendingLink, {
+ // A screen pushed above New task (such as Add project) drops the link, so it never lands
+ // over the wrong screen.
+ screenOnStack: findStackRoute(state, NEW_TASK_ROUTE)?.focused === true,
+ ready: appAtomRegistry.get(shellsSettledAtom),
+ });
+ if (step.pending === null) dropPendingLink();
+ else pendingLink = step.pending;
+ if (step.resolve !== null) resolveLink(step.resolve);
+ else if (step.pending !== null) {
+ stopWaitingForShells ??= appAtomRegistry.subscribe(shellsSettledAtom, (settled) => {
+ if (settled) resolvePendingNewTaskPromptLink(rootNavigationRef.getRootState());
+ });
+ }
+}
+
+function dropPendingLink(): void {
+ pendingLink = null;
+ stopWaitingForShells?.();
+ stopWaitingForShells = null;
+}
+
+/** Dispatches as the new-task screen would, so `replace` swaps that screen out. */
+function dispatchFromNewTask(action: StackActionType): void {
+ const root = rootNavigationRef.getRootState();
+ const screen = findStackRoute(root, NEW_TASK_ROUTE);
+ const target = screen?.navigatorKey ?? root?.key;
+ rootNavigationRef.dispatch({
+ ...action,
+ ...(target ? { target } : {}),
+ ...(screen ? { source: screen.routeKey } : {}),
+ });
+}
+
+function runQuery<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
+ return executeAtomQuery(appAtomRegistry, atom, {
+ label: atom.label?.[0] ?? "atom query",
+ reportFailure: false,
+ });
+}
+
+function writeDraft(
+ draftKey: string,
+ environmentId: EnvironmentId,
+ request: LinkedDraftRequest,
+): boolean {
+ if (request.prompt) setComposerDraftText(draftKey, request.prompt.text);
+ if (request.provider === null) return false;
+ const resolved = resolvePromptLinkModelSelection(
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.providers ?? [],
+ { provider: request.provider, model: request.model },
+ );
+ if (resolved) updateComposerDraftSettings(draftKey, { modelSelection: resolved.selection });
+ return resolved?.exact !== true;
+}
+
+function openThread(
+ thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId },
+ prompt: LinkedDraftRequest["prompt"],
+) {
+ dispatchFromNewTask(
+ StackActions.replace("Thread", {
+ environmentId: String(thread.environmentId),
+ threadId: String(thread.id),
+ }),
+ );
+ if (prompt) {
+ void applyLinkedPromptToThreadDraft(
+ scopedThreadKey(thread.environmentId, thread.id),
+ prompt,
+ promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
+ );
+ }
+}
+
+// A pull request's thread can be an older settled thread no shell holds, so ask every
+// connected environment with the repository. A lookup on another one would wait forever.
+async function findServerPullRequestThread(
+ projects: ReadonlyArray<EnvironmentProject>,
+ pullRequest: PromptLinkPullRequest,
+) {
+ const connected = new Set(
+ appAtomRegistry
+ .get(workspaceConnections.environmentsAtom)
+ .filter((environment) => environment.connectionState === "connected")
+ .map((environment) => environment.environmentId),
+ );
+ const lookups = projects
+ .filter((project) => connected.has(project.environmentId))
+ .map(async (project) => {
+ const linked = await runQuery(
+ composerPullRequests.linkedThreadsUncached({
+ environmentId: project.environmentId,
+ input: {
+ projectId: project.id,
+ repository: promptLinkRepositoryName(pullRequest),
+ number: pullRequest.number,
+ },
+ }),
+ );
+ const thread =
+ linked._tag === "Success"
+ ? linked.value.threads.find((candidate) => candidate.archivedAt === null)
+ : undefined;
+ return thread && { environmentId: project.environmentId, id: thread.id };
+ });
+ // The most recent project wins without waiting for the lookups after it.
+ for (const lookup of lookups) {
+ const thread = await lookup;
+ if (thread) return thread;
+ }
+ return undefined;
+}
+
+async function openProjectDraft(project: EnvironmentProject, request: LinkedDraftRequest) {
+ try {
+ await waitForComposerDraftsLoaded();
+ } catch {
+ Dialog.alert("Could not open link", "Drafts could not be loaded, so the prompt was not added.");
+ return;
+ }
+ const draftKey = createNewTaskDraft({
+ environmentId: project.environmentId,
+ projectId: project.id,
+ });
+ let pullRequestUnavailable: number | null = null;
+ if (request.pullRequest) {
+ const detail = await runQuery(
+ composerPullRequests.detail({
+ environmentId: project.environmentId,
+ input: {
+ projectId: project.id,
+ repository: promptLinkRepositoryName(request.pullRequest),
+ number: request.pullRequest.number,
+ },
+ }),
+ );
+ if (detail._tag === "Success") {
+ updateComposerDraftSettings(draftKey, {
+ workspaceSelection: {
+ mode: "worktree",
+ branch: detail.value.headBranch,
+ worktreePath: null,
+ startFromOrigin: false,
+ pullRequestReference: detail.value.url,
+ },
+ });
+ } else {
+ pullRequestUnavailable = request.pullRequest.number;
+ }
+ }
+ const modelUnavailable = writeDraft(draftKey, project.environmentId, request);
+ dispatchFromNewTask(
+ StackActions.push("Thread", {
+ draft: {
+ draftId: draftKey,
+ title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
+ },
+ }),
+ );
+ if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {
+ showPromptLinkNotice(
+ promptLinkNotice({
+ hiddenCharacters: request.prompt?.hiddenCharacters ?? 0,
+ modelUnavailable,
+ pullRequestUnavailable,
+ }),
+ );
+ }
+}
+
+async function openScratchDraft(request: LinkedDraftRequest) {
+ const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
+ const environmentId = promptLinkScratchEnvironmentId(
+ latestThreadEnvironmentIds(appAtomRegistry.get(environmentThreadShells.threadShellsAtom)),
+ appAtomRegistry
+ .get(workspaceConnections.environmentsAtom)
+ .filter(
+ (environment) =>
+ availableScratchWorkspaceRoot(
+ environment.connectionState,
+ serverConfigs.get(environment.environmentId),
+ ) !== null,
+ )
+ .map((environment) => environment.environmentId),
+ );
+ if (environmentId === null) {
+ Dialog.alert(
+ "Could not start without a project",
+ "No connected environment offers threads without a project.",
+ );
+ return;
+ }
+ const result = await runAtomCommand(
+ appAtomRegistry,
+ projectEnvironment.openScratch,
+ { environmentId, input: {} },
+ { reportFailure: false },
+ );
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(
+ "Could not start without a project",
+ error instanceof Error
+ ? error.message
+ : "The folder for threads without a project could not be created.",
+ );
+ }
+ return;
+ }
+ await openProjectDraft(result.value, { ...request, pullRequest: null });
+}
+
+function cloneRepository(repository: PromptLinkRepository, request: LinkedDraftRequest) {
+ // The clone screen lets the user pick another environment before cloning.
+ const environmentId =
+ appAtomRegistry.get(environmentProjects.projectsAtom)[0]?.environmentId ??
+ appAtomRegistry.get(workspaceConnections.environmentsAtom)[0]?.environmentId ??
+ null;
+ if (environmentId === null) {
+ Dialog.alert("Could not clone", "Connect an environment first.");
+ return;
+ }
+ const prompt =
+ request.pullRequest === null &&
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
+ .projectCloneTracking === true
+ ? request.prompt
+ : null;
+ const name = promptLinkRepositoryName(repository);
+ dispatchFromNewTask(
+ StackActions.push("AddProjectDestination", {
+ environmentId,
+ remoteUrl: `https://github.com/${name}.git`,
+ repositoryTitle: name,
+ repositoryName: repository.name,
+ ...(prompt ? { prompt: prompt.text } : {}),
+ }),
+ );
+ if (!request.prompt) return;
+ showPromptLinkNotice(
+ [
+ promptLinkNotice({
+ hiddenCharacters: request.prompt.hiddenCharacters,
+ modelUnavailable: prompt !== null && request.provider !== null,
+ }),
+ prompt
+ ? "The prompt opens in a new task once the clone starts."
+ : "Open the link again after the clone to get the prompt.",
+ ].join("\n\n"),
+ );
+}
+
+function resolveLink(linkSearch: string) {
+ const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
+ const parsed = parseNewThreadLink(linkSearch);
+ if (!parsed.ok) {
+ Dialog.alert("Could not open link", parsed.error);
+ return;
+ }
+ const link = parsed.value;
+ const request: LinkedDraftRequest =
+ link.kind === "new"
+ ? { prompt: link.prompt, provider: link.provider, model: link.model, pullRequest: null }
+ : { prompt: link.prompt, provider: null, model: null, pullRequest: link.pullRequest };
+
+ if (link.kind === "pull-request") {
+ const thread = findPromptLinkPullRequestThread(threads, link.pullRequest);
+ if (thread) {
+ openThread(thread, link.prompt);
+ return;
+ }
+ }
+
+ const repository = link.kind === "new" ? link.repository : link.pullRequest;
+ if (repository === null) {
+ void openScratchDraft(request);
+ return;
+ }
+ const lastActivity = new Map<string, string>();
+ for (const thread of threads) {
+ const key = `${thread.environmentId}:${thread.projectId}`;
+ if (thread.updatedAt > (lastActivity.get(key) ?? "")) lastActivity.set(key, thread.updatedAt);
+ }
+ const activityOf = (project: EnvironmentProject) =>
+ lastActivity.get(`${project.environmentId}:${project.id}`) ?? "";
+ const projects = findPromptLinkProjects(
+ [...appAtomRegistry.get(environmentProjects.projectsAtom)].sort((left, right) =>
+ activityOf(right).localeCompare(activityOf(left)),
+ ),
+ repository,
+ );
+ const project = projects[0];
+ if (project) {
+ const { pullRequest } = request;
+ void (async () => {
+ const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest));
+ if (thread) openThread(thread, request.prompt);
+ else await openProjectDraft(project, request);
+ })();
+ return;
+ }
+ Dialog.alert(`You don't have ${promptLinkRepositoryName(repository)}`, undefined, [
+ { text: "Cancel", style: "cancel" },
+ ...(request.prompt
+ ? [{ text: "Use without project", onPress: () => void openScratchDraft(request) }]
+ : []),
+ { text: "Clone", onPress: () => cloneRepository(repository, request) },
+ ]);
+}
diff --git a/apps/mobile/src/features/prompt-links/prompt-link-model.test.ts b/apps/mobile/src/features/prompt-links/prompt-link-model.test.ts
index 9bf74ef042d..2c24e9cf72f 100644
--- a/apps/mobile/src/features/prompt-links/prompt-link-model.test.ts
+++ b/apps/mobile/src/features/prompt-links/prompt-link-model.test.ts
@@ -1,7 +1,11 @@
import { parseNewThreadLink } from "@t3tools/shared/promptLinks";
import { describe, expect, it } from "vite-plus/test";
-import { promptLinkSearchFromParams } from "./prompt-link-model";
+import {
+ promptLinkSearchFromParams,
+ stepPendingPromptLink,
+ withoutPromptLinkParams,
+} from "./prompt-link-model";
describe("promptLinkSearchFromParams", () => {
it("round-trips decoded route params into the shared parser", () => {
@@ -24,3 +28,40 @@ describe("promptLinkSearchFromParams", () => {
});
});
});
+
+describe("stepPendingPromptLink", () => {
+ const waiting = "repo=t3tools%2Ft3code";
+
+ it("drops a link whose screen is missing from the first state after it was parsed", () => {
+ expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: true })).toEqual({
+ pending: null,
+ resolve: null,
+ });
+ });
+
+ it("holds a link on its screen until its target is ready, then resolves it once", () => {
+ expect(stepPendingPromptLink(waiting, { screenOnStack: true, ready: false })).toEqual({
+ pending: waiting,
+ resolve: null,
+ });
+ expect(stepPendingPromptLink(waiting, { screenOnStack: true, ready: true })).toEqual({
+ pending: null,
+ resolve: waiting,
+ });
+ });
+
+ it("drops a link whose screen was left before its target was ready", () => {
+ expect(stepPendingPromptLink(waiting, { screenOnStack: false, ready: false })).toEqual({
+ pending: null,
+ resolve: null,
+ });
+ });
+});
+
+describe("withoutPromptLinkParams", () => {
+ it("keeps the route's other params", () => {
+ expect(withoutPromptLinkParams({ prompt: "hi", repo: "a/b", incomingShareId: "1" })).toEqual({
+ incomingShareId: "1",
+ });
+ });
+});
diff --git a/apps/mobile/src/features/prompt-links/prompt-link-model.ts b/apps/mobile/src/features/prompt-links/prompt-link-model.ts
index 5872b8c9f72..1e52f69870d 100644
--- a/apps/mobile/src/features/prompt-links/prompt-link-model.ts
+++ b/apps/mobile/src/features/prompt-links/prompt-link-model.ts
@@ -17,8 +17,12 @@ export function promptLinkSearchFromParams(
return search.size > 0 ? search.toString() : null;
}
-export function clearedPromptLinkParams(keys: ReadonlyArray<string> = PROMPT_LINK_PARAM_KEYS) {
- return Object.fromEntries(keys.map((key) => [key, undefined]));
+export function withoutPromptLinkParams(params: object | undefined): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(params ?? {}).filter(
+ ([key]) => !(PROMPT_LINK_PARAM_KEYS as ReadonlyArray<string>).includes(key),
+ ),
+ );
}
export function promptLinkNotice(input: {
@@ -73,3 +77,17 @@ export function latestThreadEnvironmentIds<Id extends string>(
export const promptLinkRepositoryName = (repository: PromptLinkRepository) =>
`${repository.owner}/${repository.name}`;
+
+/**
+ * Advances a parsed link at each navigation state; `resolve` is the link to apply. The first
+ * state after the parse must hold the link's screen. A link that never lands there, or whose
+ * screen is left before its target is ready, is dropped so it cannot apply on a later visit.
+ */
+export function stepPendingPromptLink<Link>(
+ link: Link,
+ input: { readonly screenOnStack: boolean; readonly ready: boolean },
+): { readonly pending: Link | null; readonly resolve: Link | null } {
+ if (!input.screenOnStack) return { pending: null, resolve: null };
+ if (input.ready) return { pending: null, resolve: link };
+ return { pending: link, resolve: null };
+}
diff --git a/apps/mobile/src/features/prompt-links/threadPromptLink.test.ts b/apps/mobile/src/features/prompt-links/threadPromptLink.test.ts
new file mode 100644
index 00000000000..3ad3bca31eb
--- /dev/null
+++ b/apps/mobile/src/features/prompt-links/threadPromptLink.test.ts
@@ -0,0 +1,144 @@
+import type { NavigationState, PartialState } from "@react-navigation/native";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+const fixture = vi.hoisted(() => ({
+ applied: [] as { draftKey: string; text: string }[],
+ root: undefined as NavigationState | undefined,
+ detailOpens: 0,
+}));
+
+vi.mock("../../components/ui/Dialog", () => ({ alert: () => {} }));
+vi.mock("./prompt-link-actions", () => ({
+ applyLinkedPromptToThreadDraft: async (draftKey: string, prompt: { text: string }) => {
+ fixture.applied.push({ draftKey, text: prompt.text });
+ },
+}));
+vi.mock("../../lib/rootNavigation", () => ({
+ rootNavigationRef: { getRootState: () => fixture.root },
+}));
+vi.mock("../../state/atom-registry", async () => {
+ const { AtomRegistry } = await import("effect/reactivity");
+ return { appAtomRegistry: AtomRegistry.make() };
+});
+vi.mock("../../state/threads", async () => {
+ const { AsyncResult, Atom } = await import("effect/reactivity");
+ const Option = await import("effect/Option");
+ const shell = Atom.make<object | null>(null);
+ const detailSource = Atom.make(AsyncResult.success({ data: Option.none() }));
+ // Computing the real detail atom opens the thread's server stream.
+ const detail = Atom.make((get) => {
+ fixture.detailOpens += 1;
+ return get(detailSource);
+ });
+ return {
+ environmentThreadShells: { threadShellAtom: () => shell },
+ environmentThreads: { stateAtom: () => detail },
+ fixtureShell: shell,
+ fixtureDetail: detail,
+ fixtureDetailSource: detailSource,
+ };
+});
+
+const { appAtomRegistry } = await import("../../state/atom-registry");
+const { fixtureDetail, fixtureDetailSource, fixtureShell } =
+ (await import("../../state/threads")) as unknown as {
+ fixtureShell: Atom.Writable<object | null>;
+ fixtureDetail: Atom.Atom<unknown>;
+ fixtureDetailSource: Atom.Writable<AsyncResult.AsyncResult<{ data: Option.Option<object> }>>;
+ };
+const { resolvePendingThreadPromptLink, takeThreadPromptLink } = await import("./threadPromptLink");
+
+function setup() {
+ fixture.applied.length = 0;
+ fixture.root = undefined;
+ appAtomRegistry.reset();
+ appAtomRegistry.set(fixtureShell, null);
+ appAtomRegistry.set(fixtureDetailSource, AsyncResult.success({ data: Option.none() }));
+ fixture.detailOpens = 0;
+}
+
+const loadedDetail = AsyncResult.success({ data: Option.some({}) });
+
+const threadParams = { environmentId: "env-1", threadId: "thread-1" };
+
+function linkedState(prompt = "Fix the bug"): PartialState<NavigationState> {
+ return { routes: [{ name: "Thread", params: { ...threadParams, prompt } }] };
+}
+
+function stack(routes: NavigationState["routes"]): NavigationState {
+ return {
+ key: "root",
+ index: routes.length - 1,
+ routeNames: routes.map((route) => route.name),
+ routes,
+ stale: false,
+ type: "stack",
+ };
+}
+
+const threadRoute = stack([{ key: "thread", name: "Thread", params: threadParams }]);
+
+describe("takeThreadPromptLink", () => {
+ it("writes no draft for a thread that never shows", () => {
+ setup();
+ takeThreadPromptLink(linkedState());
+ expect(fixture.applied).toEqual([]);
+
+ resolvePendingThreadPromptLink(threadRoute);
+ // An unknown thread's screen replaces itself with a new-thread draft.
+ resolvePendingThreadPromptLink(
+ stack([{ key: "draft", name: "Thread", params: { draft: { draftId: "d" } } }]),
+ );
+ appAtomRegistry.set(fixtureShell, { id: "thread-1" });
+ expect(fixture.applied).toEqual([]);
+ });
+
+ it("fills the draft once the linked thread shows on its screen", () => {
+ setup();
+ takeThreadPromptLink(linkedState());
+ fixture.root = threadRoute;
+ resolvePendingThreadPromptLink(threadRoute);
+ expect(fixture.applied).toEqual([]);
+
+ appAtomRegistry.set(fixtureShell, { id: "thread-1" });
+ expect(fixture.applied).toEqual([{ draftKey: expect.any(String), text: "Fix the bug" }]);
+ appAtomRegistry.set(fixtureShell, { id: "thread-1", title: "renamed" });
+ expect(fixture.applied).toHaveLength(1);
+ });
+
+ it("fills the draft of an archived thread its screen shows from detail", () => {
+ setup();
+ takeThreadPromptLink(linkedState());
+ fixture.root = threadRoute;
+ // Archived threads have no shell; the open screen subscribes to their detail instead.
+ using _screen = { [Symbol.dispose]: appAtomRegistry.mount(fixtureDetail) };
+ resolvePendingThreadPromptLink(threadRoute);
+ expect(fixture.applied).toEqual([]);
+
+ appAtomRegistry.set(fixtureDetailSource, loadedDetail);
+ expect(fixture.applied).toEqual([{ draftKey: expect.any(String), text: "Fix the bug" }]);
+ });
+
+ it("opens no detail for a thread no screen has loaded", () => {
+ setup();
+ takeThreadPromptLink(linkedState());
+ fixture.root = threadRoute;
+ resolvePendingThreadPromptLink(threadRoute);
+ appAtomRegistry.set(fixtureDetailSource, loadedDetail);
+ expect(fixture.detailOpens).toBe(0);
+ expect(fixture.applied).toEqual([]);
+ resolvePendingThreadPromptLink(stack([{ key: "home", name: "Home" }]));
+ });
+
+ it("drops an earlier link to the thread when a newer one is invalid", () => {
+ setup();
+ takeThreadPromptLink(linkedState());
+ takeThreadPromptLink(linkedState("\u200b"));
+ fixture.root = threadRoute;
+ resolvePendingThreadPromptLink(threadRoute);
+ appAtomRegistry.set(fixtureShell, { id: "thread-1" });
+ expect(fixture.applied).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/features/prompt-links/threadPromptLink.ts b/apps/mobile/src/features/prompt-links/threadPromptLink.ts
new file mode 100644
index 00000000000..bb8795fffc7
--- /dev/null
+++ b/apps/mobile/src/features/prompt-links/threadPromptLink.ts
@@ -0,0 +1,128 @@
+import * as Dialog from "../../components/ui/Dialog";
+import type { NavigationState, PartialState } from "@react-navigation/native";
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import { parseThreadLinkPrompt, type LinkedPrompt } from "@t3tools/shared/promptLinks";
+import * as Option from "effect/Option";
+import { AsyncResult } from "effect/reactivity";
+
+import { findStackRoute } from "../../lib/appLinking";
+import { rootNavigationRef } from "../../lib/rootNavigation";
+import { scopedThreadKey } from "../../lib/scopedEntities";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentThreadShells, environmentThreads } from "../../state/threads";
+import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
+import {
+ promptLinkNotice,
+ promptLinkSearchFromParams,
+ stepPendingPromptLink,
+} from "./prompt-link-model";
+
+const THREAD_LINK_KEYS = ["prompt"];
+
+type PendingThreadLink = { readonly ref: ScopedThreadRef; readonly prompt: LinkedPrompt };
+
+function firstString(value: unknown): string | null {
+ const first = Array.isArray(value) ? value[0] : value;
+ return typeof first === "string" && first.length > 0 ? first : null;
+}
+
+let pendingLink: PendingThreadLink | null = null;
+let stopWaitingForShell: (() => void) | null = null;
+let stopWaitingForDetail: (() => void) | null = null;
+
+/**
+ * `threads/<environment>/<thread>?prompt=…` fills that thread's composer draft. The param is
+ * dropped as the link arrives, so the thread screen never sees it and a later visit cannot apply
+ * it again. The draft is written only once the thread's screen shows a thread that exists: a
+ * screen for an unknown thread replaces itself with a new-thread draft, which drops the link.
+ */
+export function takeThreadPromptLink(
+ state: PartialState<NavigationState> | undefined,
+): PartialState<NavigationState> | undefined {
+ if (!state) return state;
+ const index = state.routes.findIndex((route) => route.name === "Thread");
+ const route = state.routes[index];
+ const params = route?.params as Readonly<Record<string, unknown>> | undefined;
+ const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS);
+ if (!route || !params || search === null) return state;
+ // A newer link replaces a waiting one even when it turns out to be invalid.
+ dropPendingLink();
+ const { prompt: _prompt, ...rest } = params;
+ const routes = state.routes.slice();
+ routes[index] = { ...route, params: rest };
+ const nextState = { ...state, routes };
+
+ const environmentId = firstString(params.environmentId);
+ const threadId = firstString(params.threadId);
+ if (environmentId === null || threadId === null) return nextState;
+ const parsed = parseThreadLinkPrompt(search);
+ if (!parsed.ok) {
+ Dialog.alert("Could not open link", parsed.error);
+ return nextState;
+ }
+ if (parsed.value !== null) {
+ pendingLink = {
+ ref: { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) },
+ prompt: parsed.value,
+ };
+ }
+ return nextState;
+}
+
+/** Wired to the navigation container's state changes. */
+export function resolvePendingThreadPromptLink(state: NavigationState | undefined): void {
+ if (pendingLink === null) return;
+ const { ref } = pendingLink;
+ // A subagent thread the environment's list leaves out gets a shell once the screen mounts its
+ // family. An archived thread never does; the screen shows it from its detail.
+ const shellAtom = environmentThreadShells.threadShellAtom(ref);
+ const detailAtom = environmentThreads.stateAtom(ref.environmentId, ref.threadId);
+ // Read detail only while the screen holds it: opening it here for an unknown thread would keep
+ // retrying with no screen to close it.
+ const screenHoldsDetail = appAtomRegistry.getNodes().has(detailAtom);
+ const step = stepPendingPromptLink(pendingLink, {
+ screenOnStack:
+ findStackRoute(
+ state,
+ "Thread",
+ (params) =>
+ firstString(params?.environmentId) === ref.environmentId &&
+ firstString(params?.threadId) === ref.threadId,
+ ) !== undefined,
+ ready:
+ appAtomRegistry.get(shellAtom) !== null ||
+ (screenHoldsDetail && detailLoaded(appAtomRegistry.get(detailAtom))),
+ });
+ if (step.pending === null) dropPendingLink();
+ if (step.resolve !== null) {
+ const { prompt } = step.resolve;
+ void applyLinkedPromptToThreadDraft(
+ scopedThreadKey(ref.environmentId, ref.threadId),
+ prompt,
+ promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
+ );
+ } else if (step.pending !== null) {
+ stopWaitingForShell ??= appAtomRegistry.subscribe(shellAtom, (shell) => {
+ if (shell !== null) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
+ });
+ if (screenHoldsDetail) {
+ stopWaitingForDetail ??= appAtomRegistry.subscribe(detailAtom, (detail) => {
+ if (detailLoaded(detail)) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
+ });
+ }
+ }
+}
+
+function detailLoaded(
+ result: AsyncResult.AsyncResult<{ readonly data: Option.Option<unknown> }, unknown>,
+): boolean {
+ return Option.isSome(Option.flatMap(AsyncResult.value(result), (state) => state.data));
+}
+
+function dropPendingLink(): void {
+ pendingLink = null;
+ stopWaitingForShell?.();
+ stopWaitingForShell = null;
+ stopWaitingForDetail?.();
+ stopWaitingForDetail = null;
+}
diff --git a/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts b/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts
deleted file mode 100644
index 4b31055ae2c..00000000000
--- a/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts
+++ /dev/null
@@ -1,348 +0,0 @@
-import * as Dialog from "../../components/ui/Dialog";
-import { StackActions, useNavigation } from "@react-navigation/native";
-import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
-import {
- findPromptLinkProjects,
- findPromptLinkPullRequestThread,
- resolvePromptLinkModelSelection,
-} from "@t3tools/client-runtime/prompt-links";
-import {
- isAtomCommandInterrupted,
- squashAtomCommandFailure,
-} from "@t3tools/client-runtime/state/runtime";
-import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
-import {
- parseNewThreadLink,
- type LinkedPrompt,
- type PromptLinkPullRequest,
- type PromptLinkRepository,
-} from "@t3tools/shared/promptLinks";
-import { useEffect, useEffectEvent, useRef } from "react";
-
-import { scopedThreadKey } from "../../lib/scopedEntities";
-import { useServerConfigs, useThreadShells } from "../../state/entities";
-import { projectEnvironment } from "../../state/projects";
-import { composerPullRequests } from "../../state/pull-requests";
-import { useAtomCommand } from "../../state/use-atom-command";
-import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
-import {
- createNewTaskDraft,
- setComposerDraftText,
- updateComposerDraftSettings,
- waitForComposerDraftsLoaded,
-} from "../../state/use-composer-drafts";
-import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
-import { useWorkspaceState } from "../../state/workspace";
-import { useNewTaskFlow } from "../threads/new-task-flow-provider";
-import { applyLinkedPromptToThreadDraft, showPromptLinkNotice } from "./prompt-link-actions";
-import {
- clearedPromptLinkParams,
- promptLinkNotice,
- promptLinkRepositoryName,
- latestThreadEnvironmentIds,
- promptLinkScratchEnvironmentId,
- promptLinkSearchFromParams,
-} from "./prompt-link-model";
-
-type LinkedDraftRequest = {
- readonly prompt: LinkedPrompt | null;
- readonly provider: string | null;
- readonly model: string | null;
- readonly pullRequest: PromptLinkPullRequest | null;
-};
-
-export function usePromptLinkResolver(params: Readonly<Record<string, unknown>> | undefined) {
- const navigation = useNavigation();
- const flow = useNewTaskFlow();
- const { state: catalogState } = useWorkspaceState();
- const threads = useThreadShells();
- const serverConfigs = useServerConfigs();
- const { connectedEnvironments } = useRemoteConnectionStatus();
- const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
- const loadPullRequest = useAtomQueryRunner(composerPullRequests.detail, {
- reportFailure: false,
- });
- const loadLinkedThreads = useAtomQueryRunner(composerPullRequests.linkedThreadsUncached, {
- reportFailure: false,
- });
- const search = promptLinkSearchFromParams(params);
- // Wait for cold-launch shells or existing repositories may be offered for cloning.
- const waitingForShells =
- catalogState.isLoadingConnections ||
- catalogState.hasPendingShellSnapshot ||
- // Connecting machines may hold the target; persistently offline ones must not block every link.
- catalogState.connectingEnvironments.some(
- (environment) =>
- environment.connectionState === "connecting" || environment.connectionError === null,
- );
-
- const writeDraft = (
- draftKey: string,
- environmentId: EnvironmentId,
- request: LinkedDraftRequest,
- ): boolean => {
- if (request.prompt) setComposerDraftText(draftKey, request.prompt.text);
- if (request.provider === null) return false;
- const resolved = resolvePromptLinkModelSelection(
- serverConfigs.get(environmentId)?.providers ?? [],
- { provider: request.provider, model: request.model },
- );
- if (resolved) updateComposerDraftSettings(draftKey, { modelSelection: resolved.selection });
- return resolved?.exact !== true;
- };
-
- const openThread = (
- thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId },
- prompt: LinkedDraftRequest["prompt"],
- ) => {
- (navigation.getParent() ?? navigation).dispatch(
- StackActions.replace("Thread", {
- environmentId: String(thread.environmentId),
- threadId: String(thread.id),
- }),
- );
- if (prompt) {
- void applyLinkedPromptToThreadDraft(
- scopedThreadKey(thread.environmentId, thread.id),
- prompt,
- promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
- );
- }
- };
-
- // A pull request's thread can be an older settled thread no shell holds, so ask every
- // connected environment with the repository. A lookup on another one would wait forever.
- const findServerPullRequestThread = async (
- projects: ReadonlyArray<EnvironmentProject>,
- pullRequest: PromptLinkPullRequest,
- ) => {
- const connected = new Set(
- connectedEnvironments
- .filter((environment) => environment.connectionState === "connected")
- .map((environment) => environment.environmentId),
- );
- const lookups = projects
- .filter((project) => connected.has(project.environmentId))
- .map(async (project) => {
- const linked = await loadLinkedThreads({
- environmentId: project.environmentId,
- input: {
- projectId: project.id,
- repository: promptLinkRepositoryName(pullRequest),
- number: pullRequest.number,
- },
- });
- const thread =
- linked._tag === "Success"
- ? linked.value.threads.find((candidate) => candidate.archivedAt === null)
- : undefined;
- return thread && { environmentId: project.environmentId, id: thread.id };
- });
- // The most recent project wins without waiting for the lookups after it.
- for (const lookup of lookups) {
- const thread = await lookup;
- if (thread) return thread;
- }
- return undefined;
- };
-
- const openProjectDraft = async (project: EnvironmentProject, request: LinkedDraftRequest) => {
- try {
- await waitForComposerDraftsLoaded();
- } catch {
- Dialog.alert(
- "Could not open link",
- "Drafts could not be loaded, so the prompt was not added.",
- );
- return;
- }
- const draftKey = createNewTaskDraft({
- environmentId: project.environmentId,
- projectId: project.id,
- });
- let pullRequestUnavailable: number | null = null;
- if (request.pullRequest) {
- const detail = await loadPullRequest({
- environmentId: project.environmentId,
- input: {
- projectId: project.id,
- repository: promptLinkRepositoryName(request.pullRequest),
- number: request.pullRequest.number,
- },
- });
- if (detail._tag === "Success") {
- updateComposerDraftSettings(draftKey, {
- workspaceSelection: {
- mode: "worktree",
- branch: detail.value.headBranch,
- worktreePath: null,
- startFromOrigin: false,
- pullRequestReference: detail.value.url,
- },
- });
- } else {
- pullRequestUnavailable = request.pullRequest.number;
- }
- }
- const modelUnavailable = writeDraft(draftKey, project.environmentId, request);
- navigation.dispatch(
- StackActions.push("Thread", {
- draft: {
- draftId: draftKey,
- title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
- },
- }),
- );
- if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {
- showPromptLinkNotice(
- promptLinkNotice({
- hiddenCharacters: request.prompt?.hiddenCharacters ?? 0,
- modelUnavailable,
- pullRequestUnavailable,
- }),
- );
- }
- };
-
- const openScratchDraft = async (request: LinkedDraftRequest) => {
- const environmentId = promptLinkScratchEnvironmentId(
- latestThreadEnvironmentIds(threads),
- connectedEnvironments
- .filter(
- (environment) =>
- availableScratchWorkspaceRoot(
- environment.connectionState,
- serverConfigs.get(environment.environmentId),
- ) !== null,
- )
- .map((environment) => environment.environmentId),
- );
- if (environmentId === null) {
- Dialog.alert(
- "Could not start without a project",
- "No connected environment offers threads without a project.",
- );
- return;
- }
- const result = await openScratch({ environmentId, input: {} });
- if (result._tag === "Failure") {
- if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- Dialog.alert(
- "Could not start without a project",
- error instanceof Error
- ? error.message
- : "The folder for threads without a project could not be created.",
- );
- }
- return;
- }
- await openProjectDraft(result.value, { ...request, pullRequest: null });
- };
-
- const cloneRepository = (repository: PromptLinkRepository, request: LinkedDraftRequest) => {
- const environmentId =
- flow.selectedEnvironmentId ?? connectedEnvironments[0]?.environmentId ?? null;
- if (environmentId === null) {
- Dialog.alert("Could not clone", "Connect an environment first.");
- return;
- }
- const prompt =
- request.pullRequest === null &&
- serverConfigs.get(environmentId)?.environment.capabilities.projectCloneTracking === true
- ? request.prompt
- : null;
- const name = promptLinkRepositoryName(repository);
- navigation.dispatch(
- StackActions.push("AddProjectDestination", {
- environmentId,
- remoteUrl: `https://github.com/${name}.git`,
- repositoryTitle: name,
- repositoryName: repository.name,
- ...(prompt ? { prompt: prompt.text } : {}),
- }),
- );
- if (!request.prompt) return;
- showPromptLinkNotice(
- [
- promptLinkNotice({
- hiddenCharacters: request.prompt.hiddenCharacters,
- modelUnavailable: prompt !== null && request.provider !== null,
- }),
- prompt
- ? "The prompt opens in a new task once the clone starts."
- : "Open the link again after the clone to get the prompt.",
- ].join("\n\n"),
- );
- };
-
- const resolveLink = useEffectEvent((linkSearch: string) => {
- const parsed = parseNewThreadLink(linkSearch);
- if (!parsed.ok) {
- Dialog.alert("Could not open link", parsed.error);
- return;
- }
- const link = parsed.value;
- const request: LinkedDraftRequest =
- link.kind === "new"
- ? { prompt: link.prompt, provider: link.provider, model: link.model, pullRequest: null }
- : { prompt: link.prompt, provider: null, model: null, pullRequest: link.pullRequest };
-
- if (link.kind === "pull-request") {
- const thread = findPromptLinkPullRequestThread(threads, link.pullRequest);
- if (thread) {
- openThread(thread, link.prompt);
- return;
- }
- }
-
- const repository = link.kind === "new" ? link.repository : link.pullRequest;
- if (repository === null) {
- void openScratchDraft(request);
- return;
- }
- const lastActivity = new Map<string, string>();
- for (const thread of threads) {
- const key = `${thread.environmentId}:${thread.projectId}`;
- if (thread.updatedAt > (lastActivity.get(key) ?? "")) lastActivity.set(key, thread.updatedAt);
- }
- const activityOf = (project: EnvironmentProject) =>
- lastActivity.get(`${project.environmentId}:${project.id}`) ?? "";
- const projects = findPromptLinkProjects(
- flow.projectScopes
- .flatMap((scope) => scope.projects)
- .sort((left, right) => activityOf(right).localeCompare(activityOf(left))),
- repository,
- );
- const project = projects[0];
- if (project) {
- const { pullRequest } = request;
- void (async () => {
- const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest));
- if (thread) openThread(thread, request.prompt);
- else await openProjectDraft(project, request);
- })();
- return;
- }
- Dialog.alert(`You don't have ${promptLinkRepositoryName(repository)}`, undefined, [
- { text: "Cancel", style: "cancel" },
- ...(request.prompt
- ? [{ text: "Use without project", onPress: () => void openScratchDraft(request) }]
- : []),
- { text: "Clone", onPress: () => cloneRepository(repository, request) },
- ]);
- });
-
- const handledSearchRef = useRef<string | null>(null);
- useEffect(() => {
- if (search === null) {
- handledSearchRef.current = null;
- return;
- }
- if (waitingForShells || handledSearchRef.current === search) return;
- handledSearchRef.current = search;
- navigation.setParams(clearedPromptLinkParams());
- resolveLink(search);
- }, [navigation, search, waitingForShells]);
-}
diff --git a/apps/mobile/src/features/prompt-links/useThreadPromptLink.ts b/apps/mobile/src/features/prompt-links/useThreadPromptLink.ts
deleted file mode 100644
index f01f5c39643..00000000000
--- a/apps/mobile/src/features/prompt-links/useThreadPromptLink.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import * as Dialog from "../../components/ui/Dialog";
-import { useNavigation } from "@react-navigation/native";
-import { parseThreadLinkPrompt } from "@t3tools/shared/promptLinks";
-import { useEffect, useRef } from "react";
-
-import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
-import {
- clearedPromptLinkParams,
- promptLinkNotice,
- promptLinkSearchFromParams,
-} from "./prompt-link-model";
-
-const THREAD_LINK_KEYS = ["prompt"];
-
-export function useThreadPromptLink(
- params: Readonly<Record<string, unknown>> | undefined,
- threadDraftKey: string | null,
-) {
- const navigation = useNavigation();
- const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS);
- const handledSearchRef = useRef<string | null>(null);
- useEffect(() => {
- if (search === null) {
- handledSearchRef.current = null;
- return;
- }
- if (threadDraftKey === null || handledSearchRef.current === search) return;
- handledSearchRef.current = search;
- navigation.setParams(clearedPromptLinkParams(THREAD_LINK_KEYS));
- const parsed = parseThreadLinkPrompt(search);
- if (!parsed.ok) {
- Dialog.alert("Could not open link", parsed.error);
- return;
- }
- if (parsed.value === null) return;
- void applyLinkedPromptToThreadDraft(
- threadDraftKey,
- parsed.value,
- promptLinkNotice({ hiddenCharacters: parsed.value.hiddenCharacters }),
- );
- }, [navigation, search, threadDraftKey]);
-}
diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
index 01b3ed0c0f4..cae0f7771a4 100644
--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
@@ -33,7 +33,6 @@ import { useRemoteConnectionStatus } from "../../state/use-remote-environment-re
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
-import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { useNewTaskFlow } from "./new-task-flow-provider";
import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
@@ -159,7 +158,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
const isFocused = useIsFocused();
const insets = useSafeAreaInsets();
const { getShare, releaseShareReservation } = useIncomingShare();
- usePromptLinkResolver(route.params);
const routeShareId = Array.isArray(route.params?.incomingShareId)
? route.params.incomingShareId[0]
: route.params?.incomingShareId;
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index c99586c7f56..ed1a9819d26 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -95,7 +95,6 @@ import {
type ThreadInspectorMode,
} from "./thread-inspector-content-stack";
import { threadRouteIsHydrating } from "./thread-route-hydration";
-import { useThreadPromptLink } from "../prompt-links/useThreadPromptLink";
import { ThreadHeader } from "./ThreadHeader";
import {
useAndroidWorkspaceBack,
@@ -265,7 +264,6 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
? null
: scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const selectedThreadDetailState = useSelectedThreadDetailState();
- useThreadPromptLink(params, routeThreadKey);
const withInspectorHeader = (content: ReactNode) => (
<>
{props.inspectorPresentation ? (
diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts
index 0fbf540a4d1..977a5a5e41e 100644
--- a/apps/mobile/src/lib/appLinking.test.ts
+++ b/apps/mobile/src/lib/appLinking.test.ts
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
-import { findLinkedRoute, restoreDraftLinkState, shouldHandleAppLink } from "./appLinking";
+import type { NavigationState } from "@react-navigation/native";
+import {
+ findLinkedRoute,
+ findStackRoute,
+ restoreDraftLinkState,
+ shouldHandleAppLink,
+ updateLinkedRoute,
+} from "./appLinking";
describe("shouldHandleAppLink", () => {
it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(
@@ -113,4 +120,62 @@ describe("nested link routes", () => {
});
expect(findLinkedRoute(settingsLink, ["ConnectionsNew"])).toBeUndefined();
});
+
+ it("rewrites a nested route without touching the rest of the state", () => {
+ const next = updateLinkedRoute(settingsLink, ["SettingsEnvironmentNew"], (route) => ({
+ ...route,
+ params: { pairingUrl: "x" },
+ }));
+ expect(findLinkedRoute(next, ["SettingsEnvironmentNew"])?.params).toEqual({ pairingUrl: "x" });
+ expect(next?.routes[0]).toBe(settingsLink.routes[0]);
+ expect(updateLinkedRoute(settingsLink, ["ConnectionsNew"], (route) => route)).toBe(
+ settingsLink,
+ );
+ });
+});
+
+describe("findStackRoute", () => {
+ const stack = (key: string, routes: NavigationState["routes"]) =>
+ ({
+ key,
+ index: routes.length - 1,
+ routeNames: routes.map((route) => route.name),
+ routes,
+ stale: false,
+ type: "stack",
+ }) as NavigationState;
+
+ it("finds a nested screen with the navigator that holds it", () => {
+ const root = stack("root", [
+ { key: "home", name: "Home" },
+ {
+ key: "settings",
+ name: "Settings",
+ state: stack("settings-stack", [{ key: "new-task", name: "NewTaskProject" }]),
+ },
+ ]);
+ expect(findStackRoute(root, "NewTaskProject")).toEqual({
+ navigatorKey: "settings-stack",
+ routeKey: "new-task",
+ focused: true,
+ });
+ });
+
+ it("reports whether the screen is its navigator's focused route", () => {
+ const covered = stack("root", [
+ { key: "new-task", name: "NewTaskProject" },
+ { key: "add-project", name: "AddProject" },
+ ]);
+ expect(findStackRoute(covered, "NewTaskProject")?.focused).toBe(false);
+ expect(findStackRoute(covered, "AddProject")?.focused).toBe(true);
+ });
+
+ it("prefers the top-most screen and reports a missing one", () => {
+ const root = stack("root", [
+ { key: "first", name: "NewTaskProject" },
+ { key: "second", name: "NewTaskProject" },
+ ]);
+ expect(findStackRoute(root, "NewTaskProject")?.routeKey).toBe("second");
+ expect(findStackRoute(root, "Thread")).toBeUndefined();
+ });
});
diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts
index 6f8e8953972..9da768150f5 100644
--- a/apps/mobile/src/lib/appLinking.ts
+++ b/apps/mobile/src/lib/appLinking.ts
@@ -59,3 +59,58 @@ export function findLinkedRoute(
}
return undefined;
}
+
+/**
+ * The last route named `name` (and accepted by `accept`, when given) at any depth of a live
+ * navigation state, with the key of the navigator holding it, so an action can be dispatched as
+ * that screen would. `focused` says whether it is that navigator's current route.
+ */
+export function findStackRoute(
+ state: NavigationState | undefined,
+ name: string,
+ accept?: (params: Readonly<Record<string, unknown>> | undefined) => boolean,
+):
+ | { readonly navigatorKey: string; readonly routeKey: string; readonly focused: boolean }
+ | undefined {
+ if (!state) return undefined;
+ for (let index = state.routes.length - 1; index >= 0; index -= 1) {
+ const route = state.routes[index]!;
+ if (
+ route.name === name &&
+ (accept === undefined ||
+ accept(route.params as Readonly<Record<string, unknown>> | undefined))
+ ) {
+ return { navigatorKey: state.key, routeKey: route.key, focused: index === state.index };
+ }
+ const nested = route.state;
+ // Mounted navigators always have keys; a partial state from a link has not been mounted yet.
+ if (typeof nested?.key === "string") {
+ const found = findStackRoute(nested as NavigationState, name, accept);
+ if (found) return found;
+ }
+ }
+ return undefined;
+}
+
+/** Rewrites the first route named one of `names`, keeping every untouched branch of the state. */
+export function updateLinkedRoute(
+ state: LinkState | undefined,
+ names: ReadonlyArray<string>,
+ update: (route: LinkRoute) => LinkRoute,
+): LinkState | undefined {
+ if (!state) return state;
+ for (const [index, route] of state.routes.entries()) {
+ let next: LinkRoute | undefined;
+ if (names.includes(route.name)) next = update(route);
+ else if (isLinkState(route.state)) {
+ const nested = updateLinkedRoute(route.state, names, update);
+ if (nested !== route.state) next = { ...route, state: nested };
+ }
+ if (next) {
+ const routes = state.routes.slice();
+ routes[index] = next;
+ return { ...state, routes };
+ }
+ }
+ return state;
+}
diff --git a/apps/mobile/src/state/workspace.ts b/apps/mobile/src/state/workspace.ts
index 46fafdf265d..c15ec215aac 100644
--- a/apps/mobile/src/state/workspace.ts
+++ b/apps/mobile/src/state/workspace.ts
@@ -1,5 +1,4 @@
import { useAtomValue } from "@effect/atom-react";
-import { useMemo } from "react";
import { Atom } from "effect/reactivity";
import { environmentShell, environmentShellSummaryAtom } from "./shell";
@@ -36,26 +35,19 @@ export function useConnectionsReady() {
return useAtomValue(workspaceConnections.isReadyAtom);
}
-export function useWorkspaceState() {
- const isReady = useConnectionsReady();
- const networkStatus = useAtomValue(environmentCatalog.networkStatusValueAtom);
- const projectedEnvironments = useWorkspaceEnvironments();
- const shellSummary = useAtomValue(environmentShellSummaryAtom);
- const hasSyncingConnectedEnvironment = useAtomValue(hasSyncingConnectedEnvironmentAtom);
- const state = useMemo(
- () =>
- projectWorkspaceState({
- isReady,
- networkStatus,
- environments: projectedEnvironments,
- shellSummary,
- hasSyncingConnectedEnvironment,
- }),
- [isReady, networkStatus, projectedEnvironments, shellSummary, hasSyncingConnectedEnvironment],
- );
+export const workspaceStateAtom = Atom.make((get) =>
+ projectWorkspaceState({
+ isReady: get(workspaceConnections.isReadyAtom),
+ networkStatus: get(environmentCatalog.networkStatusValueAtom),
+ environments: get(workspaceConnections.environmentsAtom),
+ shellSummary: get(environmentShellSummaryAtom),
+ hasSyncingConnectedEnvironment: get(hasSyncingConnectedEnvironmentAtom),
+ }),
+).pipe(Atom.withLabel("mobile:workspace-state"));
+export function useWorkspaceState() {
return {
- environments: projectedEnvironments,
- state,
+ environments: useWorkspaceEnvironments(),
+ state: useAtomValue(workspaceStateAtom),
};
}