Skip to content

Commit 8e129a0

Browse files
feat(mobile): allow several new-task drafts per project (#10327)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent c0bf354 commit 8e129a0

15 files changed

Lines changed: 664 additions & 345 deletions

‎apps/mobile/src/features/home/usePendingTaskListActions.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,14 @@ export function usePendingTaskListActions(): {
1515

1616
const openPendingTask = useCallback(
1717
(pendingTask: PendingNewTask) => {
18-
// A draft is the project's own new-task composer content, so opening
19-
// the project's new-task screen lands on it without extra params.
2018
navigation.navigate("NewTaskSheet", {
2119
screen: "NewTaskDraft",
2220
params: {
2321
environmentId: String(pendingTask.environmentId),
2422
projectId: String(pendingTask.projectId),
2523
...(pendingTask.kind === "pending"
2624
? { pendingTaskId: String(pendingTask.message.messageId) }
27-
: {}),
25+
: { draftId: pendingTask.draftKey }),
2826
},
2927
});
3028
},

‎apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ type NewTaskDraftRouteParams = {
99
readonly projectId?: string | string[];
1010
readonly title?: string | string[];
1111
readonly pendingTaskId?: string | string[];
12+
readonly draftId?: string | string[];
1213
readonly incomingShareId?: string | string[];
1314
};
1415

@@ -43,6 +44,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
4344
pendingTaskId={
4445
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
4546
}
47+
draftId={Array.isArray(params.draftId) ? params.draftId[0] : params.draftId}
4648
/>
4749
</>
4850
);

‎apps/mobile/src/features/threads/NewTaskDraftScreen.tsx‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ import {
8383
restoreComposerDraftSnapshot,
8484
scheduleUnusedComposerAttachmentCleanup,
8585
type ComposerDraft,
86+
waitForComposerDraftsLoaded,
8687
} from "../../state/use-composer-drafts";
8788
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
8889
import {
@@ -150,6 +151,8 @@ export function NewTaskDraftScreen(props: {
150151
};
151152
/** Queued outbox message id when editing an existing pending task. */
152153
readonly pendingTaskId?: string;
154+
/** Existing new-task draft key to resume (a Draft row in the thread list). */
155+
readonly draftId?: string;
153156
/** Durable native share inbox item to merge into this project draft. */
154157
readonly incomingShareId?: string;
155158
}) {
@@ -420,7 +423,44 @@ export function NewTaskDraftScreen(props: {
420423
};
421424
}, []);
422425

423-
const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
426+
const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask, openDraft } = flow;
427+
// A Draft row opens its own draft; a fresh New Task never reuses one.
428+
// Drafts hydrate from disk and projects arrive with the shell snapshot, so
429+
// on a cold launch the draft or its project can be missing for a moment;
430+
// wait for hydration and retry while projects load. Attempt each id once
431+
// after that so a draft discarded mid-session does not keep bouncing to
432+
// the picker.
433+
const attemptedDraftIdRef = useRef<string | null>(null);
434+
useEffect(() => {
435+
if (!props.draftId || props.pendingTaskId) {
436+
return;
437+
}
438+
const draftId = props.draftId;
439+
if (attemptedDraftIdRef.current === draftId) {
440+
return;
441+
}
442+
let cancelled = false;
443+
void waitForComposerDraftsLoaded().then(() => {
444+
if (cancelled || attemptedDraftIdRef.current === draftId) {
445+
return;
446+
}
447+
if (openDraft(draftId)) {
448+
attemptedDraftIdRef.current = draftId;
449+
return;
450+
}
451+
if (getComposerDraftSnapshot(draftId).project !== undefined && projects.length === 0) {
452+
// The draft exists; its project has not arrived yet. Retry on the
453+
// next projects change instead of giving up.
454+
return;
455+
}
456+
attemptedDraftIdRef.current = draftId;
457+
navigation.dispatch(StackActions.replace("NewTask"));
458+
});
459+
return () => {
460+
cancelled = true;
461+
};
462+
}, [navigation, openDraft, projects, props.draftId, props.pendingTaskId]);
463+
424464
const attemptedPendingTaskIdRef = useRef<string | null>(null);
425465
useEffect(() => {
426466
if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
@@ -457,9 +497,10 @@ export function NewTaskDraftScreen(props: {
457497
const lastInitialProjectRefRef = useRef(props.initialProjectRef);
458498

459499
useEffect(() => {
460-
// Pending-task editing owns project selection (and must not fall through
461-
// to the replace("NewTask") fallback while its hydration is in flight).
462-
if (props.pendingTaskId) {
500+
// Pending-task editing and draft resumption own project selection (and
501+
// must not fall through to the replace("NewTask") fallback while their
502+
// hydration is in flight).
503+
if (props.pendingTaskId || props.draftId) {
463504
return;
464505
}
465506
if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
@@ -518,6 +559,7 @@ export function NewTaskDraftScreen(props: {
518559
props.initialProjectRef,
519560
props.incomingShareId,
520561
props.pendingTaskId,
562+
props.draftId,
521563
navigation,
522564
selectedProject,
523565
selectedProjectKey,

‎apps/mobile/src/features/threads/new-task-flow-provider.tsx‎

Lines changed: 68 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,14 @@ import { useEnvironmentQuery } from "../../state/query";
4343
import {
4444
appendComposerDraftAttachments,
4545
clearComposerDraft,
46-
copyComposerDraftContentIfEmpty,
46+
composerDraftsAtom,
47+
createNewTaskDraft,
4748
getComposerDraftSnapshot,
4849
isComposerDraftEmpty,
50+
isNewTaskDraftKey,
4951
removeComposerDraftAttachment,
5052
replaceComposerDraftAttachments,
53+
retargetNewTaskDraft,
5154
scheduleUnusedComposerAttachmentCleanup,
5255
setComposerDraftText,
5356
setStickyComposerModelSelection,
@@ -169,6 +172,12 @@ type NewTaskFlowContextValue = {
169172
readonly filteredBranches: ReadonlyArray<VcsRef>;
170173
readonly reset: () => void;
171174
readonly setProject: (project: EnvironmentProject) => void;
175+
/**
176+
* Binds the composer to an existing new-task draft (a row in the thread
177+
* list). Returns false when the draft is gone, so the caller can fall back
178+
* to a fresh one.
179+
*/
180+
readonly openDraft: (draftKey: string) => boolean;
172181
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
173182
readonly setSelectedModelKey: (
174183
key: string | null,
@@ -232,6 +241,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
232241
? selectedEnvironmentIdOverride
233242
: (projects[0]?.environmentId ?? null);
234243
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
244+
// The new-task draft the composer is bound to. Null until a project is
245+
// chosen; each New Task entry mints its own, so a project can hold several.
246+
const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
235247
const [submitting, setSubmitting] = useState(false);
236248
const [branchQuery, setBranchQuery] = useState("");
237249
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
@@ -247,6 +259,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
247259
const reset = useCallback(() => {
248260
setSelectedEnvironmentId(null);
249261
setSelectedProjectKey(null);
262+
setActiveDraftKey(null);
250263
setSubmitting(false);
251264
setBranchQuery("");
252265
setExpandedProvider(null);
@@ -367,12 +380,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
367380
selectedProject?.environmentId ?? null,
368381
);
369382
// While a queued pending task is being edited its draft lives under a key
370-
// scoped to the queued message, so per-project new-task drafts stay intact.
383+
// scoped to the queued message, so new-task drafts stay intact.
371384
const selectedProjectDraftKey = editingPendingTask
372385
? pendingTaskDraftKey(editingPendingTask.messageId)
373386
: selectedProject
374-
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
387+
? activeDraftKey
375388
: null;
389+
// selectedProject can resolve without setProject ever running (the
390+
// environment's first project is the fallback, and the draft screen skips
391+
// setProject when the route's project already matches it). The composer
392+
// still needs a draft to write into, so bind one the moment a project is
393+
// in view and nothing else owns the key.
394+
useEffect(() => {
395+
if (activeDraftKey !== null || editingPendingTask !== null || selectedProject === null) {
396+
return;
397+
}
398+
setActiveDraftKey(
399+
createNewTaskDraft({
400+
environmentId: selectedProject.environmentId,
401+
projectId: selectedProject.id,
402+
}),
403+
);
404+
}, [activeDraftKey, editingPendingTask, selectedProject]);
376405
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
377406
const prompt = selectedProjectDraft.text;
378407
const attachments = selectedProjectDraft.attachments;
@@ -625,20 +654,19 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
625654
);
626655
}, [availableBranches, branchQuery]);
627656

628-
// New-task drafts are keyed per (environment, project), so retargeting the
629-
// composer would otherwise show the target's empty draft and strand what the
630-
// user typed under the old key.
657+
// The composer's draft follows the project it will be sent to: switching
658+
// mid-compose keeps the same draft and moves it, so typed text follows the
659+
// user. A pending-task edit owns its own key and is untouched here.
631660
const carryDraftContentTo = useCallback(
632661
(project: EnvironmentProject) => {
633-
const nextDraftKey = `new-task:${scopedProjectKey(project.environmentId, project.id)}`;
634-
if (
635-
selectedProjectDraftKey?.startsWith("new-task:") &&
636-
selectedProjectDraftKey !== nextDraftKey
637-
) {
638-
void copyComposerDraftContentIfEmpty(selectedProjectDraftKey, nextDraftKey);
662+
const target = { environmentId: project.environmentId, projectId: project.id };
663+
if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
664+
retargetNewTaskDraft(activeDraftKey, target);
665+
} else if (!editingPendingTaskRef.current) {
666+
setActiveDraftKey(createNewTaskDraft(target));
639667
}
640668
},
641-
[selectedProjectDraftKey],
669+
[activeDraftKey],
642670
);
643671

644672
const setProject = useCallback(
@@ -650,6 +678,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
650678
[carryDraftContentTo],
651679
);
652680

681+
const openDraft = useCallback(
682+
(draftKey: string): boolean => {
683+
const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
684+
const stamp = draft?.project;
685+
if (!isNewTaskDraftKey(draftKey) || !stamp) {
686+
return false;
687+
}
688+
// The stamped project must be loaded: selectedProject falls back to
689+
// the environment's first project otherwise, and the draft would be
690+
// sent somewhere the user never chose.
691+
const projectLoaded = projects.some(
692+
(project) =>
693+
project.environmentId === stamp.environmentId && project.id === stamp.projectId,
694+
);
695+
if (!projectLoaded) {
696+
return false;
697+
}
698+
setActiveDraftKey(draftKey);
699+
setSelectedEnvironmentId(stamp.environmentId);
700+
setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
701+
return true;
702+
},
703+
[projects],
704+
);
705+
653706
const selectEnvironment = useCallback(
654707
(environmentId: EnvironmentId) => {
655708
const match = resolveEnvironmentProjectMatch(
@@ -1085,6 +1138,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
10851138
filteredBranches,
10861139
reset,
10871140
setProject,
1141+
openDraft,
10881142
selectEnvironment,
10891143
setSelectedModelKey,
10901144
setWorkspaceMode,
@@ -1148,6 +1202,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
11481202
selectedProjectKey,
11491203
selectedWorktreePath,
11501204
setProject,
1205+
openDraft,
11511206
selectBranch,
11521207
selectEnvironment,
11531208
setInteractionMode,

‎apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,24 @@ describe("draft upload scope and offline submission", () => {
230230
);
231231
});
232232

233+
it("reads an id-keyed new-task draft's environment from its project stamp", () => {
234+
const stamped = {
235+
project: {
236+
environmentId,
237+
projectId: "project" as never,
238+
createdAt: "2026-09-05T00:00:00.000Z",
239+
},
240+
};
241+
expect(composerDraftEnvironmentId("new-task:abc123-def456", [], stamped)).toBe(environmentId);
242+
// An id-keyed draft that lost its stamp belongs to nobody: uploads must
243+
// not start and sign-out must not sweep it into some other environment.
244+
expect(composerDraftEnvironmentId("new-task:abc123-def456", [])).toBeNull();
245+
// The stamp wins over a legacy-looking key when both are present.
246+
expect(composerDraftEnvironmentId("new-task:environment-2:project", [], stamped)).toBe(
247+
environmentId,
248+
);
249+
});
250+
233251
it("allows offline queuing while a connected composer waits for upload or retry", () => {
234252
const key = composerAttachmentUploadKey(environmentId, "file");
235253
const input = {

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

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
22
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
33

4+
import { parseLegacyNewTaskDraftKey } from "../state/new-task-draft-key";
45
import type { DraftComposerAttachment } from "./composerImages";
56

67
export interface ComposerAttachmentUploadRequest {
@@ -20,22 +21,35 @@ export function composerAttachmentUploadKey(
2021
return `${environmentId}:${attachmentId}`;
2122
}
2223

24+
/**
25+
* Which environment a composer draft belongs to. Thread drafts carry it in
26+
* the key; pending-task editor drafts borrow it from the queued message;
27+
* new-task drafts carry it in their project stamp (legacy project-keyed
28+
* new-task drafts still parse from the key until they are migrated on load).
29+
*/
2330
export function composerDraftEnvironmentId(
2431
draftKey: string,
2532
queuedMessages: ReadonlyArray<{
2633
readonly messageId: string;
2734
readonly environmentId: EnvironmentId;
2835
}>,
36+
draft?: { readonly project?: { readonly environmentId: EnvironmentId } },
2937
): EnvironmentId | null {
3038
if (draftKey.startsWith("pending-task:")) {
3139
return (
3240
queuedMessages.find((message) => `pending-task:${message.messageId}` === draftKey)
3341
?.environmentId ?? null
3442
);
3543
}
36-
const scope = draftKey.startsWith("new-task:") ? draftKey.slice("new-task:".length) : draftKey;
37-
const separator = scope.lastIndexOf(":");
38-
return separator > 0 ? EnvironmentId.make(scope.slice(0, separator)) : null;
44+
if (draftKey.startsWith("new-task:")) {
45+
if (draft?.project) {
46+
return draft.project.environmentId;
47+
}
48+
const legacy = parseLegacyNewTaskDraftKey(draftKey);
49+
return legacy === null ? null : EnvironmentId.make(legacy.environmentId);
50+
}
51+
const separator = draftKey.lastIndexOf(":");
52+
return separator > 0 ? EnvironmentId.make(draftKey.slice(0, separator)) : null;
3953
}
4054

4155
type UploadServerConfig = {

‎apps/mobile/src/state/composer-attachment-uploads.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export function useComposerAttachmentUploadWorker() {
7979
let retained = false;
8080
for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
8181
if (
82-
composerDraftEnvironmentId(key, queued) === environmentId &&
82+
composerDraftEnvironmentId(key, queued, draft) === environmentId &&
8383
draft.attachments.some((candidate) => candidate.id === attachment.id)
8484
) {
8585
retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
@@ -113,7 +113,7 @@ export function useComposerAttachmentUploadWorker() {
113113
.map((environment) => environment.environmentId),
114114
);
115115
const requests = Object.entries(drafts).flatMap(([key, draft]) => {
116-
const environmentId = composerDraftEnvironmentId(key, queued);
116+
const environmentId = composerDraftEnvironmentId(key, queued, draft);
117117
if (environmentId === null || !connected.has(environmentId)) return [];
118118
return draft.attachments
119119
.filter((attachment) =>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const NEW_TASK_DRAFT_PREFIX = "new-task:";
2+
3+
/** Every new-task draft key: `new-task:<draftId>`. */
4+
export function newTaskDraftKey(draftId: string): string {
5+
return `${NEW_TASK_DRAFT_PREFIX}${draftId}`;
6+
}
7+
8+
export function isNewTaskDraftKey(draftKey: string): boolean {
9+
return draftKey.startsWith(NEW_TASK_DRAFT_PREFIX);
10+
}
11+
12+
/**
13+
* Builds before drafts were id-keyed used `new-task:<environmentId>:<projectId>`,
14+
* one slot per project. Ids are UUIDs and never contain a colon, so a colon
15+
* after the prefix marks the legacy shape. Returns the split scope, or null
16+
* when the key is not legacy.
17+
*/
18+
export function parseLegacyNewTaskDraftKey(
19+
draftKey: string,
20+
): { readonly environmentId: string; readonly projectId: string } | null {
21+
if (!isNewTaskDraftKey(draftKey)) {
22+
return null;
23+
}
24+
const scope = draftKey.slice(NEW_TASK_DRAFT_PREFIX.length);
25+
const separator = scope.lastIndexOf(":");
26+
if (separator <= 0 || separator === scope.length - 1) {
27+
return null;
28+
}
29+
return { environmentId: scope.slice(0, separator), projectId: scope.slice(separator + 1) };
30+
}

0 commit comments

Comments
 (0)