Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Surface pending tasks in mobile home and draft flow (#3670)

Julius Marminge4ac094fef689
diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index 52b268226..9c26bd7f5 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -5,6 +5,7 @@ import { useMemo, useState } from "react";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
+import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
@@ -13,6 +14,7 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
import { useHomeListOptions } from "./home-list-options";
+import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -26,6 +28,8 @@ export function HomeRouteScreen() {
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
const { archiveThread, confirmDeleteThread } = useThreadListActions();
+ const pendingTasks = usePendingNewTasks();
+ const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Arr.sort(
@@ -116,8 +120,11 @@ export function HomeRouteScreen() {
threadId: thread.id,
});
}}
+ onSelectPendingTask={openPendingTask}
+ onDeletePendingTask={confirmDeletePendingTask}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
+ pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 5418fc959..a671a5c95 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -22,7 +22,9 @@ import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
+import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
+ PendingTaskListRow,
ThreadListGroupHeader,
ThreadListRow,
ThreadListShowMoreRow,
@@ -47,6 +49,7 @@ import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-stat
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
+ readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
@@ -67,6 +70,8 @@ interface HomeScreenProps {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
+ readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
+ readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}
/* ─── Layout constants ───────────────────────────────────────────────── */
@@ -189,6 +194,7 @@ export function HomeScreen(props: HomeScreenProps) {
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
+ pendingTasks: props.pendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -196,6 +202,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
+ props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
@@ -242,10 +249,24 @@ export function HomeScreen(props: HomeScreenProps) {
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
project={item.group.representative}
- threadCount={item.group.threads.length}
+ threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
+ case "pending-task":
+ return (
+ <PendingTaskListRow
+ variant="compact"
+ pendingTask={item.pendingTask}
+ environmentLabel={
+ props.savedConnectionsById[item.pendingTask.message.environmentId]
+ ?.environmentLabel ?? null
+ }
+ isLast={item.isLast}
+ onSelectPendingTask={props.onSelectPendingTask}
+ onDeletePendingTask={props.onDeletePendingTask}
+ />
+ );
case "thread": {
const thread = item.thread;
return (
@@ -285,7 +306,9 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
+ props.onDeletePendingTask,
props.onDeleteThread,
+ props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
@@ -295,7 +318,8 @@ export function HomeScreen(props: HomeScreenProps) {
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
- const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
+ const hasAnyThreads =
+ props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
diff --git a/apps/mobile/src/features/home/homeListItems.test.ts b/apps/mobile/src/features/home/homeListItems.test.ts
index 891a72711..5a10fcb9d 100644
--- a/apps/mobile/src/features/home/homeListItems.test.ts
+++ b/apps/mobile/src/features/home/homeListItems.test.ts
@@ -62,6 +62,7 @@ function makeGroup(key: string, threadCount: number): HomeThreadGroup {
title: key,
representative: project,
projects: [project],
+ pendingTasks: [],
threads: Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
),
diff --git a/apps/mobile/src/features/home/homeListItems.ts b/apps/mobile/src/features/home/homeListItems.ts
index 4a9385142..f15b1252b 100644
--- a/apps/mobile/src/features/home/homeListItems.ts
+++ b/apps/mobile/src/features/home/homeListItems.ts
@@ -1,5 +1,6 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import type { HomeThreadGroup } from "./homeThreadList";
/** Threads shown per project before the "Show more" affordance appears. */
@@ -33,6 +34,13 @@ export interface HomeThreadListItem {
readonly isLast: boolean;
}
+export interface HomePendingTaskListItem {
+ readonly type: "pending-task";
+ readonly key: string;
+ readonly pendingTask: PendingNewTask;
+ readonly isLast: boolean;
+}
+
export interface HomeShowMoreListItem {
readonly type: "show-more";
readonly key: string;
@@ -43,7 +51,11 @@ export interface HomeShowMoreListItem {
readonly canShowLess: boolean;
}
-export type HomeListItem = HomeHeaderListItem | HomeThreadListItem | HomeShowMoreListItem;
+export type HomeListItem =
+ | HomeHeaderListItem
+ | HomePendingTaskListItem
+ | HomeThreadListItem
+ | HomeShowMoreListItem;
export interface HomeListLayout {
readonly items: ReadonlyArray<HomeListItem>;
@@ -82,6 +94,12 @@ export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem
previous.collapsed === item.collapsed &&
previous.isFirst === item.isFirst
);
+ case "pending-task":
+ return (
+ previous.type === "pending-task" &&
+ previous.pendingTask === item.pendingTask &&
+ previous.isLast === item.isLast
+ );
case "thread":
return (
previous.type === "thread" &&
@@ -134,6 +152,19 @@ export function buildHomeListLayout(input: {
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > HOME_INITIAL_VISIBLE_THREADS;
+ // Pending (unsent) tasks lead the group and are never paginated away.
+ for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
+ items.push({
+ type: "pending-task",
+ key: `pending-task:${pendingTask.message.messageId}`,
+ pendingTask,
+ isLast:
+ pendingIndex === group.pendingTasks.length - 1 &&
+ visibleThreads.length === 0 &&
+ !hasShowMoreRow,
+ });
+ }
+
for (const [threadIndex, thread] of visibleThreads.entries()) {
items.push({
type: "thread",
diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts
index 9f09e894c..01605adb8 100644
--- a/apps/mobile/src/features/home/homeThreadList.ts
+++ b/apps/mobile/src/features/home/homeThreadList.ts
@@ -17,6 +17,7 @@ import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
+import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
@@ -25,25 +26,32 @@ export interface HomeThreadGroup {
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
+ readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
+ readonly pendingTasks: PendingNewTask[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
- return group.threads.reduce(
+ const latestThread = group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
+ return group.pendingTasks.reduce((latest, pendingTask) => {
+ const timestamp = Date.parse(pendingTask.message.createdAt);
+ return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
+ }, latestThread);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
+ readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
@@ -68,10 +76,49 @@ export function buildHomeThreadGroups(input: {
if (existing) {
existing.projects.push(project);
} else {
- groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
+ groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
}
}
+ for (const pendingTask of input.pendingTasks ?? []) {
+ if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) {
+ continue;
+ }
+
+ const physicalKey = scopedProjectKey(
+ pendingTask.message.environmentId,
+ pendingTask.creation.projectId,
+ );
+ let groupKey = groupKeyByProjectKey.get(physicalKey);
+ if (!groupKey) {
+ // The project shell is not loaded (environment offline / project gone).
+ // A queued task must stay visible and deletable regardless, so build a
+ // standalone group from the metadata snapshotted at enqueue time.
+ groupKey = `pending-project:${physicalKey}`;
+ groupKeyByProjectKey.set(physicalKey, groupKey);
+ groups.set(groupKey, {
+ key: groupKey,
+ projects: [
+ {
+ environmentId: pendingTask.message.environmentId,
+ id: pendingTask.creation.projectId,
+ title: pendingTask.creation.projectTitle ?? "Unknown project",
+ workspaceRoot:
+ pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: pendingTask.message.createdAt,
+ updatedAt: pendingTask.message.createdAt,
+ },
+ ],
+ pendingTasks: [],
+ threads: [],
+ });
+ }
+ groups.get(groupKey)?.pendingTasks.push(pendingTask);
+ }
+
for (const thread of input.threads) {
if (thread.archivedAt !== null) {
continue;
@@ -93,7 +140,7 @@ export function buildHomeThreadGroups(input: {
for (const group of groups.values()) {
const representative = group.projects[0];
- if (!representative || group.threads.length === 0) {
+ if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
continue;
}
@@ -108,8 +155,13 @@ export function buildHomeThreadGroups(input: {
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
+ const matchingPendingTasks = groupMatches
+ ? group.pendingTasks
+ : group.pendingTasks.filter((pendingTask) =>
+ pendingTask.title.toLocaleLowerCase().includes(query),
+ );
- if (matchingThreads.length === 0) {
+ if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
continue;
}
@@ -118,6 +170,7 @@ export function buildHomeThreadGroups(input: {
title,
representative,
projects: group.projects,
+ pendingTasks: matchingPendingTasks,
threads: sortThreads(matchingThreads, input.threadSortOrder),
});
}
diff --git a/apps/mobile/src/features/home/usePendingTaskListActions.ts b/apps/mobile/src/features/home/usePendingTaskListActions.ts
new file mode 100644
index 000000000..3f0867ba0
--- /dev/null
+++ b/apps/mobile/src/features/home/usePendingTaskListActions.ts
@@ -0,0 +1,57 @@
+import { useNavigation } from "@react-navigation/native";
+import { useCallback } from "react";
+import { Alert } from "react-native";
+
+import { removeThreadOutboxMessage } from "../../state/thread-outbox";
+import type { PendingNewTask } from "../../state/use-pending-new-tasks";
+import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox";
+
+export function usePendingTaskListActions(): {
+ readonly openPendingTask: (pendingTask: PendingNewTask) => void;
+ readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
+} {
+ const navigation = useNavigation();
+
+ const openPendingTask = useCallback(
+ (pendingTask: PendingNewTask) => {
+ navigation.navigate("NewTaskSheet", {
+ screen: "NewTaskDraft",
+ params: {
+ environmentId: String(pendingTask.message.environmentId),
+ projectId: String(pendingTask.creation.projectId),
+ pendingTaskId: String(pendingTask.message.messageId),
+ },
+ });
+ },
+ [navigation],
+ );
+
+ const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {
+ Alert.alert(
+ "Delete pending task?",
+ `“${pendingTask.title}” has not been sent yet and will be removed from the outbox.`,
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Delete",
+ style: "destructive",
+ onPress: () => {
+ // Release the edit lock only after removal succeeds, and only if
+ // it is held for THIS task — clearing it up front (or for another
+ // task) would let the drain deliver a mid-edit payload.
+ void removeThreadOutboxMessage(pendingTask.message)
+ .then(() => releaseEditingQueuedMessage(pendingTask.message.messageId))
+ .catch((error) => {
+ Alert.alert(
+ "Could not delete pending task",
+ error instanceof Error ? error.message : "The pending task could not be removed.",
+ );
+ });
+ },
+ },
+ ],
+ );
+ }, []);
+
+ return { openPendingTask, confirmDeletePendingTask };
+}
diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
index e821a9d1b..a9c508f81 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
@@ -1,4 +1,5 @@
import type { StaticScreenProps } from "@react-navigation/native";
+import { useMemo } from "react";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
@@ -7,11 +8,25 @@ type NewTaskDraftRouteParams = {
readonly environmentId?: string | string[];
readonly projectId?: string | string[];
readonly title?: string | string[];
+ readonly pendingTaskId?: string | string[];
};
export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
const params = route.params ?? {};
+ // Keyed on the params object so a fresh navigation to this (already
+ // mounted) screen produces a new reference, letting the draft screen
+ // re-apply the requested project.
+ const initialProjectRef = useMemo(
+ () => ({
+ environmentId: Array.isArray(params.environmentId)
+ ? params.environmentId[0]
+ : params.environmentId,
+ projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
+ }),
+ [route.params],
+ );
+
return (
<>
<NativeStackScreenOptions
@@ -20,12 +35,10 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
}}
/>
<NewTaskDraftScreen
- initialProjectRef={{
- environmentId: Array.isArray(params.environmentId)
- ? params.environmentId[0]
- : params.environmentId,
- projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
- }}
+ initialProjectRef={initialProjectRef}
+ pendingTaskId={
+ Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
+ }
/>
</>
);
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index de41e1857..3ffbad199 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -23,6 +23,7 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
+import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import {
applyProviderOptionMenuEvent,
@@ -30,10 +31,11 @@ import {
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
-import { scopedProjectKey } from "../../lib/scopedEntities";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
+import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
+import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
@@ -54,6 +56,8 @@ export function NewTaskDraftScreen(props: {
readonly environmentId?: string;
readonly projectId?: string;
};
+ /** Queued outbox message id when editing an existing pending task. */
+ readonly pendingTaskId?: string;
}) {
const projects = useProjects();
const createProjectThread = useCreateProjectThread();
@@ -64,15 +68,67 @@ export function NewTaskDraftScreen(props: {
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
+ const { connectedEnvironments } = useRemoteConnectionStatus();
+ const environmentConnected =
+ selectedProject !== null &&
+ connectedEnvironments.find(
+ (environment) => environment.environmentId === selectedProject.environmentId,
+ )?.connectionState === "connected";
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
+ const appliedInitialProjectKeyRef = useRef<string | null>(null);
+ useEffect(() => {
+ return () => {
+ appliedInitialProjectKeyRef.current = null;
+ };
+ }, []);
+
+ const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
+ const attemptedPendingTaskIdRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
+ return;
+ }
+ // Attempt each pending task once: after it is delivered or deleted the
+ // editing session legitimately ends, and re-running must not navigate.
+ if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
+ return;
+ }
+ attemptedPendingTaskIdRef.current = props.pendingTaskId;
+ if (!beginEditingPendingTask(props.pendingTaskId)) {
+ // The queued task no longer exists (sent or deleted before opening).
+ navigation.dispatch(StackActions.replace("NewTask"));
+ }
+ }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
+
+ useEffect(() => {
+ if (!props.pendingTaskId) return;
+ return () => {
+ // Allow a later navigation for the same pending task to re-hydrate it.
+ attemptedPendingTaskIdRef.current = null;
+ cancelEditingPendingTask();
+ };
+ }, [props.pendingTaskId, cancelEditingPendingTask]);
const borderColor = useThemeColor("--color-border");
const bodyText = useScaledTextRole("body");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
+ // A new navigation to this mounted screen delivers a fresh initialProjectRef
+ // reference — treat it as a new request and let it apply again.
+ const lastInitialProjectRefRef = useRef(props.initialProjectRef);
+
useEffect(() => {
+ // Pending-task editing owns project selection (and must not fall through
+ // to the replace("NewTask") fallback while its hydration is in flight).
+ if (props.pendingTaskId) {
+ return;
+ }
+ if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
+ lastInitialProjectRefRef.current = props.initialProjectRef;
+ appliedInitialProjectKeyRef.current = null;
+ }
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const directProject =
projects.find(
@@ -82,6 +138,13 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
+ // Apply the route's project once. Re-applying on every change would
+ // instantly revert environment/project switches made in the picker.
+ const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
+ if (appliedInitialProjectKeyRef.current === directProjectKey) {
+ return;
+ }
+ appliedInitialProjectKeyRef.current = directProjectKey;
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
@@ -106,8 +169,8 @@ export function NewTaskDraftScreen(props: {
}, [
logicalProjects,
projects,
- props.initialProjectRef?.environmentId,
- props.initialProjectRef?.projectId,
+ props.initialProjectRef,
+ props.pendingTaskId,
navigation,
selectedProject,
setProject,
@@ -274,12 +337,24 @@ export function NewTaskDraftScreen(props: {
subtitle: flow.selectedBranchName ?? "Choose branch",
subactions: branchActions,
},
+ ...(flow.workspaceMode === "worktree"
+ ? [
+ {
+ id: "workspace:start-from-origin",
+ title: "Start from origin",
+ subtitle: "Base the worktree on the latest origin branch",
+ image: "arrow.triangle.pull",
+ state: flow.startFromOrigin ? ("on" as const) : undefined,
+ },
+ ]
+ : []),
];
}, [
flow.availableBranches,
flow.branchesLoading,
flow.selectedBranchName,
flow.selectedProject,
+ flow.startFromOrigin,
flow.workspaceMode,
]);
@@ -344,6 +419,10 @@ export function NewTaskDraftScreen(props: {
);
return;
}
+ if (event === "workspace:start-from-origin") {
+ flow.setStartFromOrigin(!flow.startFromOrigin);
+ return;
+ }
if (event.startsWith("workspace:branch:")) {
const branchName = event.slice("workspace:branch:".length);
const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
@@ -379,17 +458,17 @@ export function NewTaskDraftScreen(props: {
async function handleStart(): Promise<void> {
const selectedProject = flow.selectedProject;
- if (!selectedProject) {
+ const draftKey = flow.draftKey;
+ if (!selectedProject || !draftKey) {
return;
}
- const draft = getComposerDraftSnapshot(
- `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
- );
+ const draft = getComposerDraftSnapshot(draftKey);
const modelSelection = draft.modelSelection ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
+ const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
const interactionMode = draft.interactionMode ?? flow.interactionMode;
const initialMessageText = draft.text.trim();
@@ -403,6 +482,46 @@ export function NewTaskDraftScreen(props: {
return;
}
+ const editingPendingTask = flow.editingPendingTask;
+
+ if (!environmentConnected) {
+ // Offline: park the task in the outbox; the drain sends it when the
+ // environment reconnects. Editing an existing pending task re-queues it
+ // under its original identifiers.
+ const metadata = editingPendingTask
+ ? {
+ threadId: editingPendingTask.threadId,
+ commandId: editingPendingTask.commandId,
+ messageId: editingPendingTask.messageId,
+ createdAt: editingPendingTask.createdAt,
+ }
+ : makeTurnCommandMetadata();
+ const message = flow.buildPendingTaskMessage(metadata);
+ if (!message) {
+ return;
+ }
+ flow.setSubmitting(true);
+ try {
+ await enqueueThreadOutboxMessage(message);
+ } catch (error) {
+ Alert.alert(
+ "Could not queue task",
+ error instanceof Error ? error.message : "The task could not be saved to the outbox.",
+ );
+ return;
+ } finally {
+ flow.setSubmitting(false);
+ }
+ if (editingPendingTask) {
+ flow.finishEditingPendingTask();
+ } else {
+ flow.setPrompt("");
+ flow.clearAttachments();
+ }
+ navigation.getParent()?.goBack();
+ return;
+ }
+
flow.setSubmitting(true);
const result = await createProjectThread({
project: selectedProject,
@@ -410,10 +529,21 @@ export function NewTaskDraftScreen(props: {
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
+ startFromOrigin,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
+ ...(editingPendingTask
+ ? {
+ turnMetadata: {
+ threadId: editingPendingTask.threadId,
+ commandId: editingPendingTask.commandId,
+ messageId: editingPendingTask.messageId,
+ createdAt: editingPendingTask.createdAt,
+ },
+ }
+ : {}),
});
flow.setSubmitting(false);
@@ -428,8 +558,17 @@ export function NewTaskDraftScreen(props: {
return;
}
- flow.setPrompt("");
- flow.clearAttachments();
+ if (editingPendingTask) {
+ try {
+ await removeThreadOutboxMessage(editingPendingTask);
+ } catch (error) {
+ console.warn("[new-task] failed to remove delivered pending task", error);
+ }
+ flow.finishEditingPendingTask();
+ } else {
+ flow.setPrompt("");
+ flow.clearAttachments();
+ }
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(result.value.environmentId),
@@ -538,8 +677,14 @@ export function NewTaskDraftScreen(props: {
</ControlPillMenu>
</ComposerToolbarScroller>
<ComposerToolbarButton
- accessibilityLabel={flow.submitting ? "Starting task" : "Start task"}
- icon="arrow.up"
+ accessibilityLabel={
+ flow.submitting
+ ? "Starting task"
+ : environmentConnected
+ ? "Start task"
+ : "Queue task"
+ }
+ icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
onPress={() => void handleStart()}
variant="primary"
showChevron={false}
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 21a4851e4..1cdb4ce25 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -18,6 +18,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
+import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
@@ -40,6 +41,7 @@ import {
} from "../home/homeListItems";
import { buildHomeThreadGroups } from "../home/homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
+import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
@@ -47,7 +49,12 @@ import { SidebarHeaderActions } from "./sidebar-header-actions";
import { SidebarFilterButton } from "./sidebar-filter-button";
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
import { SidebarNavigationShell } from "./sidebar-navigation-shell";
-import { ThreadListGroupHeader, ThreadListRow, ThreadListShowMoreRow } from "./thread-list-items";
+import {
+ PendingTaskListRow,
+ ThreadListGroupHeader,
+ ThreadListRow,
+ ThreadListShowMoreRow,
+} from "./thread-list-items";
/**
* Shared capsule behind the sidebar header buttons — a native liquid-glass
@@ -162,6 +169,8 @@ function ThreadNavigationSidebarPane(
const headerIsOverContentRef = useRef(false);
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread } = useThreadListActions();
+ const pendingTasks = usePendingNewTasks();
+ const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Object.values(savedConnectionsById)
@@ -188,13 +197,14 @@ function ThreadNavigationSidebarPane(
buildHomeThreadGroups({
projects,
threads,
+ pendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
- [options, projects, props.searchQuery, threads],
+ [options, pendingTasks, projects, props.searchQuery, threads],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -404,10 +414,24 @@ function ThreadNavigationSidebarPane(
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
project={item.group.representative}
- threadCount={item.group.threads.length}
+ threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
+ case "pending-task":
+ return (
+ <PendingTaskListRow
+ variant="sidebar"
+ pendingTask={item.pendingTask}
+ environmentLabel={
+ savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
+ null
+ }
+ isLast={item.isLast}
+ onSelectPendingTask={openPendingTask}
+ onDeletePendingTask={confirmDeletePendingTask}
+ />
+ );
case "thread": {
const thread = item.thread;
return (
@@ -449,10 +473,12 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
+ confirmDeletePendingTask,
confirmDeleteThread,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
+ openPendingTask,
projectCwdByKey,
props.selectedThreadKey,
props.width,
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 9a8dde342..58af4b4fc 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useMemo, useState } from "react";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type {
EnvironmentId,
@@ -8,18 +8,29 @@ import type {
RuntimeMode,
ServerProviderSkill,
} from "@t3tools/contracts";
-import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts";
+import {
+ CommandId,
+ DEFAULT_PROVIDER_INTERACTION_MODE,
+ DEFAULT_RUNTIME_MODE,
+ MessageId,
+ ThreadId,
+} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
+import type { TurnCommandMetadata } from "../../lib/commandMetadata";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
+import { appAtomRegistry } from "../../state/atom-registry";
import {
appendComposerDraftAttachments,
+ clearComposerDraft,
+ getComposerDraftSnapshot,
+ isComposerDraftEmpty,
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
@@ -27,6 +38,17 @@ import {
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
+import {
+ flattenQueuedThreadMessages,
+ threadOutboxManager,
+ updateThreadOutboxMessage,
+ type QueuedThreadMessage,
+} from "../../state/thread-outbox";
+import {
+ holdEditingQueuedMessage,
+ releaseEditingQueuedMessage,
+ useThreadOutboxMessages,
+} from "../../state/use-thread-outbox";
import {
setPendingConnectionError,
useSavedRemoteConnections,
@@ -36,6 +58,23 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
+function pendingTaskDraftKey(messageId: string): string {
+ return `pending-task:${messageId}`;
+}
+
+// The message id owned by the currently active editing session, tracked
+// across provider instances. An in-flight flush from a dismissed session
+// consults it so it never drops the draft or releases the drain lock out from
+// under a newer session editing the same task.
+let activeEditingMessageId: string | null = null;
+
+function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
+ const message = flattenQueuedThreadMessages(
+ appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
+ ).find((candidate) => candidate.messageId === messageId);
+ return message?.creation !== undefined ? message : null;
+}
+
function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
if (!branch.worktreePath) {
return null;
@@ -74,6 +113,9 @@ type NewTaskFlowContextValue = {
readonly workspaceMode: WorkspaceMode;
readonly selectedBranchName: string | null;
readonly selectedWorktreePath: string | null;
+ readonly startFromOrigin: boolean;
+ readonly draftKey: string | null;
+ readonly editingPendingTask: QueuedThreadMessage | null;
readonly prompt: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly submitting: boolean;
@@ -100,6 +142,11 @@ type NewTaskFlowContextValue = {
readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
+ readonly setStartFromOrigin: (value: boolean) => void;
+ readonly beginEditingPendingTask: (messageId: string) => boolean;
+ readonly finishEditingPendingTask: () => void;
+ readonly cancelEditingPendingTask: () => void;
+ readonly buildPendingTaskMessage: (metadata: TurnCommandMetadata) => QueuedThreadMessage | null;
readonly setPrompt: (value: string) => void;
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
@@ -162,6 +209,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
+ const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
+ // Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
+ // on a task whose editing session already ended this render.
+ const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
@@ -169,6 +220,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSubmitting(false);
setBranchQuery("");
setExpandedProvider(null);
+ const editing = editingPendingTaskRef.current;
+ editingPendingTaskRef.current = null;
+ setEditingPendingTask(null);
+ if (editing) {
+ if (activeEditingMessageId === editing.messageId) {
+ activeEditingMessageId = null;
+ }
+ releaseEditingQueuedMessage(editing.messageId);
+ }
}, []);
const environments = useMemo(
@@ -214,24 +274,59 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[projects, selectedEnvironmentId],
);
+ // Stand-in for the edited task's project while its shell is not loaded
+ // (environment offline / still synchronizing), built from the metadata
+ // snapshotted at enqueue time.
+ const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
+ const creation = editingPendingTask?.creation;
+ if (!editingPendingTask || !creation) {
+ return null;
+ }
+ return {
+ environmentId: editingPendingTask.environmentId,
+ id: creation.projectId,
+ title: creation.projectTitle ?? "Unknown project",
+ // Deliberately empty when the snapshot has no cwd — downstream consumers
+ // (branch queries, worktree bootstrap) must skip it, not receive a
+ // fabricated path.
+ workspaceRoot: creation.projectCwd ?? "",
+ repositoryIdentity: null,
+ defaultModelSelection: editingPendingTask.modelSelection ?? null,
+ scripts: [],
+ createdAt: editingPendingTask.createdAt,
+ updatedAt: editingPendingTask.createdAt,
+ };
+ }, [editingPendingTask]);
+
const selectedProject =
projectsForEnvironment.find(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
) ??
- projectsForEnvironment[0] ??
- null;
+ // While editing a queued task whose project shell is absent, keep the task
+ // pinned to its own project — falling through to an arbitrary first
+ // project would silently retarget it (and its reused turn identifiers).
+ (editingPendingProject !== null &&
+ selectedProjectKey ===
+ scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
+ ? editingPendingProject
+ : (projectsForEnvironment[0] ?? null));
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
- const selectedProjectDraftKey = selectedProject
- ? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
- : null;
+ // While a queued pending task is being edited its draft lives under a key
+ // scoped to the queued message, so per-project new-task drafts stay intact.
+ const selectedProjectDraftKey = editingPendingTask
+ ? pendingTaskDraftKey(editingPendingTask.messageId)
+ : selectedProject
+ ? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
+ : null;
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
+ const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -350,7 +445,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const branchTarget = useMemo(
() => ({
environmentId: selectedProject?.environmentId ?? null,
- cwd: selectedProject?.workspaceRoot ?? null,
+ // `|| null` also skips the stand-in project's empty workspaceRoot.
+ cwd: selectedProject?.workspaceRoot || null,
query: null,
}),
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
@@ -399,10 +495,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
+ startFromOrigin,
},
});
},
- [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
+ [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
);
const selectBranch = useCallback(
@@ -415,10 +512,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
+ startFromOrigin,
},
});
},
- [selectedProject, selectedProjectDraftKey, workspaceMode],
+ [selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
+ );
+
+ const setStartFromOrigin = useCallback(
+ (value: boolean) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ workspaceSelection: {
+ mode: workspaceMode,
+ branch: selectedBranchName,
+ worktreePath: selectedWorktreePath,
+ startFromOrigin: value,
+ },
+ });
+ },
+ [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
);
const refreshBranches = branchState.refresh;
@@ -460,6 +575,183 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[selectedProjectDraftKey],
);
+ const beginEditingPendingTask = useCallback((messageId: string): boolean => {
+ const message = findQueuedPendingTask(messageId);
+ if (!message?.creation) {
+ return false;
+ }
+ const draftKey = pendingTaskDraftKey(message.messageId);
+ // Only hydrate a fresh editing draft; reopening mid-edit keeps newer edits.
+ if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
+ setComposerDraftText(draftKey, message.text);
+ replaceComposerDraftAttachments(draftKey, message.attachments);
+ updateComposerDraftSettings(draftKey, {
+ modelSelection: message.modelSelection,
+ runtimeMode: message.runtimeMode,
+ interactionMode: message.interactionMode,
+ workspaceSelection: {
+ mode: message.creation.workspaceMode,
+ branch: message.creation.branch,
+ worktreePath: message.creation.worktreePath,
+ startFromOrigin: message.creation.startFromOrigin ?? false,
+ },
+ });
+ }
+ setSelectedEnvironmentId(message.environmentId);
+ setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
+ activeEditingMessageId = message.messageId;
+ editingPendingTaskRef.current = message;
+ setEditingPendingTask(message);
+ // Hold the outbox drain off this task while it is open in the editor.
+ holdEditingQueuedMessage(message.messageId);
+ return true;
+ }, []);
+
+ const buildPendingTaskMessage = useCallback(
+ (metadata: TurnCommandMetadata): QueuedThreadMessage | null => {
+ if (!selectedProject || !selectedProjectDraftKey) {
+ return null;
+ }
+ const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
+ const text = draft.text.trim();
+ const draftModelSelection = draft.modelSelection ?? selectedModel;
+ if (text.length === 0 || !draftModelSelection) {
+ return null;
+ }
+ const workspaceSelection = draft.workspaceSelection;
+ const mode = workspaceSelection?.mode ?? "local";
+ // When the selection is the stand-in built from the queued snapshot,
+ // persist the original (possibly absent) snapshot values — the
+ // stand-in's placeholder title/workspaceRoot must never be written back
+ // as if they were real project metadata.
+ const usingPendingSnapshot = selectedProject === editingPendingProject;
+ const projectTitle = usingPendingSnapshot
+ ? editingPendingTask?.creation?.projectTitle
+ : selectedProject.title;
+ const projectCwd = usingPendingSnapshot
+ ? editingPendingTask?.creation?.projectCwd
+ : selectedProject.workspaceRoot;
+ return {
+ environmentId: selectedProject.environmentId,
+ threadId: ThreadId.make(metadata.threadId),
+ messageId: MessageId.make(metadata.messageId),
+ commandId: CommandId.make(metadata.commandId),
+ text,
+ attachments: draft.attachments,
+ modelSelection: draftModelSelection,
+ runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE,
+ interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
+ creation: {
+ projectId: selectedProject.id,
+ ...(projectTitle !== undefined ? { projectTitle } : {}),
+ ...(projectCwd !== undefined ? { projectCwd } : {}),
+ workspaceMode: mode,
+ branch: workspaceSelection?.branch ?? null,
+ worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
+ ...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
+ },
+ createdAt: metadata.createdAt,
+ };
+ },
+ [
+ editingPendingProject,
+ editingPendingTask,
+ selectedModel,
+ selectedProject,
+ selectedProjectDraftKey,
+ ],
+ );
+
+ const finishEditingPendingTask = useCallback(() => {
+ const editing = editingPendingTaskRef.current;
+ editingPendingTaskRef.current = null;
+ if (editing) {
+ if (activeEditingMessageId === editing.messageId) {
+ activeEditingMessageId = null;
+ }
+ clearComposerDraft(pendingTaskDraftKey(editing.messageId));
+ releaseEditingQueuedMessage(editing.messageId);
+ }
+ setEditingPendingTask(null);
+ }, []);
+
+ // If the queued task disappears mid-edit (deleted from the list, or
+ // delivered), end the editing session immediately without saving — a later
+ // flush must not resurrect it, and the composer should fall back to the
+ // regular per-project draft.
+ const queuedMessagesByThreadKey = useThreadOutboxMessages();
+ useEffect(() => {
+ const editing = editingPendingTaskRef.current;
+ if (!editing) {
+ return;
+ }
+ const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
+ (candidate) => candidate.messageId === editing.messageId,
+ );
+ if (!stillQueued) {
+ finishEditingPendingTask();
+ }
+ }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
+
+ // Leaving the flow mid-edit (sheet dismissed or draft screen popped) saves
+ // the current edits back into the queued task so nothing typed here is lost.
+ const editingFlushRef = useRef<(() => void) | null>(null);
+ useEffect(() => {
+ editingFlushRef.current = () => {
+ const editing = editingPendingTaskRef.current;
+ if (!editing) {
+ return;
+ }
+ editingPendingTaskRef.current = null;
+ setEditingPendingTask(null);
+ if (activeEditingMessageId === editing.messageId) {
+ activeEditingMessageId = null;
+ }
+
+ const message = buildPendingTaskMessage({
+ threadId: editing.threadId,
+ commandId: editing.commandId,
+ messageId: editing.messageId,
+ createdAt: editing.createdAt,
+ });
+
+ if (!message) {
+ // The edits are currently unsendable (e.g. the prompt was cleared).
+ // Keep both the draft and the drain lock: the stale queued payload
+ // must not auto-send content the user just removed, and reopening the
+ // task resumes from the saved draft.
+ return;
+ }
+
+ // update() rewrites the task only if it is still queued — a concurrent
+ // delete or delivery wins, so the flush cannot resurrect it.
+ void updateThreadOutboxMessage(message)
+ .then(() => {
+ // If this task was reopened (possibly in a fresh provider) while
+ // the save was in flight, that session owns the draft and the lock.
+ if (activeEditingMessageId === editing.messageId) {
+ return;
+ }
+ clearComposerDraft(pendingTaskDraftKey(editing.messageId));
+ releaseEditingQueuedMessage(editing.messageId);
+ })
+ .catch((error) => {
+ // Keep the drain lock and the draft: delivering the stale payload
+ // would silently drop the newer edits. Reopening the task retries.
+ console.warn("[new-task] failed to save edited pending task", error);
+ });
+ };
+ }, [buildPendingTaskMessage]);
+ const cancelEditingPendingTask = useCallback(() => {
+ editingFlushRef.current?.();
+ }, []);
+ useEffect(
+ () => () => {
+ editingFlushRef.current?.();
+ },
+ [],
+ );
+
const value = useMemo<NewTaskFlowContextValue>(
() => ({
logicalProjects,
@@ -469,6 +761,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode,
selectedBranchName,
selectedWorktreePath,
+ startFromOrigin,
+ draftKey: selectedProjectDraftKey,
+ editingPendingTask,
prompt,
attachments,
submitting,
@@ -492,6 +787,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedModelKey,
setWorkspaceMode,
selectBranch,
+ setStartFromOrigin,
+ beginEditingPendingTask,
+ finishEditingPendingTask,
+ cancelEditingPendingTask,
+ buildPendingTaskMessage,
setPrompt,
replaceAttachments,
appendAttachments,
@@ -508,11 +808,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[
attachments,
availableBranches,
+ beginEditingPendingTask,
branchQuery,
branchesLoading,
+ buildPendingTaskMessage,
+ cancelEditingPendingTask,
+ editingPendingTask,
environments,
expandedProvider,
filteredBranches,
+ finishEditingPendingTask,
interactionMode,
loadBranches,
logicalProjects,
@@ -527,6 +832,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedModelKey,
selectedModelOption,
+ selectedProjectDraftKey,
selectedProviderSkills,
setSelectedModelOptions,
selectedProject,
@@ -539,7 +845,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setPrompt,
setRuntimeMode,
setSelectedModelKey,
+ setStartFromOrigin,
setWorkspaceMode,
+ startFromOrigin,
submitting,
workspaceMode,
appendAttachments,
diff --git a/apps/mobile/src/features/threads/thread-list-items.tsx b/apps/mobile/src/features/threads/thread-list-items.tsx
index 3952637da..e8ba7571d 100644
--- a/apps/mobile/src/features/threads/thread-list-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-items.tsx
@@ -14,6 +14,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
+import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
@@ -180,6 +181,173 @@ export const ThreadListShowMoreRow = memo(function ThreadListShowMoreRow(props:
);
});
+/* ─── Pending task row ───────────────────────────────────────────────── */
+
+const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
+ { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
+];
+
+/**
+ * A queued new task waiting in the outbox for its environment to reconnect.
+ * Tapping reopens the new-task composer with everything prefilled; the row
+ * disappears once the task is delivered and the real thread arrives.
+ */
+export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
+ readonly variant: ThreadListVariant;
+ readonly pendingTask: PendingNewTask;
+ readonly environmentLabel: string | null;
+ readonly isLast: boolean;
+ readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
+ readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
+}) {
+ const compact = props.variant === "compact";
+ const separatorColor = useThemeColor("--color-separator");
+ const iconSubtleColor = useThemeColor("--color-icon-subtle");
+ const foregroundColor = useThemeColor("--color-foreground");
+ const mutedColor = useThemeColor("--color-foreground-muted");
+ const pressedBackgroundColor = useThemeColor("--color-subtle");
+
+ const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
+ const timestamp = relativeTime(pendingTask.message.createdAt);
+ const subtitleParts = [props.environmentLabel, pendingTask.creation.branch].filter(
+ (part): part is string => Boolean(part),
+ );
+
+ const handleMenuAction = useCallback(
+ ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
+ if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
+ },
+ [onDeletePendingTask, pendingTask],
+ );
+
+ const statusPill = (
+ <View
+ className="bg-zinc-500/12 dark:bg-zinc-500/16"
+ style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
+ >
+ <Text className="text-3xs font-t3-bold text-zinc-600 dark:text-zinc-300">Pending</Text>
+ </View>
+ );
+
+ const subtitleRow =
+ subtitleParts.length > 0 ? (
+ <View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
+ <SymbolView
+ name="tray.and.arrow.up"
+ size={10}
+ tintColor={compact ? iconSubtleColor : mutedColor}
+ type="monochrome"
+ />
+ <Text
+ className={compact ? "text-sm text-foreground-muted" : "text-xs"}
+ numberOfLines={1}
+ style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: mutedColor }}
+ >
+ {subtitleParts.join(" · ")}
+ </Text>
+ </View>
+ ) : null;
+
+ const rowContent = compact ? (
+ <Pressable
+ accessibilityHint="Opens the queued task for editing"
+ accessibilityLabel={pendingTask.title}
+ accessibilityRole="button"
+ className="bg-screen"
+ onPress={() => onSelectPendingTask(pendingTask)}
+ style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
+ >
+ <View
+ style={{
+ paddingLeft: THREAD_LIST_COMPACT_INSET,
+ paddingRight: 18,
+ paddingTop: 10,
+ }}
+ >
+ <View
+ style={{
+ gap: 3,
+ borderBottomWidth: props.isLast ? 0 : 1,
+ borderBottomColor: separatorColor,
+ paddingBottom: 10,
+ }}
+ >
+ <View className="flex-row items-center justify-between gap-2">
+ <Text className="flex-1 text-lg font-t3-bold text-foreground" numberOfLines={1}>
+ {pendingTask.title}
+ </Text>
+ <View className="flex-row items-center gap-2">
+ {statusPill}
+ <Text
+ className="text-base text-foreground-tertiary"
+ style={{ fontVariant: ["tabular-nums"] }}
+ >
+ {timestamp}
+ </Text>
+ <SymbolView
+ name="chevron.right"
+ size={13}
+ tintColor={iconSubtleColor}
+ type="monochrome"
+ />
+ </View>
+ </View>
+ {subtitleRow}
+ </View>
+ </View>
+ </Pressable>
+ ) : (
+ <Pressable
+ accessibilityHint="Opens the queued task for editing"
+ accessibilityLabel={pendingTask.title}
+ accessibilityRole="button"
+ onPress={() => onSelectPendingTask(pendingTask)}
+ style={({ pressed }) => ({
+ backgroundColor: pressed ? pressedBackgroundColor : "transparent",
+ borderRadius: SIDEBAR_ROW_RADIUS,
+ cursor: "pointer",
+ minHeight: 64,
+ justifyContent: "center",
+ paddingHorizontal: 12,
+ paddingVertical: 10,
+ })}
+ >
+ <View style={{ gap: 3 }}>
+ <View className="flex-row items-center justify-between gap-2">
+ <Text
+ className="flex-1 text-base font-t3-medium"
+ numberOfLines={1}
+ style={{ color: foregroundColor }}
+ >
+ {pendingTask.title}
+ </Text>
+ <View className="flex-row items-center gap-2">
+ {statusPill}
+ <Text
+ className="text-xs"
+ numberOfLines={1}
+ style={{ color: mutedColor, fontVariant: ["tabular-nums"] }}
+ >
+ {timestamp}
+ </Text>
+ </View>
+ </View>
+ {subtitleRow}
+ </View>
+ </Pressable>
+ );
+
+ return (
+ <ControlPillMenu
+ actions={PENDING_TASK_MENU_ACTIONS}
+ onPressAction={handleMenuAction}
+ shouldOpenOnLongPress
+ >
+ {rowContent}
+ </ControlPillMenu>
+ );
+});
+
/* ─── Thread row ─────────────────────────────────────────────────────── */
const THREAD_ROW_MENU_ACTIONS: MenuAction[] = [
diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts
index 9531567f4..9d03dde59 100644
--- a/apps/mobile/src/features/threads/use-project-actions.ts
+++ b/apps/mobile/src/features/threads/use-project-actions.ts
@@ -4,8 +4,6 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import {
- CommandId,
- MessageId,
ThreadId,
type ModelSelection,
type ProviderInteractionMode,
@@ -17,22 +15,13 @@ import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
-import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
-import { uuidv4 } from "../../lib/uuid";
+import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
+import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
+import { randomHex } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
-function deriveThreadTitleFromPrompt(value: string): string {
- const trimmed = value.trim();
- if (trimmed.length === 0) {
- return "New thread";
- }
-
- const compact = trimmed.replace(/\s+/g, " ");
- return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
-}
-
export function useCreateProjectThread() {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
@@ -43,15 +32,17 @@ export function useCreateProjectThread() {
readonly envMode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
+ readonly startFromOrigin?: boolean;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly initialMessageText: string;
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
+ /** Reuse identifiers from a queued pending task instead of minting new ones. */
+ readonly turnMetadata?: TurnCommandMetadata;
}) => {
- const metadata = makeTurnCommandMetadata();
+ const metadata = input.turnMetadata ?? makeTurnCommandMetadata();
const threadId = ThreadId.make(metadata.threadId);
const initialMessageText = input.initialMessageText.trim();
- const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
const validationError = validateProjectThreadCreation({
environmentId: input.project.environmentId,
@@ -65,46 +56,26 @@ export function useCreateProjectThread() {
return AsyncResult.failure(Cause.fail(validationError));
}
- const isWorktree = input.envMode === "worktree";
const result = await startTurn({
environmentId: input.project.environmentId,
- input: {
- commandId: CommandId.make(metadata.commandId),
- threadId,
- message: {
- messageId: MessageId.make(metadata.messageId),
- role: "user",
- text: initialMessageText,
- attachments: input.initialAttachments,
- },
+ input: buildProjectThreadStartTurnInput({
+ projectId: input.project.id,
+ projectCwd: input.project.workspaceRoot,
+ threadId: metadata.threadId,
+ commandId: metadata.commandId,
+ messageId: metadata.messageId,
+ createdAt: metadata.createdAt,
+ text: initialMessageText,
+ attachments: input.initialAttachments,
modelSelection: input.modelSelection,
- titleSeed: nextTitle,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
- bootstrap: {
- createThread: {
- projectId: input.project.id,
- title: nextTitle,
- modelSelection: input.modelSelection,
- runtimeMode: input.runtimeMode,
- interactionMode: input.interactionMode,
- branch: input.branch,
- worktreePath: isWorktree ? null : input.worktreePath,
- createdAt: metadata.createdAt,
- },
- ...(isWorktree
- ? {
- prepareWorktree: {
- projectCwd: input.project.workspaceRoot,
- baseBranch: input.branch!,
- branch: buildTemporaryWorktreeBranchName(uuidv4),
- },
- runSetupScript: true,
- }
- : {}),
- },
- createdAt: metadata.createdAt,
- },
+ workspaceMode: input.envMode,
+ branch: input.branch,
+ worktreePath: input.worktreePath,
+ startFromOrigin: input.startFromOrigin ?? false,
+ worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
+ }),
});
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts
new file mode 100644
index 000000000..e3c2f744a
--- /dev/null
+++ b/apps/mobile/src/lib/projectThreadStartTurn.ts
@@ -0,0 +1,89 @@
+import {
+ CommandId,
+ MessageId,
+ ThreadId,
+ type ModelSelection,
+ type ProjectId,
+ type ProviderInteractionMode,
+ type RuntimeMode,
+} from "@t3tools/contracts";
+
+import type { DraftComposerImageAttachment } from "./composerImages";
+
+export function deriveThreadTitleFromPrompt(value: string): string {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ return "New thread";
+ }
+
+ const compact = trimmed.replace(/\s+/g, " ");
+ return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
+}
+
+export interface ProjectThreadStartTurnSpec {
+ readonly projectId: ProjectId;
+ readonly projectCwd: string;
+ readonly threadId: string;
+ readonly commandId: string;
+ readonly messageId: string;
+ readonly createdAt: string;
+ readonly text: string;
+ readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
+ readonly modelSelection: ModelSelection;
+ readonly runtimeMode: RuntimeMode;
+ readonly interactionMode: ProviderInteractionMode;
+ readonly workspaceMode: "local" | "worktree";
+ readonly branch: string | null;
+ readonly worktreePath: string | null;
+ readonly startFromOrigin: boolean;
+ /** Generated temp branch for worktree mode; unused for local mode. */
+ readonly worktreeBranchName: string;
+}
+
+/**
+ * Single source of the `thread.turn.start` bootstrap payload used to create a
+ * thread from a project draft — shared by the immediate send path and the
+ * offline outbox drain so both deliver identical commands.
+ */
+export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {
+ const title = deriveThreadTitleFromPrompt(spec.text);
+ const isWorktree = spec.workspaceMode === "worktree";
+ return {
+ commandId: CommandId.make(spec.commandId),
+ threadId: ThreadId.make(spec.threadId),
+ message: {
+ messageId: MessageId.make(spec.messageId),
+ role: "user" as const,
+ text: spec.text,
+ attachments: spec.attachments,
+ },
+ modelSelection: spec.modelSelection,
+ titleSeed: title,
+ runtimeMode: spec.runtimeMode,
+ interactionMode: spec.interactionMode,
+ bootstrap: {
+ createThread: {
+ projectId: spec.projectId,
+ title,
+ modelSelection: spec.modelSelection,
+ runtimeMode: spec.runtimeMode,
+ interactionMode: spec.interactionMode,
+ branch: spec.branch,
+ worktreePath: isWorktree ? null : spec.worktreePath,
+ createdAt: spec.createdAt,
+ },
+ ...(isWorktree
+ ? {
+ prepareWorktree: {
+ projectCwd: spec.projectCwd,
+ baseBranch: spec.branch!,
+ branch: spec.worktreeBranchName,
+ ...(spec.startFromOrigin ? { startFromOrigin: true } : {}),
+ },
+ runSetupScript: true,
+ }
+ : {}),
+ },
+ createdAt: spec.createdAt,
+ };
+}
diff --git a/apps/mobile/src/lib/uuid.ts b/apps/mobile/src/lib/uuid.ts
index ee757c4a0..02fd1344e 100644
--- a/apps/mobile/src/lib/uuid.ts
+++ b/apps/mobile/src/lib/uuid.ts
@@ -1,3 +1,9 @@
import * as Crypto from "expo-crypto";
export const uuidv4 = () => Crypto.randomUUID();
+
+/** Random lowercase hex string of `byteLength` bytes (2 chars per byte). */
+export const randomHex = (byteLength: number): string =>
+ Array.from(Crypto.getRandomBytes(byteLength), (byte) => byte.toString(16).padStart(2, "0")).join(
+ "",
+ );
diff --git a/apps/mobile/src/state/thread-outbox-manager.ts b/apps/mobile/src/state/thread-outbox-manager.ts
index 7762e6cdf..fc3e5069d 100644
--- a/apps/mobile/src/state/thread-outbox-manager.ts
+++ b/apps/mobile/src/state/thread-outbox-manager.ts
@@ -15,6 +15,7 @@ export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutb
operation: Schema.Literals([
"load",
"enqueue",
+ "update",
"remove",
"clear-environment-load",
"clear-environment-remove",
@@ -103,6 +104,35 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
setMessages([...currentMessages(), message]);
});
+ // Rewrites an already-queued message. A no-op when the message has been
+ // removed in the meantime (e.g. deleted or delivered), so a trailing editor
+ // flush can never resurrect it. Returns whether the message was updated.
+ const update = (message: QueuedThreadMessage): Promise<boolean> =>
+ serialize(async () => {
+ const exists = currentMessages().some(
+ (candidate) => candidate.messageId === message.messageId,
+ );
+ if (!exists) {
+ return false;
+ }
+ try {
+ await options.storage.write(message);
+ } catch (cause) {
+ throw new ThreadOutboxManagerError({
+ operation: "update",
+ environmentId: message.environmentId,
+ threadId: message.threadId,
+ messageId: message.messageId,
+ cause,
+ });
+ }
+ setMessages([
+ ...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
+ message,
+ ]);
+ return true;
+ });
+
const remove = (message: QueuedThreadMessage): Promise<void> =>
serialize(async () => {
try {
@@ -171,6 +201,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
serialize,
load,
enqueue,
+ update,
remove,
clearEnvironment,
};
diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts
index ed0c06ba3..3ba61be38 100644
--- a/apps/mobile/src/state/thread-outbox-model.ts
+++ b/apps/mobile/src/state/thread-outbox-model.ts
@@ -6,10 +6,12 @@ import {
IsoDateTime,
MessageId,
ModelSelection,
+ ProjectId,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
type ModelSelection as ModelSelectionType,
+ type ProjectId as ProjectIdType,
type ProviderInteractionMode as ProviderInteractionModeType,
type RuntimeMode as RuntimeModeType,
} from "@t3tools/contracts";
@@ -19,11 +21,23 @@ import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
-const THREAD_OUTBOX_SCHEMA_VERSION = 2;
+const THREAD_OUTBOX_SCHEMA_VERSION = 3;
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
+const QueuedThreadCreationSchema = Schema.Struct({
+ projectId: ProjectId,
+ // Snapshot of the project's display metadata so a pending task stays
+ // presentable in the thread list even when the project shell is not loaded.
+ projectTitle: Schema.optional(Schema.String),
+ projectCwd: Schema.optional(Schema.String),
+ workspaceMode: Schema.Literals(["local", "worktree"]),
+ branch: Schema.NullOr(Schema.String),
+ worktreePath: Schema.NullOr(Schema.String),
+ startFromOrigin: Schema.optional(Schema.Boolean),
+});
+
export const QueuedThreadMessageSchema = Schema.Struct({
- schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
+ schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION]),
environmentId: EnvironmentId,
threadId: ThreadId,
messageId: MessageId,
@@ -33,12 +47,25 @@ export const QueuedThreadMessageSchema = Schema.Struct({
modelSelection: Schema.optional(ModelSelection),
runtimeMode: Schema.optional(RuntimeMode),
interactionMode: Schema.optional(ProviderInteractionMode),
+ // Present when the queued item creates a brand-new thread (pending task)
+ // instead of appending a turn to an existing one.
+ creation: Schema.optional(QueuedThreadCreationSchema),
createdAt: IsoDateTime,
});
const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
+export interface QueuedThreadCreation {
+ readonly projectId: ProjectIdType;
+ readonly projectTitle?: string;
+ readonly projectCwd?: string;
+ readonly workspaceMode: "local" | "worktree";
+ readonly branch: string | null;
+ readonly worktreePath: string | null;
+ readonly startFromOrigin?: boolean;
+}
+
export interface QueuedThreadMessage {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -49,6 +76,7 @@ export interface QueuedThreadMessage {
readonly modelSelection?: ModelSelectionType;
readonly runtimeMode?: RuntimeModeType;
readonly interactionMode?: ProviderInteractionModeType;
+ readonly creation?: QueuedThreadCreation;
readonly createdAt: string;
}
@@ -121,17 +149,43 @@ export function threadOutboxRetryDelayMs(attempt: number): number {
export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
export function resolveThreadOutboxDeliveryAction(input: {
+ readonly isCreation: boolean;
readonly threadExists: boolean;
readonly shellStatus: EnvironmentShellStatus;
readonly environmentConnected: boolean;
readonly threadBusy: boolean;
}): ThreadOutboxDeliveryAction {
+ if (input.isCreation) {
+ // A pending task creates its thread on delivery. If the thread already
+ // exists the creation command went through and only cleanup remains.
+ if (input.threadExists) {
+ return "remove";
+ }
+ // Wait for the shell to be live before sending: until the thread list has
+ // synchronized, a previously delivered creation whose cleanup failed would
+ // look missing and get re-issued, duplicating the thread.
+ return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
+ }
if (!input.threadExists) {
return input.shellStatus === "live" ? "remove" : "wait";
}
return input.environmentConnected && !input.threadBusy ? "send" : "wait";
}
+/**
+ * A queued creation can only be dispatched once its payload would pass server
+ * validation; incomplete payloads stay pending until the user edits them.
+ */
+export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
+ if (!message.creation) {
+ return false;
+ }
+ if (message.text.trim().length === 0 || message.modelSelection === undefined) {
+ return false;
+ }
+ return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
+}
+
function errorMessage(error: unknown): string | null {
if (error instanceof Error) {
return error.message;
diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.ts
index 68d06d2e4..2ccaa471c 100644
--- a/apps/mobile/src/state/thread-outbox.test.ts
+++ b/apps/mobile/src/state/thread-outbox.test.ts
@@ -3,6 +3,7 @@ import {
CommandId,
EnvironmentId,
MessageId,
+ ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
@@ -12,6 +13,7 @@ import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
+ isQueuedThreadCreationSendable,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
@@ -292,9 +294,43 @@ describe("thread outbox", () => {
registry.dispose();
});
+ it("updates a queued message in place but never resurrects a removed one", async () => {
+ const registry = AtomRegistry.make();
+ const stored = new Map<MessageId, QueuedThreadMessage>();
+ const storage: ThreadOutboxStorage = {
+ load: async () => [...stored.values()],
+ write: async (message) => {
+ stored.set(message.messageId, message);
+ },
+ remove: async (message) => {
+ stored.delete(message.messageId);
+ },
+ };
+ const manager = createThreadOutboxManager({ registry, storage });
+ const message = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+
+ await manager.enqueue(message);
+ const edited = { ...message, text: "edited" };
+ await expect(manager.update(edited)).resolves.toBe(true);
+ expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
+ "environment-1:thread-1": [edited],
+ });
+ expect(stored.get(message.messageId)).toEqual(edited);
+
+ await manager.remove(edited);
+ await expect(manager.update({ ...message, text: "stale flush" })).resolves.toBe(false);
+ expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
+ expect(stored.size).toBe(0);
+ registry.dispose();
+ });
+
it("only removes a missing-thread message after shell synchronization is live", () => {
expect(
resolveThreadOutboxDeliveryAction({
+ isCreation: false,
threadExists: false,
shellStatus: "synchronizing",
environmentConnected: true,
@@ -303,6 +339,7 @@ describe("thread outbox", () => {
).toBe("wait");
expect(
resolveThreadOutboxDeliveryAction({
+ isCreation: false,
threadExists: false,
shellStatus: "live",
environmentConnected: true,
@@ -311,6 +348,7 @@ describe("thread outbox", () => {
).toBe("remove");
expect(
resolveThreadOutboxDeliveryAction({
+ isCreation: false,
threadExists: true,
shellStatus: "live",
environmentConnected: true,
@@ -319,6 +357,89 @@ describe("thread outbox", () => {
).toBe("send");
});
+ it("sends queued creations once connected and live, removing already-created ones", () => {
+ expect(
+ resolveThreadOutboxDeliveryAction({
+ isCreation: true,
+ threadExists: false,
+ shellStatus: "cached",
+ environmentConnected: false,
+ threadBusy: false,
+ }),
+ ).toBe("wait");
+ // Connected but not yet synchronized: a previously delivered creation may
+ // simply not be visible yet — sending now could duplicate the thread.
+ expect(
+ resolveThreadOutboxDeliveryAction({
+ isCreation: true,
+ threadExists: false,
+ shellStatus: "synchronizing",
+ environmentConnected: true,
+ threadBusy: false,
+ }),
+ ).toBe("wait");
+ expect(
+ resolveThreadOutboxDeliveryAction({
+ isCreation: true,
+ threadExists: false,
+ shellStatus: "live",
+ environmentConnected: true,
+ threadBusy: false,
+ }),
+ ).toBe("send");
+ expect(
+ resolveThreadOutboxDeliveryAction({
+ isCreation: true,
+ threadExists: true,
+ shellStatus: "live",
+ environmentConnected: true,
+ threadBusy: true,
+ }),
+ ).toBe("remove");
+ });
+
+ it("round-trips queued creations and gates incomplete ones from sending", () => {
+ const base = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const creationMessage = {
+ ...base,
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.4",
+ },
+ creation: {
+ projectId: ProjectId.make("project-1"),
+ workspaceMode: "worktree",
+ branch: "main",
+ worktreePath: null,
+ startFromOrigin: true,
+ },
+ } satisfies QueuedThreadMessage;
+
+ expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(creationMessage))).toEqual(
+ creationMessage,
+ );
+ expect(isQueuedThreadCreationSendable(creationMessage)).toBe(true);
+ expect(
+ isQueuedThreadCreationSendable({
+ ...creationMessage,
+ creation: { ...creationMessage.creation, branch: null },
+ }),
+ ).toBe(false);
+ expect(
+ isQueuedThreadCreationSendable({
+ ...creationMessage,
+ creation: { ...creationMessage.creation, branch: "" },
+ }),
+ ).toBe(false);
+ expect(isQueuedThreadCreationSendable({ ...creationMessage, modelSelection: undefined })).toBe(
+ false,
+ );
+ expect(isQueuedThreadCreationSendable(base)).toBe(false);
+ });
+
it("retries transport failures but drops deterministic command failures", () => {
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
expect(
diff --git a/apps/mobile/src/state/thread-outbox.ts b/apps/mobile/src/state/thread-outbox.ts
index d5eb383a0..a089c4973 100644
--- a/apps/mobile/src/state/thread-outbox.ts
+++ b/apps/mobile/src/state/thread-outbox.ts
@@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis
return threadOutboxManager.enqueue(message);
}
+/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
+export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
+ return threadOutboxManager.update(message);
+}
+
export function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {
return threadOutboxManager.remove(message);
}
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 9e2c15661..aa2e2dd5c 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -48,6 +48,7 @@ export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
+ readonly startFromOrigin?: boolean;
}
export type ComposerDraftSettingsUpdate = Pick<
@@ -59,6 +60,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
mode: Schema.Literals(["local", "worktree"]),
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
+ startFromOrigin: Schema.optional(Schema.Boolean),
});
const ComposerDraftSchema = Schema.Struct({
@@ -107,6 +109,10 @@ export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
}
+export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
+ return isEmptyDraft(draft);
+}
+
function isEmptyDraft(draft: ComposerDraft): boolean {
return (
draft.text.length === 0 &&
diff --git a/apps/mobile/src/state/use-pending-new-tasks.ts b/apps/mobile/src/state/use-pending-new-tasks.ts
new file mode 100644
index 000000000..ccfe1527b
--- /dev/null
+++ b/apps/mobile/src/state/use-pending-new-tasks.ts
@@ -0,0 +1,35 @@
+import { useMemo } from "react";
+
+import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
+import {
+ flattenQueuedThreadMessages,
+ type QueuedThreadCreation,
+ type QueuedThreadMessage,
+} from "./thread-outbox-model";
+import { useThreadOutboxMessages } from "./use-thread-outbox";
+
+/** A queued new-task creation, shaped for thread-list presentation. */
+export interface PendingNewTask {
+ readonly message: QueuedThreadMessage;
+ readonly creation: QueuedThreadCreation;
+ readonly title: string;
+}
+
+export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
+ const queuedMessagesByThreadKey = useThreadOutboxMessages();
+ return useMemo(() => {
+ const tasks: PendingNewTask[] = [];
+ for (const message of flattenQueuedThreadMessages(queuedMessagesByThreadKey)) {
+ if (!message.creation) {
+ continue;
+ }
+ tasks.push({
+ message,
+ creation: message.creation,
+ title: deriveThreadTitleFromPrompt(message.text),
+ });
+ }
+ tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt));
+ return tasks;
+ }, [queuedMessagesByThreadKey]);
+}
diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts
index e912d6366..f4de9c394 100644
--- a/apps/mobile/src/state/use-thread-outbox-drain.ts
+++ b/apps/mobile/src/state/use-thread-outbox-drain.ts
@@ -1,27 +1,44 @@
import { useAtomValue } from "@effect/atom-react";
-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import type {
+ EnvironmentProject,
+ EnvironmentThreadShell,
+} from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
-import { CommandId, type MessageId } from "@t3tools/contracts";
+import {
+ CommandId,
+ DEFAULT_PROVIDER_INTERACTION_MODE,
+ DEFAULT_RUNTIME_MODE,
+ type MessageId,
+} from "@t3tools/contracts";
+import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
import { scopedThreadKey } from "../lib/scopedEntities";
+import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
+import { randomHex } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
-import { useThreadShells } from "./entities";
+import { useProjects, useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
+ isQueuedThreadCreationSendable,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
threadOutboxRetryDelayMs,
+ type QueuedThreadCreation,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
-import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox";
+import {
+ editingQueuedMessageIdsAtom,
+ useThreadOutboxMessages,
+ useThreadOutboxShellStatuses,
+} from "./use-thread-outbox";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
@@ -48,6 +65,17 @@ function findThread(
);
}
+function findCreationProject(
+ projects: ReadonlyArray<EnvironmentProject>,
+ message: QueuedThreadMessage,
+): EnvironmentProject | undefined {
+ return projects.find(
+ (candidate) =>
+ candidate.environmentId === message.environmentId &&
+ candidate.id === message.creation?.projectId,
+ );
+}
+
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
return CommandId.make(`${message.commandId}:${setting}`);
}
@@ -64,9 +92,11 @@ export function useThreadOutboxDrain(): void {
reportFailure: false,
});
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
+ const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const shellStatuses = useThreadOutboxShellStatuses();
const threads = useThreadShells();
+ const projects = useProjects();
const { connectedEnvironments } = useRemoteConnectionStatus();
const [retryTick, setRetryTick] = useState(0);
const retryAttemptRef = useRef(new Map<MessageId, number>());
@@ -83,52 +113,57 @@ export function useThreadOutboxDrain(): void {
};
}, []);
- const sendQueuedMessage = useCallback(
- async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
- const settings = resolveQueuedThreadSettings(queuedMessage, thread);
- const reportFailure = (
- commandResult: AtomCommandResult<unknown, unknown>,
- stage: ThreadOutboxCommandStage,
- ): boolean => {
- if (!AsyncResult.isFailure(commandResult)) {
- return false;
- }
- const action = resolveThreadOutboxFailureAction({
- stage,
- error: Cause.squash(commandResult.cause),
- interrupted: Cause.hasInterruptsOnly(commandResult.cause),
- });
- const retry = action === "retry";
- console.warn("[thread-outbox] queued message delivery failed", {
+ const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => {
+ const reportFailure = (
+ commandResult: AtomCommandResult<unknown, unknown>,
+ stage: ThreadOutboxCommandStage,
+ ): boolean => {
+ if (!AsyncResult.isFailure(commandResult)) {
+ return false;
+ }
+ const action = resolveThreadOutboxFailureAction({
+ stage,
+ error: Cause.squash(commandResult.cause),
+ interrupted: Cause.hasInterruptsOnly(commandResult.cause),
+ });
+ const retry = action === "retry";
+ console.warn("[thread-outbox] queued message delivery failed", {
+ environmentId: queuedMessage.environmentId,
+ threadId: queuedMessage.threadId,
+ messageId: queuedMessage.messageId,
+ stage,
+ cause: commandResult.cause,
+ retry,
+ });
+ return retry;
+ };
+ const completeDelivery = async (
+ deliveryResult: AtomCommandResult<unknown, unknown>,
+ ): Promise<boolean> => {
+ if (reportFailure(deliveryResult, "start-turn")) {
+ return false;
+ }
+
+ try {
+ await removeThreadOutboxMessage(queuedMessage);
+ return true;
+ } catch (error) {
+ console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
- stage,
- cause: commandResult.cause,
- retry,
+ error,
});
- return retry;
- };
- const completeDelivery = async (
- deliveryResult: AtomCommandResult<unknown, unknown>,
- ): Promise<boolean> => {
- if (reportFailure(deliveryResult, "start-turn")) {
- return false;
- }
+ return false;
+ }
+ };
+ return { reportFailure, completeDelivery };
+ }, []);
- try {
- await removeThreadOutboxMessage(queuedMessage);
- return true;
- } catch (error) {
- console.warn("[thread-outbox] failed to remove delivered queued message", {
- environmentId: queuedMessage.environmentId,
- threadId: queuedMessage.threadId,
- messageId: queuedMessage.messageId,
- error,
- });
- return false;
- }
- };
+ const sendQueuedMessage = useCallback(
+ async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
+ const settings = resolveQueuedThreadSettings(queuedMessage, thread);
+ const { reportFailure, completeDelivery } = makeDeliveryHelpers(queuedMessage);
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
const updateResult = await updateThreadMetadata({
@@ -196,7 +231,50 @@ export function useThreadOutboxDrain(): void {
});
return completeDelivery(deliveryResult);
},
- [setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
+ [
+ makeDeliveryHelpers,
+ setThreadInteractionMode,
+ setThreadRuntimeMode,
+ startTurn,
+ updateThreadMetadata,
+ ],
+ );
+
+ const sendQueuedCreation = useCallback(
+ async (
+ queuedMessage: QueuedThreadMessage,
+ creation: QueuedThreadCreation,
+ projectCwd: string,
+ ) => {
+ const modelSelection = queuedMessage.modelSelection;
+ if (modelSelection === undefined) {
+ return false;
+ }
+ const { completeDelivery } = makeDeliveryHelpers(queuedMessage);
+ const deliveryResult = await startTurn({
+ environmentId: queuedMessage.environmentId,
+ input: buildProjectThreadStartTurnInput({
+ projectId: creation.projectId,
+ projectCwd,
+ threadId: queuedMessage.threadId,
+ commandId: queuedMessage.commandId,
+ messageId: queuedMessage.messageId,
+ createdAt: queuedMessage.createdAt,
+ text: queuedMessage.text.trim(),
+ attachments: queuedMessage.attachments,
+ modelSelection,
+ runtimeMode: queuedMessage.runtimeMode ?? DEFAULT_RUNTIME_MODE,
+ interactionMode: queuedMessage.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
+ workspaceMode: creation.workspaceMode,
+ branch: creation.branch,
+ worktreePath: creation.worktreePath,
+ startFromOrigin: creation.startFromOrigin ?? false,
+ worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
+ }),
+ });
+ return completeDelivery(deliveryResult);
+ },
+ [makeDeliveryHelpers, startTurn],
);
useEffect(() => {
@@ -209,6 +287,9 @@ export function useThreadOutboxDrain(): void {
if (!nextQueuedMessage) {
continue;
}
+ if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
+ continue;
+ }
if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
continue;
}
@@ -218,37 +299,65 @@ export function useThreadOutboxDrain(): void {
continue;
}
+ const creation = nextQueuedMessage.creation;
const environment = connectedEnvironments.find(
(candidate) => candidate.environmentId === nextQueuedMessage.environmentId,
);
+ const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty";
const deliveryAction = resolveThreadOutboxDeliveryAction({
+ isCreation: creation !== undefined,
threadExists: thread !== undefined,
- shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty",
+ shellStatus,
environmentConnected: environment?.connectionState === "connected",
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
});
if (deliveryAction === "wait") {
continue;
}
+ // The live project shell is preferred for the workspace path, with the
+ // snapshot taken at enqueue time as the fallback so a task never dies
+ // just because its project shell is not loaded.
+ const creationProjectCwd =
+ creation !== undefined
+ ? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ??
+ creation.projectCwd ??
+ null)
+ : null;
+ // An incomplete pending task (e.g. worktree mode without a branch) stays
+ // queued until the user finishes it in the editor.
+ if (deliveryAction === "send" && creation !== undefined) {
+ if (!isQueuedThreadCreationSendable(nextQueuedMessage)) {
+ continue;
+ }
+ if (creationProjectCwd === null && shellStatus !== "live") {
+ continue;
+ }
+ }
beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
+ const removeQueuedMessage = (warning: string) =>
+ removeThreadOutboxMessage(nextQueuedMessage).then(
+ () => true,
+ (error) => {
+ console.warn(warning, {
+ environmentId: nextQueuedMessage.environmentId,
+ threadId: nextQueuedMessage.threadId,
+ messageId: nextQueuedMessage.messageId,
+ error,
+ });
+ return false;
+ },
+ );
const delivery =
deliveryAction === "remove"
- ? removeThreadOutboxMessage(nextQueuedMessage).then(
- () => true,
- (error) => {
- console.warn("[thread-outbox] failed to remove message for a missing thread", {
- environmentId: nextQueuedMessage.environmentId,
- threadId: nextQueuedMessage.threadId,
- messageId: nextQueuedMessage.messageId,
- error,
- });
- return false;
- },
- )
- : thread !== undefined
- ? sendQueuedMessage(nextQueuedMessage, thread)
- : Promise.resolve(false);
+ ? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
+ : creation !== undefined
+ ? creationProjectCwd !== null
+ ? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd)
+ : removeQueuedMessage("[thread-outbox] dropped pending task for a missing project")
+ : thread !== undefined
+ ? sendQueuedMessage(nextQueuedMessage, thread)
+ : Promise.resolve(false);
void delivery
.then((sent) => {
if (sent) {
@@ -284,8 +393,11 @@ export function useThreadOutboxDrain(): void {
}, [
connectedEnvironments,
dispatchingQueuedMessageId,
+ editingQueuedMessageIds,
+ projects,
queuedMessagesByThreadKey,
retryTick,
+ sendQueuedCreation,
sendQueuedMessage,
shellStatuses,
threads,
diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts
index fb090cd08..542c2d401 100644
--- a/apps/mobile/src/state/use-thread-outbox.ts
+++ b/apps/mobile/src/state/use-thread-outbox.ts
@@ -1,8 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
-import type { EnvironmentId } from "@t3tools/contracts";
+import type { EnvironmentId, MessageId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
+import { appAtomRegistry } from "./atom-registry";
import { environmentShell } from "./shell";
import { threadOutboxManager } from "./thread-outbox";
@@ -19,6 +20,35 @@ const threadOutboxShellStatusesAtom = Atom.make(
},
).pipe(Atom.withLabel("mobile:thread-outbox:shell-statuses"));
+/**
+ * Queued pending tasks the outbox drain must not deliver right now: the one
+ * open in the new-task editor, plus any whose latest edits could not be saved
+ * back yet (delivering those would send stale content). Editing sessions hold
+ * their message id here and release it once the queued payload is current.
+ */
+export const editingQueuedMessageIdsAtom = Atom.make<Readonly<Record<MessageId, true>>>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:thread-outbox:editing-message-ids"),
+);
+
+export function holdEditingQueuedMessage(messageId: MessageId): void {
+ const current = appAtomRegistry.get(editingQueuedMessageIdsAtom);
+ if (current[messageId]) {
+ return;
+ }
+ appAtomRegistry.set(editingQueuedMessageIdsAtom, { ...current, [messageId]: true });
+}
+
+export function releaseEditingQueuedMessage(messageId: MessageId): void {
+ const current = appAtomRegistry.get(editingQueuedMessageIdsAtom);
+ if (!current[messageId]) {
+ return;
+ }
+ const next = { ...current };
+ delete next[messageId];
+ appAtomRegistry.set(editingQueuedMessageIdsAtom, next);
+}
+
export function useThreadOutboxMessages() {
return useAtomValue(threadOutboxManager.queuedMessagesByThreadKeyAtom);
}