Skip to content
TypeScript

fix(mobile): keep the new-task draft when switching environment (#10247)

Julius Marmingebfba7781681e
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 6d87f284ebd..c17e2c002a1 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -92,6 +92,7 @@ import {
resolveNewTaskBranchWorktreePath,
resolveNewTaskLocalWorkspaceSelection,
} from "./new-task-context-presentation";
+import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
type WorkspaceMode = "local" | "worktree";
@@ -622,51 +623,44 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
}, [availableBranches, branchQuery]);
- const setProject = useCallback(
+ // New-task drafts are keyed per (environment, project), so retargeting the
+ // composer would otherwise show the target's empty draft and strand what the
+ // user typed under the old key.
+ const carryDraftContentTo = useCallback(
(project: EnvironmentProject) => {
- const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
- const nextDraftKey = `new-task:${nextProjectKey}`;
+ const nextDraftKey = `new-task:${scopedProjectKey(project.environmentId, project.id)}`;
if (
selectedProjectDraftKey?.startsWith("new-task:") &&
selectedProjectDraftKey !== nextDraftKey
) {
void copyComposerDraftContentIfEmpty(selectedProjectDraftKey, nextDraftKey);
}
- setSelectedEnvironmentId(project.environmentId);
- setSelectedProjectKey(nextProjectKey);
},
[selectedProjectDraftKey],
);
+ const setProject = useCallback(
+ (project: EnvironmentProject) => {
+ carryDraftContentTo(project);
+ setSelectedEnvironmentId(project.environmentId);
+ setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
+ },
+ [carryDraftContentTo],
+ );
+
const selectEnvironment = useCallback(
(environmentId: EnvironmentId) => {
- const projectsOnTarget = projects.filter(
- (project) => project.environmentId === environmentId,
+ const match = resolveEnvironmentProjectMatch(
+ projects.filter((project) => project.environmentId === environmentId),
+ selectedProject,
);
- const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
- // Prefer the repository identity; projects without one (e.g. not yet
- // indexed) fall back to workspace basename, then title, so switching
- // computers still follows the same repo instead of resetting to
- // whatever project is first on the target machine.
- const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
- const match =
- (repositoryKey !== null
- ? projectsOnTarget.find(
- (project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey,
- )
- : undefined) ??
- (workspaceBasename !== null
- ? projectsOnTarget.find(
- (project) => project.workspaceRoot.split("/").at(-1) === workspaceBasename,
- )
- : undefined) ??
- (selectedProject !== null
- ? projectsOnTarget.find((project) => project.title === selectedProject.title)
- : undefined);
+ if (match) {
+ carryDraftContentTo(match);
+ }
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
},
- [projects, selectedProject],
+ [projects, selectedProject, carryDraftContentTo],
);
const setWorkspaceMode = useCallback(
diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.ts
index 2d52ed716d5..ca59a2b9ddd 100644
--- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts
+++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts
@@ -6,15 +6,33 @@ import type { HomeProjectScope } from "../home/homeThreadList";
import {
getProjectScopeSelectionTarget,
resolveDraftProjectSelection,
+ resolveEnvironmentProjectMatch,
} from "./new-task-project-selection";
-function makeProject(id: string, environmentId = "environment"): EnvironmentProject {
+function makeProject(
+ id: string,
+ environmentId = "environment",
+ options: {
+ readonly title?: string;
+ readonly workspaceRoot?: string;
+ readonly repositoryKey?: string;
+ } = {},
+): EnvironmentProject {
return {
environmentId: EnvironmentId.make(environmentId),
id: ProjectId.make(id),
- title: id,
- workspaceRoot: `/work/${id}`,
- repositoryIdentity: null,
+ title: options.title ?? id,
+ workspaceRoot: options.workspaceRoot ?? `/work/${id}`,
+ repositoryIdentity: options.repositoryKey
+ ? {
+ canonicalKey: options.repositoryKey,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: `https://${options.repositoryKey}.git`,
+ },
+ }
+ : null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-01T00:00:00.000Z",
@@ -51,6 +69,55 @@ describe("getProjectScopeSelectionTarget", () => {
});
});
+describe("resolveEnvironmentProjectMatch", () => {
+ it("follows the same repository onto the target machine", () => {
+ const selected = makeProject("t3code", "mac", { repositoryKey: "github.com/t3tools/t3code" });
+ const target = [
+ makeProject("other", "server", { repositoryKey: "github.com/t3tools/other" }),
+ makeProject("t3code-clone", "server", { repositoryKey: "github.com/t3tools/t3code" }),
+ ];
+ expect(resolveEnvironmentProjectMatch(target, selected)).toBe(target[1]);
+ });
+
+ it("falls back to workspace basename, then title, for unindexed projects", () => {
+ const selected = makeProject("t3code", "mac", { workspaceRoot: "/Users/me/t3code" });
+ const byBasename = [
+ makeProject("other", "server"),
+ makeProject("srv", "server", { workspaceRoot: "/home/me/t3code" }),
+ ];
+ expect(resolveEnvironmentProjectMatch(byBasename, selected)).toBe(byBasename[1]);
+
+ const byTitle = [
+ makeProject("other", "server"),
+ makeProject("srv", "server", { title: "t3code" }),
+ ];
+ expect(resolveEnvironmentProjectMatch(byTitle, selected)).toBe(byTitle[1]);
+ });
+
+ it("does not treat a known different repository as a basename or title match", () => {
+ const selected = makeProject("t3code", "mac", {
+ repositoryKey: "github.com/t3tools/t3code",
+ workspaceRoot: "/Users/me/t3code",
+ });
+ const fork = makeProject("fork", "server", {
+ repositoryKey: "github.com/someone/t3code",
+ title: "t3code",
+ workspaceRoot: "/home/me/t3code",
+ });
+ const unindexed = makeProject("unindexed", "server", { workspaceRoot: "/srv/t3code" });
+ expect(resolveEnvironmentProjectMatch([fork, unindexed], selected)).toBe(unindexed);
+ // Without any weaker match the fork is still the first-project fallback.
+ expect(resolveEnvironmentProjectMatch([fork], selected)).toBe(fork);
+ });
+
+ it("falls back to the first project on the target so the draft has a key to carry over to", () => {
+ const selected = makeProject("t3code", "mac", { repositoryKey: "github.com/t3tools/t3code" });
+ const target = [makeProject("unrelated", "server"), makeProject("also-unrelated", "server")];
+ expect(resolveEnvironmentProjectMatch(target, selected)).toBe(target[0]);
+ expect(resolveEnvironmentProjectMatch([], selected)).toBeNull();
+ });
+});
+
describe("resolveDraftProjectSelection", () => {
it("preserves an explicit project selection", () => {
const project = makeProject("t3code");
diff --git a/apps/mobile/src/features/threads/new-task-project-selection.ts b/apps/mobile/src/features/threads/new-task-project-selection.ts
index 0528dc66687..65dd9916f2f 100644
--- a/apps/mobile/src/features/threads/new-task-project-selection.ts
+++ b/apps/mobile/src/features/threads/new-task-project-selection.ts
@@ -26,6 +26,53 @@ function getOnlySelectableProject(
return onlyScope?.representative ?? null;
}
+/**
+ * Picks the project on a target environment that corresponds to the project
+ * currently selected in the new-task flow, so switching computers follows the
+ * same repo. Repository identity is preferred; projects without one (e.g. not
+ * yet indexed) fall back to workspace basename, then title. When nothing
+ * matches, the first project on the target stands in — the same fallback the
+ * render path applies when no key is selected — so the draft always has a
+ * concrete key to carry over to.
+ */
+export function resolveEnvironmentProjectMatch(
+ projectsOnTarget: ReadonlyArray<EnvironmentProject>,
+ selectedProject: EnvironmentProject | null,
+): EnvironmentProject | null {
+ const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
+ // `|| null` (not `??`): a pending-task placeholder project can have an empty
+ // workspaceRoot, and an "" basename would match nothing meaningful.
+ const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
+ // The weaker signals only apply where identity is unknown on at least one
+ // side; two known, different repositories never match on a shared basename
+ // or title (mirrors the environment list filter in the new-task flow).
+ const isKnownMismatch = (project: EnvironmentProject) => {
+ const projectKey = project.repositoryIdentity?.canonicalKey ?? null;
+ return repositoryKey !== null && projectKey !== null && projectKey !== repositoryKey;
+ };
+ return (
+ (repositoryKey !== null
+ ? projectsOnTarget.find(
+ (project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey,
+ )
+ : undefined) ??
+ (workspaceBasename !== null
+ ? projectsOnTarget.find(
+ (project) =>
+ !isKnownMismatch(project) &&
+ project.workspaceRoot.split("/").at(-1) === workspaceBasename,
+ )
+ : undefined) ??
+ (selectedProject !== null
+ ? projectsOnTarget.find(
+ (project) => !isKnownMismatch(project) && project.title === selectedProject.title,
+ )
+ : undefined) ??
+ projectsOnTarget[0] ??
+ null
+ );
+}
+
export function resolveDraftProjectSelection(
selectedProjectKey: string | null,
projects: ReadonlyArray<EnvironmentProject>,
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index a5e85227e27..57c0ac91d14 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -145,6 +145,7 @@ vi.mock("../features/sharing/incoming-share-storage", () => ({
loadIncomingShareDrafts: incomingShareStorageMocks.load,
}));
+import type { DraftComposerAttachment } from "../lib/composerImages";
import { appAtomRegistry } from "./atom-registry";
import { threadOutboxManager } from "./thread-outbox";
import {
@@ -1433,6 +1434,48 @@ describe("mobile composer drafts", () => {
expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);
});
+ it("drops another environment's upload stamp when carrying attachments across machines", () => {
+ const sourceKey = "new-task:environment-1:project-1";
+ const targetKey = "new-task:environment-2:project-2";
+ const uploadedElsewhere: DraftComposerAttachment = {
+ id: "image-1",
+ type: "image",
+ name: "screen.png",
+ mimeType: "image/png",
+ sizeBytes: 1,
+ previewUri: "file:///drafts/screen.png",
+ fileUri: "file:///drafts/screen.png",
+ uploadedAttachmentId: "upload-1",
+ uploadEnvironmentId: EnvironmentId.make("environment-1"),
+ };
+ const uploadedOnTarget: DraftComposerAttachment = {
+ ...uploadedElsewhere,
+ id: "image-2",
+ uploadedAttachmentId: "upload-2",
+ uploadEnvironmentId: EnvironmentId.make("environment-2"),
+ };
+
+ const next = copyComposerDraftContentState(
+ { [sourceKey]: { text: "Ship it", attachments: [uploadedElsewhere, uploadedOnTarget] } },
+ sourceKey,
+ targetKey,
+ );
+
+ expect(next[targetKey]?.attachments).toEqual([
+ {
+ id: "image-1",
+ type: "image",
+ name: "screen.png",
+ mimeType: "image/png",
+ sizeBytes: 1,
+ previewUri: "file:///drafts/screen.png",
+ fileUri: "file:///drafts/screen.png",
+ },
+ uploadedOnTarget,
+ ]);
+ expect(next[sourceKey]?.attachments).toEqual([uploadedElsewhere, uploadedOnTarget]);
+ });
+
it("merges shared content into a project draft without duplicating retries", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedAttachment = {
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 6b463c2d262..bf25866b14c 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -1049,17 +1049,35 @@ export function copyComposerDraftContentState(
if (!sourceHasContent || targetHasContent) {
return current;
}
+ // Pending uploads live on one server. Crossing environments keeps the local
+ // bytes (the upload worker re-sends them to the new key's environment) but
+ // drops the old stamp, so it cannot pin the source environment's pending
+ // upload alive from the copy.
+ const targetEnvironmentId = composerDraftEnvironmentId(targetDraftKey, []);
+ const attachments = source.attachments.map((attachment) =>
+ attachment.uploadEnvironmentId !== undefined &&
+ attachment.uploadEnvironmentId !== targetEnvironmentId
+ ? stripAttachmentUploadReference(attachment)
+ : attachment,
+ );
return {
...current,
[targetDraftKey]: {
...target,
text: source.text,
- attachments: source.attachments,
+ attachments,
...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
},
};
}
+function stripAttachmentUploadReference(
+ attachment: DraftComposerAttachment,
+): DraftComposerAttachment {
+ const { uploadedAttachmentId: _id, uploadEnvironmentId: _environmentId, ...rest } = attachment;
+ return rest;
+}
+
export async function copyComposerDraftContentIfEmpty(
sourceDraftKey: string,
targetDraftKey: string,