Skip to content
TypeScript

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

Julius Marminge3b48b5232676
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 66a041c3f3f..61e88eeb311 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -88,7 +88,6 @@ import { resolveDraftProjectSelection } from "./new-task-project-selection";
import {
resolveNewTaskBranchLabel,
resolveNewTaskWorkspaceLabel,
- resolveNewTaskWorkspaceSelection,
} from "./new-task-context-presentation";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
@@ -808,15 +807,7 @@ export function NewTaskDraftScreen(props: {
draft.modelSelection ?? null,
selectedProject.id,
) ?? flow.selectedModel;
- const workspaceSelection = resolveNewTaskWorkspaceSelection({
- selection: draft.workspaceSelection,
- fallback: {
- mode: flow.workspaceMode,
- branch: flow.selectedBranchName,
- worktreePath: flow.selectedWorktreePath,
- },
- isGitRepo: flow.isGitRepo,
- });
+ const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
const workspaceMode = workspaceSelection.mode;
const selectedBranchName = workspaceSelection.branch;
const initialMessageText = draft.text.trim();
diff --git a/apps/mobile/src/features/threads/new-task-context-presentation.test.ts b/apps/mobile/src/features/threads/new-task-context-presentation.test.ts
index 682b83c74a3..2bb2659dc6d 100644
--- a/apps/mobile/src/features/threads/new-task-context-presentation.test.ts
+++ b/apps/mobile/src/features/threads/new-task-context-presentation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ fillNewTaskWorkspaceBranch,
resolveNewTaskBranchLabel,
resolveNewTaskBranchWorktreePath,
resolveNewTaskLocalWorkspaceSelection,
@@ -105,3 +106,66 @@ describe("resolveNewTaskBranchWorktreePath", () => {
).toBeNull();
});
});
+
+describe("fillNewTaskWorkspaceBranch", () => {
+ const branches = [
+ { name: "origin/main", current: false, isDefault: true, isRemote: true },
+ { name: "feature", current: true, isDefault: false, worktreePath: "/repo-feature" },
+ ];
+ const base = {
+ branches,
+ projectCwd: "/repo",
+ worktreeDefaultSettled: true,
+ };
+
+ it("bases a new worktree on the default branch, even when only the remote has it", () => {
+ expect(
+ fillNewTaskWorkspaceBranch({
+ ...base,
+ selection: { mode: "worktree", branch: null, worktreePath: null },
+ }),
+ ).toEqual({ mode: "worktree", branch: "origin/main", worktreePath: null });
+ });
+
+ it("waits for the workspace default to settle before picking a base", () => {
+ const selection = { mode: "worktree", branch: null, worktreePath: null } as const;
+ expect(fillNewTaskWorkspaceBranch({ ...base, selection, worktreeDefaultSettled: false })).toBe(
+ selection,
+ );
+ });
+
+ it("follows the current checkout only for a local selection the user just chose", () => {
+ const selection = { mode: "local", branch: null, worktreePath: null } as const;
+ expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toBe(selection);
+ expect(
+ fillNewTaskWorkspaceBranch({
+ ...base,
+ selection: { ...selection, followsCurrentCheckout: true },
+ }),
+ ).toEqual({
+ mode: "local",
+ branch: "feature",
+ worktreePath: "/repo-feature",
+ followsCurrentCheckout: true,
+ });
+ });
+
+ it("fills the current branch once refs arrive after local mode was chosen", () => {
+ const selection = {
+ mode: "local",
+ branch: null,
+ worktreePath: null,
+ followsCurrentCheckout: true,
+ } as const;
+ expect(fillNewTaskWorkspaceBranch({ ...base, branches: [], selection })).toBe(selection);
+ expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toMatchObject({
+ branch: "feature",
+ worktreePath: "/repo-feature",
+ });
+ });
+
+ it("keeps an explicit branch", () => {
+ const selection = { mode: "worktree", branch: "release", worktreePath: null } as const;
+ expect(fillNewTaskWorkspaceBranch({ ...base, selection })).toBe(selection);
+ });
+});
diff --git a/apps/mobile/src/features/threads/new-task-context-presentation.ts b/apps/mobile/src/features/threads/new-task-context-presentation.ts
index 479ecfff4ea..44efe4cf048 100644
--- a/apps/mobile/src/features/threads/new-task-context-presentation.ts
+++ b/apps/mobile/src/features/threads/new-task-context-presentation.ts
@@ -111,3 +111,71 @@ export function filterNewTaskBranches<T extends { readonly name: string }>(
? branches
: branches.filter((branch) => branch.name.toLowerCase().includes(query));
}
+
+/**
+ * A worktree with no chosen base starts from the default branch, and a local
+ * selection the user just switched to follows the current checkout until refs
+ * load. Both are derived, never written back, so a late ref list or t3.json
+ * default still wins.
+ */
+export function fillNewTaskWorkspaceBranch(input: {
+ readonly selection: ComposerDraftWorkspaceSelection;
+ readonly branches: ReadonlyArray<{
+ readonly name: string;
+ readonly current: boolean;
+ readonly isDefault: boolean;
+ readonly isRemote?: boolean;
+ readonly worktreePath?: string | null;
+ }>;
+ readonly projectCwd: string | null;
+ readonly worktreeDefaultSettled: boolean;
+}): ComposerDraftWorkspaceSelection {
+ const { selection } = input;
+ if (selection.branch !== null) return selection;
+ if (selection.mode === "worktree") {
+ // The default may only exist as origin/<default>, so search remote refs too.
+ const base =
+ input.branches.find((branch) => branch.isDefault) ??
+ input.branches.find((branch) => !branch.isRemote && branch.current) ??
+ null;
+ return input.worktreeDefaultSettled && base
+ ? { ...selection, branch: base.name, worktreePath: null }
+ : selection;
+ }
+ if (!selection.followsCurrentCheckout || input.projectCwd === null) return selection;
+ const local = resolveNewTaskLocalWorkspaceSelection({
+ branches: input.branches.filter((branch) => !branch.isRemote),
+ projectCwd: input.projectCwd,
+ });
+ return local.awaitsCurrentBranch
+ ? selection
+ : { ...selection, branch: local.branch, worktreePath: local.worktreePath };
+}
+
+/**
+ * The workspace a new-task draft starts in: its own selection, else the
+ * project's default mode, with the branch filled in as above. The new-task
+ * flow, its send path and the home pending-drafts list all resolve through
+ * this, so what each shows is what is sent.
+ */
+export function resolveNewTaskDraftWorkspace(input: {
+ readonly selection: ComposerDraftWorkspaceSelection | undefined;
+ readonly canChooseWorkspace: boolean;
+ readonly defaultMode: WorkspaceMode;
+ readonly defaultModeSettled: boolean;
+ readonly isGitRepo: boolean;
+ readonly branches: Parameters<typeof fillNewTaskWorkspaceBranch>[0]["branches"];
+ readonly projectCwd: string | null;
+}): ComposerDraftWorkspaceSelection {
+ const selection = input.canChooseWorkspace ? input.selection : undefined;
+ return fillNewTaskWorkspaceBranch({
+ selection: resolveNewTaskWorkspaceSelection({
+ selection,
+ fallback: { mode: input.defaultMode, branch: null, worktreePath: null },
+ isGitRepo: input.isGitRepo,
+ }),
+ branches: input.branches,
+ projectCwd: input.projectCwd,
+ worktreeDefaultSettled: selection?.mode !== undefined || input.defaultModeSettled,
+ });
+}
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 a7417328e65..6f049bc5418 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -1,14 +1,10 @@
import { ActiveNewTaskContext } from "../../state/active-new-task";
import * as Dialog from "../../components/ui/Dialog";
-import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
-import { useEnvironmentPresentation } from "../../state/presentation";
-import { environmentSession } from "../../state/session";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type {
EnvironmentId,
ModelSelection,
- ProjectReadFileResult,
ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode,
@@ -17,24 +13,15 @@ import type {
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
- DEFAULT_SERVER_SETTINGS,
MessageId,
repositoryGroupingKeyOf,
- T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
-import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
-import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
-import {
- useEnvironmentServerConfig,
- useProjects,
- useServerConfigs,
- useThreadShells,
-} from "../../state/entities";
+import { useProjects, useServerConfigs, useThreadShells } from "../../state/entities";
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
import type { DraftComposerAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
@@ -53,6 +40,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
import {
appendComposerDraftAttachments,
type ComposerDraftInsertion,
+ type ComposerDraftWorkspaceSelection,
composerDraftsAtom,
createNewTaskDraft,
getComposerDraftSnapshot,
@@ -83,7 +71,6 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import { isScratchProject } from "@t3tools/client-runtime/state/projects";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
import {
@@ -98,13 +85,13 @@ import {
} from "../../state/legacy-plan-mode";
import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
import {
+ resolveNewTaskDraftWorkspace,
resolveNewTaskBranchWorktreePath,
resolveNewTaskLocalWorkspaceSelection,
- resolveNewTaskWorkspaceSelection,
} from "./new-task-context-presentation";
import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
+import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
-import { useOlderSettledCount } from "../../state/olderSettledShelf";
type WorkspaceMode = "local" | "worktree";
@@ -139,6 +126,9 @@ type NewTaskFlowContextValue = {
readonly canChooseWorkspace: boolean;
readonly selectedBranchName: string | null;
readonly selectedWorktreePath: string | null;
+ readonly resolveWorkspaceSelection: (
+ selection: ComposerDraftWorkspaceSelection | undefined,
+ ) => ComposerDraftWorkspaceSelection;
readonly startFromOrigin: boolean;
readonly pullRequestReference: string | undefined;
readonly draftKey: string | null;
@@ -239,7 +229,6 @@ export function NewTaskFlowProvider(
const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
- const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
@@ -247,7 +236,6 @@ export function NewTaskFlowProvider(
setActiveDraftKey(null);
setSubmitting(false);
setExpandedProvider(null);
- pendingLocalBranchSyncDraftKeysRef.current.clear();
}, []);
const projectsForEnvironment = pipe(
@@ -262,12 +250,9 @@ export function NewTaskFlowProvider(
projectsForEnvironment[0] ??
null;
- const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
- selectedProject?.environmentId ?? null,
- );
- const isScratchDraft =
- selectedProject !== null &&
- isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
+ const projectDefaults = useNewTaskProjectDefaults(selectedProject);
+ const selectedEnvironmentServerConfig = projectDefaults.serverConfig;
+ const isScratchDraft = projectDefaults.isScratch;
const serverConfigs = useServerConfigs();
const { connectedEnvironments } = useRemoteConnectionStatus();
const scratchEnvironments = connectedEnvironments.filter(
@@ -375,73 +360,31 @@ export function NewTaskFlowProvider(
});
const knownIsGitRepo = projectGitStatus.data?.isRepo ?? projectBranches.data?.isRepo ?? null;
const isGitRepo = knownIsGitRepo ?? true;
- const fileAccessSession = useEnvironmentQuery(
- selectedProject !== null && selectedProject.workspaceRoot !== ""
- ? environmentSession.sessionStateAtom(selectedProject.environmentId)
- : null,
- );
- const fileEnvironment = useEnvironmentPresentation(selectedProject?.environmentId ?? null);
- const fileAccess = resolveFilesystemReadAccess({
- isCatalogReady: fileEnvironment.isReady,
- connection: fileEnvironment.presentation?.connection ?? null,
- session: fileAccessSession.data,
- sessionError: fileAccessSession.error,
- });
- const { canReadFiles } = fileAccess;
- const fileAccessPending =
- selectedProject !== null && selectedProject.workspaceRoot !== "" && fileAccess.isPending;
- const t3ProjectFileQuery = useEnvironmentQuery(
- canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
- ? projectEnvironment.readFile({
- environmentId: selectedProject.environmentId,
- input: {
- cwd: selectedProject.workspaceRoot,
- relativePath: T3_PROJECT_FILE_NAME,
- allowMissing: true,
- },
- })
- : null,
- );
- const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
- const t3ProjectFile =
- t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
- ? null
- : parseT3ProjectFile(t3ProjectFileData.contents);
- const projectSettings = resolveProjectSettings(
- selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
- selectedProject?.id ?? null,
- selectedProject,
- t3ProjectFile,
- );
+ const projectSettings = projectDefaults.projectSettings;
const canChooseWorkspace = !isScratchDraft;
- const selectedProjectOlderSettledCount = useOlderSettledCount(selectedProject);
- const selectedProjectHasThreads =
- selectedProject !== null &&
- (selectedProjectOlderSettledCount > 0 ||
- threads.some(
- (thread) =>
- thread.environmentId === selectedProject.environmentId &&
- thread.projectId === selectedProject.id,
- ));
- const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace
- ? resolveNewThreadEnvMode({
- projectSettings,
- workspaceRoot: selectedProject?.workspaceRoot ?? null,
- newProjectsRoot: selectedEnvironmentServerConfig?.newProjectsRoot,
- projectHasThreads: selectedProjectHasThreads,
- })
- : "local";
- // Do not persist the provisional workspace default while t3.json is loading; it would override
- // the file's eventual default.
- const defaultWorkspaceModeSettled =
- selectedProjectDraft.workspaceSelection?.mode !== undefined ||
- projectSettings.sources.defaultThreadEnvMode !== "environment" ||
- (!t3ProjectFileQuery.isPending && !fileAccessPending);
- const workspaceSelection = resolveNewTaskWorkspaceSelection({
- selection: canChooseWorkspace ? selectedProjectDraft.workspaceSelection : undefined,
- fallback: { mode: defaultWorkspaceMode, branch: null, worktreePath: null },
- isGitRepo,
+ const defaultWorkspaceMode: WorkspaceMode = projectDefaults.defaultWorkspaceMode;
+ const branchState = usePaginatedBranches({
+ environmentId: selectedProject?.environmentId ?? null,
+ cwd: selectedProject?.workspaceRoot || null,
});
+ const branchesLoading = branchState.isPending && branchState.data === null;
+ const allBranchRefs = branchState.refs;
+ const availableBranches = pipe(
+ allBranchRefs,
+ Arr.filter((branch) => !branch.isRemote),
+ );
+
+ const resolveWorkspaceSelection = (selection: ComposerDraftWorkspaceSelection | undefined) =>
+ resolveNewTaskDraftWorkspace({
+ selection,
+ canChooseWorkspace,
+ defaultMode: defaultWorkspaceMode,
+ defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled,
+ isGitRepo,
+ branches: allBranchRefs,
+ projectCwd: selectedProject?.workspaceRoot ?? null,
+ });
+ const workspaceSelection = resolveWorkspaceSelection(selectedProjectDraft.workspaceSelection);
const workspaceMode = workspaceSelection.mode;
const selectedBranchName = workspaceSelection.branch;
const selectedWorktreePath = workspaceSelection.worktreePath;
@@ -584,16 +527,6 @@ export function NewTaskFlowProvider(
}
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
};
- const branchState = usePaginatedBranches({
- environmentId: selectedProject?.environmentId ?? null,
- cwd: selectedProject?.workspaceRoot || null,
- });
- const branchesLoading = branchState.isPending && branchState.data === null;
- const allBranchRefs = branchState.refs;
- const availableBranches = pipe(
- allBranchRefs,
- Arr.filter((branch) => !branch.isRemote),
- );
const carryDraftContentTo = (project: EnvironmentProject) => {
const target = { environmentId: project.environmentId, projectId: project.id };
@@ -690,60 +623,24 @@ export function NewTaskFlowProvider(
branches: availableBranches,
projectCwd: selectedProject.workspaceRoot,
});
- if (mode === "local" && localSelection.awaitsCurrentBranch) {
- pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
- } else {
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
- }
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode,
branch: mode === "local" ? localSelection.branch : selectedBranchName,
worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
+ // Refs have not named the current branch yet; the selection follows it.
+ ...(mode === "local" && localSelection.awaitsCurrentBranch
+ ? { followsCurrentCheckout: true }
+ : {}),
},
});
};
- useEffect(() => {
- if (
- workspaceMode !== "local" ||
- !selectedProject ||
- !selectedProjectDraftKey ||
- !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
- ) {
- return;
- }
- const localSelection = resolveNewTaskLocalWorkspaceSelection({
- branches: availableBranches,
- projectCwd: selectedProject.workspaceRoot,
- });
- if (localSelection.awaitsCurrentBranch) {
- return;
- }
-
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
- updateComposerDraftSettings(selectedProjectDraftKey, {
- workspaceSelection: {
- mode: "local",
- branch: localSelection.branch,
- worktreePath: localSelection.worktreePath,
- ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
- },
- });
- }, [
- availableBranches,
- draftStartFromOrigin,
- selectedProject,
- selectedProjectDraftKey,
- workspaceMode,
- ]);
-
const selectBranch = (branch: VcsRef) => {
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
@@ -768,6 +665,9 @@ export function NewTaskFlowProvider(
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin: value,
+ ...(selectedBranchName === null && workspaceSelection.followsCurrentCheckout
+ ? { followsCurrentCheckout: true }
+ : {}),
},
});
};
@@ -781,38 +681,6 @@ export function NewTaskFlowProvider(
refreshBranches();
};
- useEffect(() => {
- if (
- !selectedProjectDraftKey ||
- !defaultWorkspaceModeSettled ||
- workspaceMode !== "worktree" ||
- selectedBranchName !== null
- ) {
- return;
- }
- // Re-read before replacing: the draft screen can update workspace selection in this same commit.
- const live = getComposerDraftSnapshot(selectedProjectDraftKey).workspaceSelection;
- if (live && (live.mode !== "worktree" || live.branch !== null)) {
- return;
- }
- // Search unfiltered refs: the default may exist only as origin/<default>, excluded by availableBranches.
- const preferredBranch =
- allBranchRefs.find((branch) => branch.isDefault) ??
- availableBranches.find((branch) => branch.current) ??
- null;
- if (preferredBranch) {
- selectBranch(preferredBranch);
- }
- }, [
- allBranchRefs,
- availableBranches,
- defaultWorkspaceModeSettled,
- selectBranch,
- selectedBranchName,
- selectedProjectDraftKey,
- workspaceMode,
- ]);
-
const setRuntimeMode = (value: RuntimeMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
@@ -853,11 +721,7 @@ export function NewTaskFlowProvider(
) {
return null;
}
- const workspaceSelection = resolveNewTaskWorkspaceSelection({
- selection: canChooseWorkspace ? draft.workspaceSelection : undefined,
- fallback: { mode: workspaceMode, branch: null, worktreePath: null },
- isGitRepo,
- });
+ const workspaceSelection = resolveWorkspaceSelection(draft.workspaceSelection);
const mode = workspaceSelection.mode;
return {
environmentId: selectedProject.environmentId,
@@ -911,6 +775,7 @@ export function NewTaskFlowProvider(
canChooseWorkspace,
selectedBranchName,
selectedWorktreePath,
+ resolveWorkspaceSelection,
startFromOrigin,
draftKey: selectedProjectDraftKey,
pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index 6e82493945f..031b2bd5290 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -45,6 +45,12 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useEnvironmentScope } from "../../state/session";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
+import {
+ pendingDraftBranchNeedsRefs,
+ resolvePendingDraftBranch,
+} from "../../state/pending-new-tasks-model";
+import { useBranches } from "../../state/queries";
+import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
import {
resolveThreadPrBadgeAction,
type ThreadPrPresentation,
@@ -374,7 +380,28 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
[deleteLabel, handleDelete, pendingTask.title],
);
const projectTitle = props.projectTitle ?? props.project?.title ?? pendingTask.projectTitle ?? "";
- const branch = pendingTask.branch;
+ const projectCwd = props.project?.workspaceRoot || null;
+ // Drafts only; the reads are shared per-project atoms, and queued rows skip them.
+ const projectDefaults = useNewTaskProjectDefaults(isDraft ? props.project : null);
+ const draftDefaults = {
+ canChooseWorkspace: !projectDefaults.isScratch,
+ defaultMode: projectDefaults.defaultWorkspaceMode,
+ defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled,
+ };
+ const draftBranchRefs = useBranches({
+ environmentId: pendingTask.environmentId,
+ cwd:
+ isDraft && pendingDraftBranchNeedsRefs(pendingTask.draft, draftDefaults) ? projectCwd : null,
+ });
+ const branch = isDraft
+ ? resolvePendingDraftBranch({
+ draft: pendingTask.draft,
+ defaults: draftDefaults,
+ isGitRepo: draftBranchRefs.data?.isRepo ?? true,
+ branches: draftBranchRefs.data?.refs ?? [],
+ projectCwd,
+ })
+ : pendingTask.branch;
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts
index de7400ba741..18e8a2cf3b8 100644
--- a/apps/mobile/src/features/threads/threadListV2.test.ts
+++ b/apps/mobile/src/features/threads/threadListV2.test.ts
@@ -728,7 +728,6 @@ describe("buildThreadListV2ListItems", () => {
projectId: ProjectId.make("project-1"),
projectTitle: undefined,
projectCwd: undefined,
- branch: null,
title: "unsent",
createdAt: NOW,
draftKey: "new-task:unsent",
diff --git a/apps/mobile/src/features/threads/use-new-task-project-defaults.ts b/apps/mobile/src/features/threads/use-new-task-project-defaults.ts
new file mode 100644
index 00000000000..3190eeb571b
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-new-task-project-defaults.ts
@@ -0,0 +1,81 @@
+import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
+import { isScratchProject } from "@t3tools/client-runtime/state/projects";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+import type { ProjectReadFileResult } from "@t3tools/contracts";
+import { DEFAULT_SERVER_SETTINGS, T3_PROJECT_FILE_NAME } from "@t3tools/contracts";
+import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
+
+import { useEnvironmentServerConfig } from "../../state/entities";
+import { useEnvironmentPresentation } from "../../state/presentation";
+import { useProjectHasThreads } from "../../state/project-has-threads";
+import { projectEnvironment } from "../../state/projects";
+import { useEnvironmentQuery } from "../../state/query";
+import { environmentSession } from "../../state/session";
+
+/**
+ * A project's new-task defaults: server settings merged with its t3.json. The
+ * new-task flow and the home pending-drafts list both read the default
+ * workspace mode here, so a draft that never picked one shows what it sends.
+ * Every read is a shared per-environment or per-project atom.
+ */
+export function useNewTaskProjectDefaults(project: EnvironmentProject | null) {
+ const serverConfig = useEnvironmentServerConfig(project?.environmentId ?? null);
+ const isScratch =
+ project !== null && isScratchProject(project, serverConfig?.scratchWorkspaceRoot);
+ const hasWorkspace = project !== null && project.workspaceRoot !== "";
+ const fileAccessSession = useEnvironmentQuery(
+ hasWorkspace ? environmentSession.sessionStateAtom(project.environmentId) : null,
+ );
+ const fileEnvironment = useEnvironmentPresentation(project?.environmentId ?? null);
+ const fileAccess = resolveFilesystemReadAccess({
+ isCatalogReady: fileEnvironment.isReady,
+ connection: fileEnvironment.presentation?.connection ?? null,
+ session: fileAccessSession.data,
+ sessionError: fileAccessSession.error,
+ });
+ const fileAccessPending = hasWorkspace && fileAccess.isPending;
+ const t3ProjectFileQuery = useEnvironmentQuery(
+ fileAccess.canReadFiles && hasWorkspace
+ ? projectEnvironment.readFile({
+ environmentId: project.environmentId,
+ input: {
+ cwd: project.workspaceRoot,
+ relativePath: T3_PROJECT_FILE_NAME,
+ allowMissing: true,
+ },
+ })
+ : null,
+ );
+ const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
+ const t3ProjectFile =
+ t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
+ ? null
+ : parseT3ProjectFile(t3ProjectFileData.contents);
+ const projectSettings = resolveProjectSettings(
+ serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
+ project?.id ?? null,
+ project,
+ t3ProjectFile,
+ );
+ const projectHasThreads = useProjectHasThreads(project);
+ const defaultWorkspaceMode = isScratch
+ ? "local"
+ : resolveNewThreadEnvMode({
+ projectSettings,
+ workspaceRoot: project?.workspaceRoot ?? null,
+ newProjectsRoot: serverConfig?.newProjectsRoot,
+ projectHasThreads,
+ });
+ // While t3.json loads, the environment default is provisional; t3.json may replace it.
+ const defaultWorkspaceModeSettled =
+ projectSettings.sources.defaultThreadEnvMode !== "environment" ||
+ (!t3ProjectFileQuery.isPending && !fileAccessPending);
+ return {
+ serverConfig,
+ isScratch,
+ projectSettings,
+ defaultWorkspaceMode,
+ defaultWorkspaceModeSettled,
+ };
+}
diff --git a/apps/mobile/src/state/pending-new-tasks-model.test.ts b/apps/mobile/src/state/pending-new-tasks-model.test.ts
new file mode 100644
index 00000000000..6c039d7254c
--- /dev/null
+++ b/apps/mobile/src/state/pending-new-tasks-model.test.ts
@@ -0,0 +1,84 @@
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ type PendingDraftProjectDefaults,
+ pendingDraftBranchNeedsRefs,
+ resolvePendingDraftBranch,
+} from "./pending-new-tasks-model";
+import type { ComposerDraft, ComposerDraftWorkspaceSelection } from "./use-composer-drafts";
+
+const projectCwd = "/repo";
+const localDefault: PendingDraftProjectDefaults = {
+ canChooseWorkspace: true,
+ defaultMode: "local",
+ defaultModeSettled: true,
+};
+const worktreeDefault: PendingDraftProjectDefaults = { ...localDefault, defaultMode: "worktree" };
+const resolve = (
+ input: Omit<Parameters<typeof resolvePendingDraftBranch>[0], "defaults" | "isGitRepo"> & {
+ readonly defaults?: PendingDraftProjectDefaults;
+ },
+) => resolvePendingDraftBranch({ defaults: localDefault, isGitRepo: true, ...input });
+const branches = [
+ { name: "feature", current: true, isDefault: false },
+ { name: "origin/main", current: false, isDefault: true, isRemote: true },
+];
+
+function draft(workspaceSelection?: ComposerDraftWorkspaceSelection): ComposerDraft {
+ return {
+ text: "unsent",
+ attachments: [],
+ project: {
+ environmentId: EnvironmentId.make("env-1"),
+ projectId: ProjectId.make("project-1"),
+ createdAt: "2026-10-26T00:00:00.000Z",
+ },
+ ...(workspaceSelection ? { workspaceSelection } : {}),
+ };
+}
+
+describe("resolvePendingDraftBranch", () => {
+ it("shows the project's default for a draft that never picked a mode", () => {
+ const untouched = draft();
+ expect(pendingDraftBranchNeedsRefs(untouched, worktreeDefault)).toBe(true);
+ expect(resolve({ draft: untouched, defaults: worktreeDefault, branches, projectCwd })).toBe(
+ "origin/main",
+ );
+ // Until t3.json settles, the environment default may still be replaced.
+ expect(
+ resolve({
+ draft: untouched,
+ defaults: { ...worktreeDefault, defaultModeSettled: false },
+ branches,
+ projectCwd,
+ }),
+ ).toBeNull();
+ // A local default starts on the checkout without naming a branch, as on main.
+ expect(pendingDraftBranchNeedsRefs(untouched, localDefault)).toBe(false);
+ expect(resolve({ draft: untouched, branches, projectCwd })).toBeNull();
+ });
+
+ it("shows the default base for a worktree draft that never picked one", () => {
+ const worktree = draft({ mode: "worktree", branch: null, worktreePath: null });
+ expect(pendingDraftBranchNeedsRefs(worktree, localDefault)).toBe(true);
+ expect(resolve({ draft: worktree, branches, projectCwd })).toBe("origin/main");
+ });
+
+ it("shows the current branch for a local draft that follows the checkout", () => {
+ const local = draft({
+ mode: "local",
+ branch: null,
+ worktreePath: null,
+ followsCurrentCheckout: true,
+ });
+ expect(resolve({ draft: local, branches, projectCwd })).toBe("feature");
+ expect(resolve({ draft: local, branches: [], projectCwd })).toBeNull();
+ });
+
+ it("keeps a chosen branch without loading refs", () => {
+ const chosen = draft({ mode: "local", branch: "release", worktreePath: null });
+ expect(pendingDraftBranchNeedsRefs(chosen, localDefault)).toBe(false);
+ expect(resolve({ draft: chosen, branches, projectCwd })).toBe("release");
+ });
+});
diff --git a/apps/mobile/src/state/pending-new-tasks-model.ts b/apps/mobile/src/state/pending-new-tasks-model.ts
index 0ff8d020f49..b7fec4183df 100644
--- a/apps/mobile/src/state/pending-new-tasks-model.ts
+++ b/apps/mobile/src/state/pending-new-tasks-model.ts
@@ -4,6 +4,7 @@ import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
import type { QueuedThreadCreation, QueuedThreadMessage } from "./thread-outbox-model";
import { isNewTaskDraftKey } from "./new-task-draft-key";
import type { ComposerDraft } from "./use-composer-drafts";
+import { resolveNewTaskDraftWorkspace } from "../features/threads/new-task-context-presentation";
export type PendingNewTask = PendingQueuedTask | PendingDraftTask;
@@ -28,7 +29,6 @@ export interface PendingDraftTask {
readonly projectId: ProjectId;
readonly projectTitle: undefined;
readonly projectCwd: undefined;
- readonly branch: string | null;
readonly title: string;
readonly createdAt: string;
readonly draftKey: string;
@@ -47,6 +47,44 @@ function draftTitle(draft: ComposerDraft): string {
return count === 1 ? "1 attachment" : `${count} attachments`;
}
+/** A project's new-task defaults, as useNewTaskProjectDefaults resolves them. */
+export interface PendingDraftProjectDefaults {
+ readonly canChooseWorkspace: boolean;
+ readonly defaultMode: "local" | "worktree";
+ readonly defaultModeSettled: boolean;
+}
+
+/**
+ * True when the draft's branch is derived from refs rather than stored, so the list must load
+ * refs to show it.
+ */
+export function pendingDraftBranchNeedsRefs(
+ draft: ComposerDraft,
+ defaults: PendingDraftProjectDefaults,
+): boolean {
+ const selection = defaults.canChooseWorkspace ? draft.workspaceSelection : undefined;
+ return selection === undefined ? defaults.defaultMode === "worktree" : selection.branch === null;
+}
+
+/** The branch a draft will start on, derived the same way the new-task flow and send path do. */
+export function resolvePendingDraftBranch(input: {
+ readonly draft: ComposerDraft;
+ readonly defaults: PendingDraftProjectDefaults;
+ readonly isGitRepo: boolean;
+ readonly branches: Parameters<typeof resolveNewTaskDraftWorkspace>[0]["branches"];
+ readonly projectCwd: string | null;
+}): string | null {
+ return resolveNewTaskDraftWorkspace({
+ selection: input.draft.workspaceSelection,
+ canChooseWorkspace: input.defaults.canChooseWorkspace,
+ defaultMode: input.defaults.defaultMode,
+ defaultModeSettled: input.defaults.defaultModeSettled,
+ isGitRepo: input.isGitRepo,
+ branches: input.branches,
+ projectCwd: input.projectCwd,
+ }).branch;
+}
+
export function buildPendingNewTasks(input: {
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
readonly drafts: Readonly<Record<string, ComposerDraft>>;
@@ -81,7 +119,6 @@ export function buildPendingNewTasks(input: {
projectId: draft.project.projectId,
projectTitle: undefined,
projectCwd: undefined,
- branch: draft.workspaceSelection?.branch ?? null,
title: draftTitle(draft),
createdAt: draft.project.createdAt,
draftKey,
diff --git a/apps/mobile/src/state/project-has-threads.test.ts b/apps/mobile/src/state/project-has-threads.test.ts
new file mode 100644
index 00000000000..e00116b0c66
--- /dev/null
+++ b/apps/mobile/src/state/project-has-threads.test.ts
@@ -0,0 +1,75 @@
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+// The live sources pull in the connection runtime; the factory gets its own.
+vi.mock("./threads", () => ({
+ environmentThreadShells: { environmentThreadRefsByProjectAtom: () => null },
+ olderSettledThreads: { olderSettledAtom: () => null },
+}));
+
+import { makeProjectHasThreadsAtom } from "./project-has-threads";
+
+const environmentId = EnvironmentId.make("env-1");
+const mine = ProjectId.make("project-mine");
+const other = ProjectId.make("project-other");
+
+function setup() {
+ const refs = Atom.make<ReadonlyMap<ProjectId, ReadonlyArray<string>>>(new Map());
+ const older = Atom.make<{ readonly counts: ReadonlyMap<ProjectId, number> } | null>(null);
+ const family = makeProjectHasThreadsAtom({
+ threadRefsByProject: () => refs,
+ olderSettled: () => older,
+ });
+ const registry = AtomRegistry.make();
+ const onChange = vi.fn();
+ const atom = family(environmentId)(mine);
+ // Immediate, as useAtomValue reads the value when it subscribes.
+ const unsubscribe = registry.subscribe(atom, onChange, { immediate: true });
+ onChange.mockClear();
+ return { registry, refs, older, atom, onChange, unsubscribe };
+}
+
+describe("project has threads", () => {
+ it("notifies its reader only when its own project's answer flips", () => {
+ const { registry, refs, atom, onChange, unsubscribe } = setup();
+ expect(registry.get(atom)).toBe(false);
+
+ // Another project's threads come and go (streaming shells, new threads).
+ const broad = vi.fn();
+ const unsubscribeBroad = registry.subscribe(refs, broad);
+ registry.set(refs, new Map([[other, ["a"]]]));
+ registry.set(refs, new Map([[other, ["a", "b"]]]));
+ // A thread-list reader sees both changes; this project's reader sees none.
+ expect(broad).toHaveBeenCalledTimes(2);
+ expect(onChange).not.toHaveBeenCalled();
+ unsubscribeBroad();
+
+ registry.set(
+ refs,
+ new Map([
+ [other, ["a", "b"]],
+ [mine, ["c"]],
+ ]),
+ );
+ expect(registry.get(atom)).toBe(true);
+ expect(onChange).toHaveBeenCalledTimes(1);
+
+ registry.set(
+ refs,
+ new Map([
+ [other, ["a"]],
+ [mine, ["c", "d"]],
+ ]),
+ );
+ expect(onChange).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
+ it("counts older settled threads the client does not hold", () => {
+ const { registry, older, atom, unsubscribe } = setup();
+ registry.set(older, { counts: new Map([[mine, 2]]) });
+ expect(registry.get(atom)).toBe(true);
+ unsubscribe();
+ });
+});
diff --git a/apps/mobile/src/state/project-has-threads.ts b/apps/mobile/src/state/project-has-threads.ts
new file mode 100644
index 00000000000..55968ca04a2
--- /dev/null
+++ b/apps/mobile/src/state/project-has-threads.ts
@@ -0,0 +1,48 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+import { environmentThreadShells, olderSettledThreads } from "./threads";
+
+/**
+ * Whether a project has any thread, loaded or only counted as older settled.
+ * A per-project boolean, so readers re-render when it flips, not on every
+ * thread-shell change (which is frequent while agents work).
+ */
+export function makeProjectHasThreadsAtom(sources: {
+ readonly threadRefsByProject: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom<ReadonlyMap<ProjectId, ReadonlyArray<unknown>>>;
+ readonly olderSettled: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom<{ readonly counts: ReadonlyMap<ProjectId, number> } | null>;
+}) {
+ return Atom.family((environmentId: EnvironmentId) =>
+ Atom.family((projectId: ProjectId) =>
+ Atom.make(
+ (get) =>
+ (get(sources.olderSettled(environmentId))?.counts.get(projectId) ?? 0) > 0 ||
+ (get(sources.threadRefsByProject(environmentId)).get(projectId)?.length ?? 0) > 0,
+ ).pipe(Atom.withLabel(`mobile:project-has-threads:${environmentId}:${projectId}`)),
+ ),
+ );
+}
+
+const projectHasThreadsAtom = makeProjectHasThreadsAtom({
+ threadRefsByProject: environmentThreadShells.environmentThreadRefsByProjectAtom,
+ olderSettled: olderSettledThreads.olderSettledAtom,
+});
+
+const NO_PROJECT_HAS_THREADS = Atom.make(false).pipe(
+ Atom.withLabel("mobile:project-has-threads:none"),
+);
+
+export function useProjectHasThreads(
+ project: { readonly environmentId: EnvironmentId; readonly id: ProjectId } | null,
+): boolean {
+ return useAtomValue(
+ project === null
+ ? NO_PROJECT_HAS_THREADS
+ : projectHasThreadsAtom(project.environmentId)(project.id),
+ );
+}
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index a3c128b34f6..1c5cc26a084 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -389,6 +389,12 @@ export interface ComposerDraftWorkspaceSelection {
readonly worktreePath: string | null;
readonly startFromOrigin?: boolean;
readonly pullRequestReference?: string;
+ /**
+ * Local mode chosen before refs named the current branch. It is never cleared when refs load:
+ * a local task runs on the checkout, so the draft keeps following it (a later checkout change
+ * included) until the user picks a branch, rather than pinning the first name refs reported.
+ */
+ readonly followsCurrentCheckout?: boolean;
}
export type ComposerDraftSettingsUpdate = Pick<
@@ -402,6 +408,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
worktreePath: Schema.NullOr(Schema.String),
startFromOrigin: Schema.optional(Schema.Boolean),
pullRequestReference: Schema.optional(Schema.String),
+ followsCurrentCheckout: Schema.optional(Schema.Boolean),
});
const ComposerDraftProjectSchema = Schema.Struct({