@devries-cameron20 / t3code-1 / commits / 3b48b52326
Fork 0

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

refactor(mobile): new-task branch defaults are derived, not written after render (#25706)

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

Julius Marminge committed Oct 26, 2026 at 19:53 UTC 3b48b523267617cd9cff8950e4e1cf82b45cfff4
12 files changed +537 -191
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+1 -10
@@ -88,7 +88,6 @@ import { resolveDraftProjectSelection } from "./new-task-project-selection";
88 import {
89 resolveNewTaskBranchLabel,
90 resolveNewTaskWorkspaceLabel,
91 - resolveNewTaskWorkspaceSelection,
91 } from "./new-task-context-presentation";
92 import { useIncomingShare } from "../sharing/IncomingShareProvider";
93 import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
@@ -808,15 +807,7 @@ export function NewTaskDraftScreen(props: {
807 draft.modelSelection ?? null,
808 selectedProject.id,
809 ) ?? flow.selectedModel;
811 - const workspaceSelection = resolveNewTaskWorkspaceSelection({
812 - selection: draft.workspaceSelection,
813 - fallback: {
814 - mode: flow.workspaceMode,
815 - branch: flow.selectedBranchName,
816 - worktreePath: flow.selectedWorktreePath,
817 - },
818 - isGitRepo: flow.isGitRepo,
819 - });
810 + const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
811 const workspaceMode = workspaceSelection.mode;
812 const selectedBranchName = workspaceSelection.branch;
813 const initialMessageText = draft.text.trim();
apps/mobile/src/features/threads/new-task-context-presentation.test.ts
+64
@@ -1,6 +1,7 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 + fillNewTaskWorkspaceBranch,
5 resolveNewTaskBranchLabel,
6 resolveNewTaskBranchWorktreePath,
7 resolveNewTaskLocalWorkspaceSelection,
@@ -105,3 +106,66 @@ describe("resolveNewTaskBranchWorktreePath", () => {
106 ).toBeNull();
107 });
108 });
109 +
110 +describe("fillNewTaskWorkspaceBranch", () => {
111 + const branches = [
112 + { name: "origin/main", current: false, isDefault: true, isRemote: true },
113 + { name: "feature", current: true, isDefault: false, worktreePath: "/repo-feature" },
114 + ];
115 + const base = {
116 + branches,
117 + projectCwd: "/repo",
118 + worktreeDefaultSettled: true,
119 + };
120 +
121 + it("bases a new worktree on the default branch, even when only the remote has it", () => {
122 + expect(
123 + fillNewTaskWorkspaceBranch({
124 + ...base,
125 + selection: { mode: "worktree", branch: null, worktreePath: null },
126 + }),
127 + ).toEqual({ mode: "worktree", branch: "origin/main", worktreePath: null });
128 + });
129 +
130 + it("waits for the workspace default to settle before picking a base", () => {
131 + const selection = { mode: "worktree", branch: null, worktreePath: null } as const;
132 + expect(fillNewTaskWorkspaceBranch({ ...base, selection, worktreeDefaultSettled: false })).toBe(
133 + selection,
134 + );
135 + });
136 +
137 + it("follows the current checkout only for a local selection the user just chose", () => {
138 + const selection = { mode: "local", branch: null, worktreePath: null } as const;
139 + expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toBe(selection);
140 + expect(
141 + fillNewTaskWorkspaceBranch({
142 + ...base,
143 + selection: { ...selection, followsCurrentCheckout: true },
144 + }),
145 + ).toEqual({
146 + mode: "local",
147 + branch: "feature",
148 + worktreePath: "/repo-feature",
149 + followsCurrentCheckout: true,
150 + });
151 + });
152 +
153 + it("fills the current branch once refs arrive after local mode was chosen", () => {
154 + const selection = {
155 + mode: "local",
156 + branch: null,
157 + worktreePath: null,
158 + followsCurrentCheckout: true,
159 + } as const;
160 + expect(fillNewTaskWorkspaceBranch({ ...base, branches: [], selection })).toBe(selection);
161 + expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toMatchObject({
162 + branch: "feature",
163 + worktreePath: "/repo-feature",
164 + });
165 + });
166 +
167 + it("keeps an explicit branch", () => {
168 + const selection = { mode: "worktree", branch: "release", worktreePath: null } as const;
169 + expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toBe(selection);
170 + });
171 +});
apps/mobile/src/features/threads/new-task-context-presentation.ts
+68
@@ -111,3 +111,71 @@ export function filterNewTaskBranches<T extends { readonly name: string }>(
111 ? branches
112 : branches.filter((branch) => branch.name.toLowerCase().includes(query));
113 }
114 +
115 +/**
116 + * A worktree with no chosen base starts from the default branch, and a local
117 + * selection the user just switched to follows the current checkout until refs
118 + * load. Both are derived, never written back, so a late ref list or t3.json
119 + * default still wins.
120 + */
121 +export function fillNewTaskWorkspaceBranch(input: {
122 + readonly selection: ComposerDraftWorkspaceSelection;
123 + readonly branches: ReadonlyArray<{
124 + readonly name: string;
125 + readonly current: boolean;
126 + readonly isDefault: boolean;
127 + readonly isRemote?: boolean;
128 + readonly worktreePath?: string | null;
129 + }>;
130 + readonly projectCwd: string | null;
131 + readonly worktreeDefaultSettled: boolean;
132 +}): ComposerDraftWorkspaceSelection {
133 + const { selection } = input;
134 + if (selection.branch !== null) return selection;
135 + if (selection.mode === "worktree") {
136 + // The default may only exist as origin/<default>, so search remote refs too.
137 + const base =
138 + input.branches.find((branch) => branch.isDefault) ??
139 + input.branches.find((branch) => !branch.isRemote && branch.current) ??
140 + null;
141 + return input.worktreeDefaultSettled && base
142 + ? { ...selection, branch: base.name, worktreePath: null }
143 + : selection;
144 + }
145 + if (!selection.followsCurrentCheckout || input.projectCwd === null) return selection;
146 + const local = resolveNewTaskLocalWorkspaceSelection({
147 + branches: input.branches.filter((branch) => !branch.isRemote),
148 + projectCwd: input.projectCwd,
149 + });
150 + return local.awaitsCurrentBranch
151 + ? selection
152 + : { ...selection, branch: local.branch, worktreePath: local.worktreePath };
153 +}
154 +
155 +/**
156 + * The workspace a new-task draft starts in: its own selection, else the
157 + * project's default mode, with the branch filled in as above. The new-task
158 + * flow, its send path and the home pending-drafts list all resolve through
159 + * this, so what each shows is what is sent.
160 + */
161 +export function resolveNewTaskDraftWorkspace(input: {
162 + readonly selection: ComposerDraftWorkspaceSelection | undefined;
163 + readonly canChooseWorkspace: boolean;
164 + readonly defaultMode: WorkspaceMode;
165 + readonly defaultModeSettled: boolean;
166 + readonly isGitRepo: boolean;
167 + readonly branches: Parameters<typeof fillNewTaskWorkspaceBranch>[0]["branches"];
168 + readonly projectCwd: string | null;
169 +}): ComposerDraftWorkspaceSelection {
170 + const selection = input.canChooseWorkspace ? input.selection : undefined;
171 + return fillNewTaskWorkspaceBranch({
172 + selection: resolveNewTaskWorkspaceSelection({
173 + selection,
174 + fallback: { mode: input.defaultMode, branch: null, worktreePath: null },
175 + isGitRepo: input.isGitRepo,
176 + }),
177 + branches: input.branches,
178 + projectCwd: input.projectCwd,
179 + worktreeDefaultSettled: selection?.mode !== undefined || input.defaultModeSettled,
180 + });
181 +}
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+42 -177
@@ -1,14 +1,10 @@
1 import { ActiveNewTaskContext } from "../../state/active-new-task";
2 import * as Dialog from "../../components/ui/Dialog";
3 -import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
4 -import { useEnvironmentPresentation } from "../../state/presentation";
5 -import { environmentSession } from "../../state/session";
3 import React, { useCallback, useEffect, useRef, useState } from "react";
4
5 import type {
6 EnvironmentId,
7 ModelSelection,
11 - ProjectReadFileResult,
8 ProviderInteractionMode,
9 ProviderOptionSelection,
10 RuntimeMode,
@@ -17,24 +13,15 @@ import type {
13 import {
14 CommandId,
15 DEFAULT_PROVIDER_INTERACTION_MODE,
20 - DEFAULT_SERVER_SETTINGS,
16 MessageId,
17 repositoryGroupingKeyOf,
23 - T3_PROJECT_FILE_NAME,
18 ThreadId,
19 } from "@t3tools/contracts";
20 import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
27 -import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
28 -import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
21 import * as Arr from "effect/Array";
22 import { pipe } from "effect/Function";
23
32 -import {
33 - useEnvironmentServerConfig,
34 - useProjects,
35 - useServerConfigs,
36 - useThreadShells,
37 -} from "../../state/entities";
24 +import { useProjects, useServerConfigs, useThreadShells } from "../../state/entities";
25 import type { TurnCommandMetadata } from "../../lib/commandMetadata";
26 import type { DraftComposerAttachment } from "../../lib/composerImages";
27 import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
@@ -53,6 +40,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
40 import {
41 appendComposerDraftAttachments,
42 type ComposerDraftInsertion,
43 + type ComposerDraftWorkspaceSelection,
44 composerDraftsAtom,
45 createNewTaskDraft,
46 getComposerDraftSnapshot,
@@ -83,7 +71,6 @@ import {
71 isAtomCommandInterrupted,
72 squashAtomCommandFailure,
73 } from "@t3tools/client-runtime/state/runtime";
86 -import { isScratchProject } from "@t3tools/client-runtime/state/projects";
74 import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
75 import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
76 import {
@@ -98,13 +85,13 @@ import {
85 } from "../../state/legacy-plan-mode";
86 import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
87 import {
88 + resolveNewTaskDraftWorkspace,
89 resolveNewTaskBranchWorktreePath,
90 resolveNewTaskLocalWorkspaceSelection,
103 - resolveNewTaskWorkspaceSelection,
91 } from "./new-task-context-presentation";
92 import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
93 +import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
94 import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
107 -import { useOlderSettledCount } from "../../state/olderSettledShelf";
95
96 type WorkspaceMode = "local" | "worktree";
97
@@ -139,6 +126,9 @@ type NewTaskFlowContextValue = {
126 readonly canChooseWorkspace: boolean;
127 readonly selectedBranchName: string | null;
128 readonly selectedWorktreePath: string | null;
129 + readonly resolveWorkspaceSelection: (
130 + selection: ComposerDraftWorkspaceSelection | undefined,
131 + ) => ComposerDraftWorkspaceSelection;
132 readonly startFromOrigin: boolean;
133 readonly pullRequestReference: string | undefined;
134 readonly draftKey: string | null;
@@ -239,7 +229,6 @@ export function NewTaskFlowProvider(
229 const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
230 const [submitting, setSubmitting] = useState(false);
231 const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
242 - const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
232
233 const reset = useCallback(() => {
234 setSelectedEnvironmentId(null);
@@ -247,7 +236,6 @@ export function NewTaskFlowProvider(
236 setActiveDraftKey(null);
237 setSubmitting(false);
238 setExpandedProvider(null);
250 - pendingLocalBranchSyncDraftKeysRef.current.clear();
239 }, []);
240
241 const projectsForEnvironment = pipe(
@@ -262,12 +250,9 @@ export function NewTaskFlowProvider(
250 projectsForEnvironment[0] ??
251 null;
252
265 - const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
266 - selectedProject?.environmentId ?? null,
267 - );
268 - const isScratchDraft =
269 - selectedProject !== null &&
270 - isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
253 + const projectDefaults = useNewTaskProjectDefaults(selectedProject);
254 + const selectedEnvironmentServerConfig = projectDefaults.serverConfig;
255 + const isScratchDraft = projectDefaults.isScratch;
256 const serverConfigs = useServerConfigs();
257 const { connectedEnvironments } = useRemoteConnectionStatus();
258 const scratchEnvironments = connectedEnvironments.filter(
@@ -375,73 +360,31 @@ export function NewTaskFlowProvider(
360 });
361 const knownIsGitRepo = projectGitStatus.data?.isRepo ?? projectBranches.data?.isRepo ?? null;
362 const isGitRepo = knownIsGitRepo ?? true;
378 - const fileAccessSession = useEnvironmentQuery(
379 - selectedProject !== null && selectedProject.workspaceRoot !== ""
380 - ? environmentSession.sessionStateAtom(selectedProject.environmentId)
381 - : null,
382 - );
383 - const fileEnvironment = useEnvironmentPresentation(selectedProject?.environmentId ?? null);
384 - const fileAccess = resolveFilesystemReadAccess({
385 - isCatalogReady: fileEnvironment.isReady,
386 - connection: fileEnvironment.presentation?.connection ?? null,
387 - session: fileAccessSession.data,
388 - sessionError: fileAccessSession.error,
389 - });
390 - const { canReadFiles } = fileAccess;
391 - const fileAccessPending =
392 - selectedProject !== null && selectedProject.workspaceRoot !== "" && fileAccess.isPending;
393 - const t3ProjectFileQuery = useEnvironmentQuery(
394 - canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
395 - ? projectEnvironment.readFile({
396 - environmentId: selectedProject.environmentId,
397 - input: {
398 - cwd: selectedProject.workspaceRoot,
399 - relativePath: T3_PROJECT_FILE_NAME,
400 - allowMissing: true,
401 - },
402 - })
403 - : null,
404 - );
405 - const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
406 - const t3ProjectFile =
407 - t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
408 - ? null
409 - : parseT3ProjectFile(t3ProjectFileData.contents);
410 - const projectSettings = resolveProjectSettings(
411 - selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
412 - selectedProject?.id ?? null,
413 - selectedProject,
414 - t3ProjectFile,
415 - );
363 + const projectSettings = projectDefaults.projectSettings;
364 const canChooseWorkspace = !isScratchDraft;
417 - const selectedProjectOlderSettledCount = useOlderSettledCount(selectedProject);
418 - const selectedProjectHasThreads =
419 - selectedProject !== null &&
420 - (selectedProjectOlderSettledCount > 0 ||
421 - threads.some(
422 - (thread) =>
423 - thread.environmentId === selectedProject.environmentId &&
424 - thread.projectId === selectedProject.id,
425 - ));
426 - const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace
427 - ? resolveNewThreadEnvMode({
428 - projectSettings,
429 - workspaceRoot: selectedProject?.workspaceRoot ?? null,
430 - newProjectsRoot: selectedEnvironmentServerConfig?.newProjectsRoot,
431 - projectHasThreads: selectedProjectHasThreads,
432 - })
433 - : "local";
434 - // Do not persist the provisional workspace default while t3.json is loading; it would override
435 - // the file's eventual default.
436 - const defaultWorkspaceModeSettled =
437 - selectedProjectDraft.workspaceSelection?.mode !== undefined ||
438 - projectSettings.sources.defaultThreadEnvMode !== "environment" ||
439 - (!t3ProjectFileQuery.isPending && !fileAccessPending);
440 - const workspaceSelection = resolveNewTaskWorkspaceSelection({
441 - selection: canChooseWorkspace ? selectedProjectDraft.workspaceSelection : undefined,
442 - fallback: { mode: defaultWorkspaceMode, branch: null, worktreePath: null },
443 - isGitRepo,
365 + const defaultWorkspaceMode: WorkspaceMode = projectDefaults.defaultWorkspaceMode;
366 + const branchState = usePaginatedBranches({
367 + environmentId: selectedProject?.environmentId ?? null,
368 + cwd: selectedProject?.workspaceRoot || null,
369 });
370 + const branchesLoading = branchState.isPending && branchState.data === null;
371 + const allBranchRefs = branchState.refs;
372 + const availableBranches = pipe(
373 + allBranchRefs,
374 + Arr.filter((branch) => !branch.isRemote),
375 + );
376 +
377 + const resolveWorkspaceSelection = (selection: ComposerDraftWorkspaceSelection | undefined) =>
378 + resolveNewTaskDraftWorkspace({
379 + selection,
380 + canChooseWorkspace,
381 + defaultMode: defaultWorkspaceMode,
382 + defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled,
383 + isGitRepo,
384 + branches: allBranchRefs,
385 + projectCwd: selectedProject?.workspaceRoot ?? null,
386 + });
387 + const workspaceSelection = resolveWorkspaceSelection(selectedProjectDraft.workspaceSelection);
388 const workspaceMode = workspaceSelection.mode;
389 const selectedBranchName = workspaceSelection.branch;
390 const selectedWorktreePath = workspaceSelection.worktreePath;
@@ -584,16 +527,6 @@ export function NewTaskFlowProvider(
527 }
528 replaceComposerDraftAttachments(selectedProjectDraftKey, []);
529 };
587 - const branchState = usePaginatedBranches({
588 - environmentId: selectedProject?.environmentId ?? null,
589 - cwd: selectedProject?.workspaceRoot || null,
590 - });
591 - const branchesLoading = branchState.isPending && branchState.data === null;
592 - const allBranchRefs = branchState.refs;
593 - const availableBranches = pipe(
594 - allBranchRefs,
595 - Arr.filter((branch) => !branch.isRemote),
596 - );
530
531 const carryDraftContentTo = (project: EnvironmentProject) => {
532 const target = { environmentId: project.environmentId, projectId: project.id };
@@ -690,60 +623,24 @@ export function NewTaskFlowProvider(
623 branches: availableBranches,
624 projectCwd: selectedProject.workspaceRoot,
625 });
693 - if (mode === "local" && localSelection.awaitsCurrentBranch) {
694 - pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
695 - } else {
696 - pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
697 - }
626 updateComposerDraftSettings(selectedProjectDraftKey, {
627 workspaceSelection: {
628 mode,
629 branch: mode === "local" ? localSelection.branch : selectedBranchName,
630 worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
631 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
632 + // Refs have not named the current branch yet; the selection follows it.
633 + ...(mode === "local" && localSelection.awaitsCurrentBranch
634 + ? { followsCurrentCheckout: true }
635 + : {}),
636 },
637 });
638 };
639
708 - useEffect(() => {
709 - if (
710 - workspaceMode !== "local" ||
711 - !selectedProject ||
712 - !selectedProjectDraftKey ||
713 - !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
714 - ) {
715 - return;
716 - }
717 - const localSelection = resolveNewTaskLocalWorkspaceSelection({
718 - branches: availableBranches,
719 - projectCwd: selectedProject.workspaceRoot,
720 - });
721 - if (localSelection.awaitsCurrentBranch) {
722 - return;
723 - }
724 -
725 - pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
726 - updateComposerDraftSettings(selectedProjectDraftKey, {
727 - workspaceSelection: {
728 - mode: "local",
729 - branch: localSelection.branch,
730 - worktreePath: localSelection.worktreePath,
731 - ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
732 - },
733 - });
734 - }, [
735 - availableBranches,
736 - draftStartFromOrigin,
737 - selectedProject,
738 - selectedProjectDraftKey,
739 - workspaceMode,
740 - ]);
741 -
640 const selectBranch = (branch: VcsRef) => {
641 if (!selectedProject || !selectedProjectDraftKey) {
642 return;
643 }
746 - pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
644 updateComposerDraftSettings(selectedProjectDraftKey, {
645 workspaceSelection: {
646 mode: workspaceMode,
@@ -768,6 +665,9 @@ export function NewTaskFlowProvider(
665 branch: selectedBranchName,
666 worktreePath: selectedWorktreePath,
667 startFromOrigin: value,
668 + ...(selectedBranchName === null && workspaceSelection.followsCurrentCheckout
669 + ? { followsCurrentCheckout: true }
670 + : {}),
671 },
672 });
673 };
@@ -781,38 +681,6 @@ export function NewTaskFlowProvider(
681 refreshBranches();
682 };
683
784 - useEffect(() => {
785 - if (
786 - !selectedProjectDraftKey ||
787 - !defaultWorkspaceModeSettled ||
788 - workspaceMode !== "worktree" ||
789 - selectedBranchName !== null
790 - ) {
791 - return;
792 - }
793 - // Re-read before replacing: the draft screen can update workspace selection in this same commit.
794 - const live = getComposerDraftSnapshot(selectedProjectDraftKey).workspaceSelection;
795 - if (live && (live.mode !== "worktree" || live.branch !== null)) {
796 - return;
797 - }
798 - // Search unfiltered refs: the default may exist only as origin/<default>, excluded by availableBranches.
799 - const preferredBranch =
800 - allBranchRefs.find((branch) => branch.isDefault) ??
801 - availableBranches.find((branch) => branch.current) ??
802 - null;
803 - if (preferredBranch) {
804 - selectBranch(preferredBranch);
805 - }
806 - }, [
807 - allBranchRefs,
808 - availableBranches,
809 - defaultWorkspaceModeSettled,
810 - selectBranch,
811 - selectedBranchName,
812 - selectedProjectDraftKey,
813 - workspaceMode,
814 - ]);
815 -
684 const setRuntimeMode = (value: RuntimeMode) => {
685 if (selectedProjectDraftKey) {
686 updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
@@ -853,11 +721,7 @@ export function NewTaskFlowProvider(
721 ) {
722 return null;
723 }
856 - const workspaceSelection = resolveNewTaskWorkspaceSelection({
857 - selection: canChooseWorkspace ? draft.workspaceSelection : undefined,
858 - fallback: { mode: workspaceMode, branch: null, worktreePath: null },
859 - isGitRepo,
860 - });
724 + const workspaceSelection = resolveWorkspaceSelection(draft.workspaceSelection);
725 const mode = workspaceSelection.mode;
726 return {
727 environmentId: selectedProject.environmentId,
@@ -911,6 +775,7 @@ export function NewTaskFlowProvider(
775 canChooseWorkspace,
776 selectedBranchName,
777 selectedWorktreePath,
778 + resolveWorkspaceSelection,
779 startFromOrigin,
780 draftKey: selectedProjectDraftKey,
781 pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+28 -1
@@ -45,6 +45,12 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
45 import { useUniwindTheme } from "../../lib/useUniwindTheme";
46 import { useEnvironmentScope } from "../../state/session";
47 import type { PendingNewTask } from "../../state/use-pending-new-tasks";
48 +import {
49 + pendingDraftBranchNeedsRefs,
50 + resolvePendingDraftBranch,
51 +} from "../../state/pending-new-tasks-model";
52 +import { useBranches } from "../../state/queries";
53 +import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
54 import {
55 resolveThreadPrBadgeAction,
56 type ThreadPrPresentation,
@@ -374,7 +380,28 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
380 [deleteLabel, handleDelete, pendingTask.title],
381 );
382 const projectTitle = props.projectTitle ?? props.project?.title ?? pendingTask.projectTitle ?? "";
377 - const branch = pendingTask.branch;
383 + const projectCwd = props.project?.workspaceRoot || null;
384 + // Drafts only; the reads are shared per-project atoms, and queued rows skip them.
385 + const projectDefaults = useNewTaskProjectDefaults(isDraft ? props.project : null);
386 + const draftDefaults = {
387 + canChooseWorkspace: !projectDefaults.isScratch,
388 + defaultMode: projectDefaults.defaultWorkspaceMode,
389 + defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled,
390 + };
391 + const draftBranchRefs = useBranches({
392 + environmentId: pendingTask.environmentId,
393 + cwd:
394 + isDraft && pendingDraftBranchNeedsRefs(pendingTask.draft, draftDefaults) ? projectCwd : null,
395 + });
396 + const branch = isDraft
397 + ? resolvePendingDraftBranch({
398 + draft: pendingTask.draft,
399 + defaults: draftDefaults,
400 + isGitRepo: draftBranchRefs.data?.isRepo ?? true,
401 + branches: draftBranchRefs.data?.refs ?? [],
402 + projectCwd,
403 + })
404 + : pendingTask.branch;
405
406 const handleMenuAction = useCallback(
407 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
apps/mobile/src/features/threads/threadListV2.test.ts
-1
@@ -728,7 +728,6 @@ describe("buildThreadListV2ListItems", () => {
728 projectId: ProjectId.make("project-1"),
729 projectTitle: undefined,
730 projectCwd: undefined,
731 - branch: null,
731 title: "unsent",
732 createdAt: NOW,
733 draftKey: "new-task:unsent",
apps/mobile/src/features/threads/use-new-task-project-defaults.ts new
+81
@@ -0,0 +1,81 @@
1 +import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
2 +import { isScratchProject } from "@t3tools/client-runtime/state/projects";
3 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4 +import type { ProjectReadFileResult } from "@t3tools/contracts";
5 +import { DEFAULT_SERVER_SETTINGS, T3_PROJECT_FILE_NAME } from "@t3tools/contracts";
6 +import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
7 +import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
8 +
9 +import { useEnvironmentServerConfig } from "../../state/entities";
10 +import { useEnvironmentPresentation } from "../../state/presentation";
11 +import { useProjectHasThreads } from "../../state/project-has-threads";
12 +import { projectEnvironment } from "../../state/projects";
13 +import { useEnvironmentQuery } from "../../state/query";
14 +import { environmentSession } from "../../state/session";
15 +
16 +/**
17 + * A project's new-task defaults: server settings merged with its t3.json. The
18 + * new-task flow and the home pending-drafts list both read the default
19 + * workspace mode here, so a draft that never picked one shows what it sends.
20 + * Every read is a shared per-environment or per-project atom.
21 + */
22 +export function useNewTaskProjectDefaults(project: EnvironmentProject | null) {
23 + const serverConfig = useEnvironmentServerConfig(project?.environmentId ?? null);
24 + const isScratch =
25 + project !== null && isScratchProject(project, serverConfig?.scratchWorkspaceRoot);
26 + const hasWorkspace = project !== null && project.workspaceRoot !== "";
27 + const fileAccessSession = useEnvironmentQuery(
28 + hasWorkspace ? environmentSession.sessionStateAtom(project.environmentId) : null,
29 + );
30 + const fileEnvironment = useEnvironmentPresentation(project?.environmentId ?? null);
31 + const fileAccess = resolveFilesystemReadAccess({
32 + isCatalogReady: fileEnvironment.isReady,
33 + connection: fileEnvironment.presentation?.connection ?? null,
34 + session: fileAccessSession.data,
35 + sessionError: fileAccessSession.error,
36 + });
37 + const fileAccessPending = hasWorkspace && fileAccess.isPending;
38 + const t3ProjectFileQuery = useEnvironmentQuery(
39 + fileAccess.canReadFiles && hasWorkspace
40 + ? projectEnvironment.readFile({
41 + environmentId: project.environmentId,
42 + input: {
43 + cwd: project.workspaceRoot,
44 + relativePath: T3_PROJECT_FILE_NAME,
45 + allowMissing: true,
46 + },
47 + })
48 + : null,
49 + );
50 + const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
51 + const t3ProjectFile =
52 + t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
53 + ? null
54 + : parseT3ProjectFile(t3ProjectFileData.contents);
55 + const projectSettings = resolveProjectSettings(
56 + serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
57 + project?.id ?? null,
58 + project,
59 + t3ProjectFile,
60 + );
61 + const projectHasThreads = useProjectHasThreads(project);
62 + const defaultWorkspaceMode = isScratch
63 + ? "local"
64 + : resolveNewThreadEnvMode({
65 + projectSettings,
66 + workspaceRoot: project?.workspaceRoot ?? null,
67 + newProjectsRoot: serverConfig?.newProjectsRoot,
68 + projectHasThreads,
69 + });
70 + // While t3.json loads, the environment default is provisional; t3.json may replace it.
71 + const defaultWorkspaceModeSettled =
72 + projectSettings.sources.defaultThreadEnvMode !== "environment" ||
73 + (!t3ProjectFileQuery.isPending && !fileAccessPending);
74 + return {
75 + serverConfig,
76 + isScratch,
77 + projectSettings,
78 + defaultWorkspaceMode,
79 + defaultWorkspaceModeSettled,
80 + };
81 +}
apps/mobile/src/state/pending-new-tasks-model.test.ts new
+84
@@ -0,0 +1,84 @@
1 +import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import {
5 + type PendingDraftProjectDefaults,
6 + pendingDraftBranchNeedsRefs,
7 + resolvePendingDraftBranch,
8 +} from "./pending-new-tasks-model";
9 +import type { ComposerDraft, ComposerDraftWorkspaceSelection } from "./use-composer-drafts";
10 +
11 +const projectCwd = "/repo";
12 +const localDefault: PendingDraftProjectDefaults = {
13 + canChooseWorkspace: true,
14 + defaultMode: "local",
15 + defaultModeSettled: true,
16 +};
17 +const worktreeDefault: PendingDraftProjectDefaults = { ...localDefault, defaultMode: "worktree" };
18 +const resolve = (
19 + input: Omit<Parameters<typeof resolvePendingDraftBranch>[0], "defaults" | "isGitRepo"> & {
20 + readonly defaults?: PendingDraftProjectDefaults;
21 + },
22 +) => resolvePendingDraftBranch({ defaults: localDefault, isGitRepo: true, ...input });
23 +const branches = [
24 + { name: "feature", current: true, isDefault: false },
25 + { name: "origin/main", current: false, isDefault: true, isRemote: true },
26 +];
27 +
28 +function draft(workspaceSelection?: ComposerDraftWorkspaceSelection): ComposerDraft {
29 + return {
30 + text: "unsent",
31 + attachments: [],
32 + project: {
33 + environmentId: EnvironmentId.make("env-1"),
34 + projectId: ProjectId.make("project-1"),
35 + createdAt: "2026-10-26T00:00:00.000Z",
36 + },
37 + ...(workspaceSelection ? { workspaceSelection } : {}),
38 + };
39 +}
40 +
41 +describe("resolvePendingDraftBranch", () => {
42 + it("shows the project's default for a draft that never picked a mode", () => {
43 + const untouched = draft();
44 + expect(pendingDraftBranchNeedsRefs(untouched, worktreeDefault)).toBe(true);
45 + expect(resolve({ draft: untouched, defaults: worktreeDefault, branches, projectCwd })).toBe(
46 + "origin/main",
47 + );
48 + // Until t3.json settles, the environment default may still be replaced.
49 + expect(
50 + resolve({
51 + draft: untouched,
52 + defaults: { ...worktreeDefault, defaultModeSettled: false },
53 + branches,
54 + projectCwd,
55 + }),
56 + ).toBeNull();
57 + // A local default starts on the checkout without naming a branch, as on main.
58 + expect(pendingDraftBranchNeedsRefs(untouched, localDefault)).toBe(false);
59 + expect(resolve({ draft: untouched, branches, projectCwd })).toBeNull();
60 + });
61 +
62 + it("shows the default base for a worktree draft that never picked one", () => {
63 + const worktree = draft({ mode: "worktree", branch: null, worktreePath: null });
64 + expect(pendingDraftBranchNeedsRefs(worktree, localDefault)).toBe(true);
65 + expect(resolve({ draft: worktree, branches, projectCwd })).toBe("origin/main");
66 + });
67 +
68 + it("shows the current branch for a local draft that follows the checkout", () => {
69 + const local = draft({
70 + mode: "local",
71 + branch: null,
72 + worktreePath: null,
73 + followsCurrentCheckout: true,
74 + });
75 + expect(resolve({ draft: local, branches, projectCwd })).toBe("feature");
76 + expect(resolve({ draft: local, branches: [], projectCwd })).toBeNull();
77 + });
78 +
79 + it("keeps a chosen branch without loading refs", () => {
80 + const chosen = draft({ mode: "local", branch: "release", worktreePath: null });
81 + expect(pendingDraftBranchNeedsRefs(chosen, localDefault)).toBe(false);
82 + expect(resolve({ draft: chosen, branches, projectCwd })).toBe("release");
83 + });
84 +});
apps/mobile/src/state/pending-new-tasks-model.ts
+39 -2
@@ -4,6 +4,7 @@ import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
4 import type { QueuedThreadCreation, QueuedThreadMessage } from "./thread-outbox-model";
5 import { isNewTaskDraftKey } from "./new-task-draft-key";
6 import type { ComposerDraft } from "./use-composer-drafts";
7 +import { resolveNewTaskDraftWorkspace } from "../features/threads/new-task-context-presentation";
8
9 export type PendingNewTask = PendingQueuedTask | PendingDraftTask;
10
@@ -28,7 +29,6 @@ export interface PendingDraftTask {
29 readonly projectId: ProjectId;
30 readonly projectTitle: undefined;
31 readonly projectCwd: undefined;
31 - readonly branch: string | null;
32 readonly title: string;
33 readonly createdAt: string;
34 readonly draftKey: string;
@@ -47,6 +47,44 @@ function draftTitle(draft: ComposerDraft): string {
47 return count === 1 ? "1 attachment" : `${count} attachments`;
48 }
49
50 +/** A project's new-task defaults, as useNewTaskProjectDefaults resolves them. */
51 +export interface PendingDraftProjectDefaults {
52 + readonly canChooseWorkspace: boolean;
53 + readonly defaultMode: "local" | "worktree";
54 + readonly defaultModeSettled: boolean;
55 +}
56 +
57 +/**
58 + * True when the draft's branch is derived from refs rather than stored, so the list must load
59 + * refs to show it.
60 + */
61 +export function pendingDraftBranchNeedsRefs(
62 + draft: ComposerDraft,
63 + defaults: PendingDraftProjectDefaults,
64 +): boolean {
65 + const selection = defaults.canChooseWorkspace ? draft.workspaceSelection : undefined;
66 + return selection === undefined ? defaults.defaultMode === "worktree" : selection.branch === null;
67 +}
68 +
69 +/** The branch a draft will start on, derived the same way the new-task flow and send path do. */
70 +export function resolvePendingDraftBranch(input: {
71 + readonly draft: ComposerDraft;
72 + readonly defaults: PendingDraftProjectDefaults;
73 + readonly isGitRepo: boolean;
74 + readonly branches: Parameters<typeof resolveNewTaskDraftWorkspace>[0]["branches"];
75 + readonly projectCwd: string | null;
76 +}): string | null {
77 + return resolveNewTaskDraftWorkspace({
78 + selection: input.draft.workspaceSelection,
79 + canChooseWorkspace: input.defaults.canChooseWorkspace,
80 + defaultMode: input.defaults.defaultMode,
81 + defaultModeSettled: input.defaults.defaultModeSettled,
82 + isGitRepo: input.isGitRepo,
83 + branches: input.branches,
84 + projectCwd: input.projectCwd,
85 + }).branch;
86 +}
87 +
88 export function buildPendingNewTasks(input: {
89 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
90 readonly drafts: Readonly<Record<string, ComposerDraft>>;
@@ -81,7 +119,6 @@ export function buildPendingNewTasks(input: {
119 projectId: draft.project.projectId,
120 projectTitle: undefined,
121 projectCwd: undefined,
84 - branch: draft.workspaceSelection?.branch ?? null,
122 title: draftTitle(draft),
123 createdAt: draft.project.createdAt,
124 draftKey,
apps/mobile/src/state/project-has-threads.test.ts new
+75
@@ -0,0 +1,75 @@
1 +import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 +import { Atom, AtomRegistry } from "effect/reactivity";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +// The live sources pull in the connection runtime; the factory gets its own.
6 +vi.mock("./threads", () => ({
7 + environmentThreadShells: { environmentThreadRefsByProjectAtom: () => null },
8 + olderSettledThreads: { olderSettledAtom: () => null },
9 +}));
10 +
11 +import { makeProjectHasThreadsAtom } from "./project-has-threads";
12 +
13 +const environmentId = EnvironmentId.make("env-1");
14 +const mine = ProjectId.make("project-mine");
15 +const other = ProjectId.make("project-other");
16 +
17 +function setup() {
18 + const refs = Atom.make<ReadonlyMap<ProjectId, ReadonlyArray<string>>>(new Map());
19 + const older = Atom.make<{ readonly counts: ReadonlyMap<ProjectId, number> } | null>(null);
20 + const family = makeProjectHasThreadsAtom({
21 + threadRefsByProject: () => refs,
22 + olderSettled: () => older,
23 + });
24 + const registry = AtomRegistry.make();
25 + const onChange = vi.fn();
26 + const atom = family(environmentId)(mine);
27 + // Immediate, as useAtomValue reads the value when it subscribes.
28 + const unsubscribe = registry.subscribe(atom, onChange, { immediate: true });
29 + onChange.mockClear();
30 + return { registry, refs, older, atom, onChange, unsubscribe };
31 +}
32 +
33 +describe("project has threads", () => {
34 + it("notifies its reader only when its own project's answer flips", () => {
35 + const { registry, refs, atom, onChange, unsubscribe } = setup();
36 + expect(registry.get(atom)).toBe(false);
37 +
38 + // Another project's threads come and go (streaming shells, new threads).
39 + const broad = vi.fn();
40 + const unsubscribeBroad = registry.subscribe(refs, broad);
41 + registry.set(refs, new Map([[other, ["a"]]]));
42 + registry.set(refs, new Map([[other, ["a", "b"]]]));
43 + // A thread-list reader sees both changes; this project's reader sees none.
44 + expect(broad).toHaveBeenCalledTimes(2);
45 + expect(onChange).not.toHaveBeenCalled();
46 + unsubscribeBroad();
47 +
48 + registry.set(
49 + refs,
50 + new Map([
51 + [other, ["a", "b"]],
52 + [mine, ["c"]],
53 + ]),
54 + );
55 + expect(registry.get(atom)).toBe(true);
56 + expect(onChange).toHaveBeenCalledTimes(1);
57 +
58 + registry.set(
59 + refs,
60 + new Map([
61 + [other, ["a"]],
62 + [mine, ["c", "d"]],
63 + ]),
64 + );
65 + expect(onChange).toHaveBeenCalledTimes(1);
66 + unsubscribe();
67 + });
68 +
69 + it("counts older settled threads the client does not hold", () => {
70 + const { registry, older, atom, unsubscribe } = setup();
71 + registry.set(older, { counts: new Map([[mine, 2]]) });
72 + expect(registry.get(atom)).toBe(true);
73 + unsubscribe();
74 + });
75 +});
apps/mobile/src/state/project-has-threads.ts new
+48
@@ -0,0 +1,48 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
3 +import { Atom } from "effect/reactivity";
4 +
5 +import { environmentThreadShells, olderSettledThreads } from "./threads";
6 +
7 +/**
8 + * Whether a project has any thread, loaded or only counted as older settled.
9 + * A per-project boolean, so readers re-render when it flips, not on every
10 + * thread-shell change (which is frequent while agents work).
11 + */
12 +export function makeProjectHasThreadsAtom(sources: {
13 + readonly threadRefsByProject: (
14 + environmentId: EnvironmentId,
15 + ) => Atom.Atom<ReadonlyMap<ProjectId, ReadonlyArray<unknown>>>;
16 + readonly olderSettled: (
17 + environmentId: EnvironmentId,
18 + ) => Atom.Atom<{ readonly counts: ReadonlyMap<ProjectId, number> } | null>;
19 +}) {
20 + return Atom.family((environmentId: EnvironmentId) =>
21 + Atom.family((projectId: ProjectId) =>
22 + Atom.make(
23 + (get) =>
24 + (get(sources.olderSettled(environmentId))?.counts.get(projectId) ?? 0) > 0 ||
25 + (get(sources.threadRefsByProject(environmentId)).get(projectId)?.length ?? 0) > 0,
26 + ).pipe(Atom.withLabel(`mobile:project-has-threads:${environmentId}:${projectId}`)),
27 + ),
28 + );
29 +}
30 +
31 +const projectHasThreadsAtom = makeProjectHasThreadsAtom({
32 + threadRefsByProject: environmentThreadShells.environmentThreadRefsByProjectAtom,
33 + olderSettled: olderSettledThreads.olderSettledAtom,
34 +});
35 +
36 +const NO_PROJECT_HAS_THREADS = Atom.make(false).pipe(
37 + Atom.withLabel("mobile:project-has-threads:none"),
38 +);
39 +
40 +export function useProjectHasThreads(
41 + project: { readonly environmentId: EnvironmentId; readonly id: ProjectId } | null,
42 +): boolean {
43 + return useAtomValue(
44 + project === null
45 + ? NO_PROJECT_HAS_THREADS
46 + : projectHasThreadsAtom(project.environmentId)(project.id),
47 + );
48 +}
apps/mobile/src/state/use-composer-drafts.ts
+7
@@ -389,6 +389,12 @@ export interface ComposerDraftWorkspaceSelection {
389 readonly worktreePath: string | null;
390 readonly startFromOrigin?: boolean;
391 readonly pullRequestReference?: string;
392 + /**
393 + * Local mode chosen before refs named the current branch. It is never cleared when refs load:
394 + * a local task runs on the checkout, so the draft keeps following it (a later checkout change
395 + * included) until the user picks a branch, rather than pinning the first name refs reported.
396 + */
397 + readonly followsCurrentCheckout?: boolean;
398 }
399
400 export type ComposerDraftSettingsUpdate = Pick<
@@ -402,6 +408,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
408 worktreePath: Schema.NullOr(Schema.String),
409 startFromOrigin: Schema.optional(Schema.Boolean),
410 pullRequestReference: Schema.optional(Schema.String),
411 + followsCurrentCheckout: Schema.optional(Schema.Boolean),
412 });
413
414 const ComposerDraftProjectSchema = Schema.Struct({