Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 61ebadb99f Derive newThreadTarget from the full thread history, not search matches
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 14:29:11 -07:00
Theo BrowneandClaude Fable 5 542ce60b9e Show the quick new-thread button on multi-machine project groups
Instead of hiding the plus on aggregated groups, target the member that
owns the group's newest thread — the machine the user last worked on.
The draft's computer picker covers switching from there. Synthetic
pending-project groups still hide the button (placeholder shells).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 14:24:13 -07:00
Theo BrowneandClaude Fable 5 21eb3bdaa7 Add the quick new-thread button to the split-view sidebar
Same behavior as the compact Home list: a plus button on each
single-project group header opens the new-task draft targeted at that
project. The navigation callback is minted in AdaptiveWorkspaceLayout
(root stack) per the sidebar's no-navigation-hooks convention.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 14:16:42 -07:00
Theo BrowneandClaude Fable 5 8fb1785ee1 Extend collapse toggle hitSlop over the left gutter
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 12:49:12 -07:00
Theo BrowneandClaude Fable 5 14dcf30bc7 Fix group header plus-button vertical alignment
The header's asymmetric padding (pt-6/pb-3) sat on each Pressable, so the
plus button rendered high relative to the row's visual center. Move the
padding to the shared container so title and button share one centerline,
and tune the right inset so the plus lines up with the thread rows'
trailing chevron column. hitSlop keeps the padded strip tappable.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 12:44:04 -07:00
Theo BrowneandClaude Fable 5 cf9a56460c Treat empty workspaceRoot as null when matching hosts by basename
A pending-task placeholder project has workspaceRoot "" when no cwd was
snapshotted; an "" basename rejected every real host, emptying the
environment picker for that queued task.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 06:38:03 -07:00
Theo BrowneandClaude Fable 5 3fd7f73c95 Group header polish + second-round review fixes
- Replace the pencil icon with a larger plus, flush right with full-height
  padded hit area; drop the fold/unfold chevron (title press still toggles).
- Give the collapse toggle back its padded hit area (was reduced when
  padding moved to the outer View).
- Hide the quick new-thread button on synthetic pending-project groups.
- Environment picker: fall back to workspace basename/title matching when
  either side lacks repositoryIdentity, so still-indexing hosts stay visible.
- Deep-link/cold-start threads (no back stack) get an explicit header
  button to reach the threads list.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 06:29:21 -07:00
Theo BrowneandClaude Fable 5 3edb72e016 Address macroscope review findings
- selectEnvironment: fall back to workspace basename, then title, when the
  selected project has no repositoryIdentity, so computer switching still
  follows the same repo instead of resetting to the target's first project.
- ThreadListGroupHeader: lift the new-thread button out of the collapse
  toggle Pressable — nested touchables are invisible to VoiceOver/TalkBack.
- homeListItems: compare canShowLess against the group's recency baseline
  instead of the global page size, so stale groups can collapse back.
- HomeScreen: only offer the quick new-thread button on single-project
  groups; an aggregated group's representative is arbitrary.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 06:20:14 -07:00
Theo BrowneandClaude Fable 5 f726113e14 Remove the legacy thread navigation drawer and its edge-pan gesture
The drawer predates the current navigation (it shipped with the old
sheet-based thread routing). On phones its only trigger was an invisible
40px left-edge pan that competed with the native back swipe — the cause
of the dead far-left-edge back gesture — and on split view it never
rendered at all. Thread switching now goes through Home (compact) or the
persistent sidebar (split view), so the drawer, its gesture, its modal
component, and the now-orphaned thread-navigation-groups helpers are all
removed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 06:12:06 -07:00
Theo BrowneandClaude Fable 5 90ea2d376a Fail the header drawer pan at touch-down outside the header strip
The drawer gesture's 40px-wide left-edge hitSlop spans the full screen
height; its y-position check only ran in onEnd, after the pan had
already activated and stolen the touch from the native back-swipe
recognizer. Fail the gesture immediately when the touch starts below
the header so left-edge back-swipes work everywhere else.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 06:03:59 -07:00
Theo BrowneandClaude Fable 5 9ac1d7f398 Upgrade react-native-keyboard-controller 1.21.6 → 1.21.13 for contentInset scroll fixes
The far-edge/blank-area scroll failures trace to the keyboard-controller
version: @legendapp/list's KeyboardAwareLegendList requires >= 1.21.7,
and 1.21.12 additionally fixes the non-scrollable KeyboardChatScrollView
when blankSpace is large (viewport clamp + Android touch-dispatch
workaround).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 05:58:46 -07:00
Theo BrowneandClaude Fable 5 aa38fd2f3f Merge origin/main into integration/test-all, re-porting mobile changes onto the split-view restructure
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 05:20:28 -07:00
Theo BrowneandClaude Fable 5 efee0c9f26 Pull uncommitted work: home thread list changes (worktree c4c62ae9), resolve HomeScreen conflicts
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:16:56 -07:00
Theo BrowneandClaude Fable 5 9531885405 Pull uncommitted work: new-task draft flow changes (worktree 4673f128)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:16:31 -07:00
Theo BrowneandClaude Fable 5 ad6c6c1a30 Pull uncommitted work: thread swipe area / route screens (worktree 42795bc9), resolve import conflict
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:16:25 -07:00
Theo BrowneandClaude Fable 5 fab05c3ebe Pull uncommitted work: relative time formatting tweaks (worktree 2d307dad)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:15:42 -07:00
Theo BrowneandClaude Fable 5 6f5dd37c93 Pull uncommitted work: quick project thread button (worktree 27a5341b)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:15:42 -07:00
Theo BrowneandClaude Fable 5 e899698f2f Pull uncommitted work: fix mobile thread scroll jump (worktree 20990773)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-04 04:15:42 -07:00
Theo BrowneandClaude Opus 4.8 dd8c6493fd Mobile: enlarge new-task composer text to 17pt
The new-task draft composer (route /new/draft) typed its text at the
compact 14pt `composer` size, which felt too small for a full-screen,
primary task-description input. Bump it to the iOS-standard 17pt body
size via the existing `headline` typography token.

Scoped to the new-task screen only; the in-thread ThreadComposer pill
keeps its intentional 14pt.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-04 04:15:19 -07:00
Julius Marminge 4ac094fef6 Surface pending tasks in mobile home and draft flow (#3670) 2026-07-03 13:32:14 -07:00
Julius Marminge a7e43b2281 Upgrade Vite Plus and enable bundled dev opt-in (#3679) 2026-07-03 11:21:47 -07:00
41 changed files with 2534 additions and 1281 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
vp staged
+1 -1
View File
@@ -96,7 +96,7 @@
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.6",
"react-native-keyboard-controller": "1.21.13",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
@@ -333,7 +333,7 @@ function ArchivedThreadRow(props: {
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
>
{timestamp}
</Text>
@@ -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,21 @@ export function HomeRouteScreen() {
threadId: thread.id,
});
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onNewThreadInProject={(project) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
+34 -2
View File
@@ -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,9 @@ 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;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
}
/* ─── Layout constants ───────────────────────────────────────────────── */
@@ -189,6 +195,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 +203,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
@@ -241,11 +249,31 @@ export function HomeScreen(props: HomeScreenProps) {
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Aggregated groups (same repo across machines) have no single
// target project, and `pending-project:` groups hold a placeholder
// built from queued-task metadata rather than a real project shell,
// so the quick new-thread button is single-real-project only.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
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 +313,10 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
@@ -295,7 +326,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
@@ -57,14 +57,20 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
const project = makeProject(key, key);
const threads = Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
);
return {
key,
title: key,
representative: project,
projects: [project],
threads: Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
),
pendingTasks: [],
threads,
// All threads inside the recency window, so the baseline stays at the
// initial page size and the pagination expectations below hold.
recentThreads: threads,
newThreadTarget: project,
};
}
@@ -152,6 +158,48 @@ describe("buildHomeListLayout", () => {
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
});
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
// Stale project: 10 threads total but only 3 within the recency window.
const project = makeProject("stale", "stale");
const threads = Array.from({ length: 10 }, (_, index) =>
makeThread(`stale-thread-${index}`, project.id),
);
const group: HomeThreadGroup = {
key: "stale",
title: "stale",
representative: project,
projects: [project],
pendingTasks: [],
threads,
recentThreads: threads.slice(0, 3),
newThreadTarget: project,
};
const collapsedToRecent = buildHomeListLayout({
groups: [group],
displayStates: displayStates({}),
});
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
expect(collapsedToRecent.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 7,
canShowLess: false,
});
const expanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
expect(expanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
});
it("hides threads and the show-more row for collapsed groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
+53 -4
View File
@@ -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" &&
@@ -127,12 +145,40 @@ export function buildHomeListLayout(input: {
}
const totalCount = group.threads.length;
// Default to the group's recent-activity window (last few days, or a small
// fallback for stale projects), capped at the initial page size. Until the
// user taps "Show more", older threads stay hidden to save vertical space;
// "Show less" resets visibleCount to the initial constant, which lands back
// here at the recency baseline.
const baselineCount = Math.min(
group.recentThreads.length,
HOME_INITIAL_VISIBLE_THREADS,
totalCount,
);
const visibleCount = input.showAllThreads
? totalCount
: Math.min(Math.max(display.visibleCount, HOME_INITIAL_VISIBLE_THREADS), totalCount);
: Math.min(
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
? display.visibleCount
: baselineCount,
totalCount,
);
const visibleThreads = group.threads.slice(0, visibleCount);
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > HOME_INITIAL_VISIBLE_THREADS;
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
// 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({
@@ -149,7 +195,10 @@ export function buildHomeListLayout(input: {
key: `show-more:${group.key}`,
groupKey: group.key,
hiddenCount,
canShowLess: visibleCount > HOME_INITIAL_VISIBLE_THREADS,
// Compare against the group's own baseline, not the global page size:
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
// less" must be offered as soon as anything beyond the baseline shows.
canShowLess: visibleCount > baselineCount,
});
}
}
@@ -44,6 +44,8 @@ function makeThread(
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
@@ -57,6 +59,7 @@ function buildGroups(
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
now: NOW,
...overrides,
});
}
@@ -220,4 +223,144 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("recent-1"),
projectId: project.id,
title: "Today",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("recent-2"),
projectId: project.id,
title: "Within window",
updatedAt: "2026-06-25T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("old"),
projectId: project.id,
title: "Two weeks ago",
updatedAt: "2026-06-14T00:00:00.000Z",
}),
];
const group = buildGroups([project], threads)[0];
// Default view trims to recent threads...
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
// ...while full history stays available for the expanded view.
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
});
it("falls back to the most recent 3 threads when none are within 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads)[0];
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
"thread-4",
"thread-3",
"thread-2",
]);
expect(group?.threads).toHaveLength(5);
});
it("does not apply the recency window while searching", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
// Search reaches the full history rather than the 3-thread fallback.
expect(group?.recentThreads).toHaveLength(5);
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
group?.threads.map((thread) => thread.id),
);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const laptopProject = makeProject({
environmentId: laptopEnv,
id: ProjectId.make("project-laptop"),
title: "t3code",
repositoryIdentity,
});
const desktopProject = makeProject({
environmentId: desktopEnv,
id: ProjectId.make("project-desktop"),
title: "t3code",
repositoryIdentity,
});
const threads = [
makeThread({
environmentId: laptopEnv,
id: ThreadId.make("thread-laptop"),
projectId: laptopProject.id,
title: "Older laptop thread",
updatedAt: "2026-06-27T00:00:00.000Z",
}),
makeThread({
environmentId: desktopEnv,
id: ThreadId.make("thread-desktop"),
projectId: desktopProject.id,
title: "Newest desktop thread",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
];
// Aggregated into one group by repository; the quick new-thread target
// must follow the newest thread (desktop), not the arbitrary first member.
const groups = buildGroups([laptopProject, desktopProject], threads);
expect(groups).toHaveLength(1);
expect(groups[0]?.projects).toHaveLength(2);
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
});
});
+133 -5
View File
@@ -14,42 +14,92 @@ import type {
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
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">;
/**
* Default home view only surfaces threads active within this window, to keep the
* screen compact while keeping recent work visible.
*/
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
/** Fallback when a project has no threads inside the recency window. */
const RECENT_THREAD_FALLBACK_COUNT = 3;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
/** Full sorted thread history for the group (revealed when expanded / searching). */
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
/** Subset shown by default: threads from the last few days, or the most recent few. */
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
/**
* Where a quick "new thread in this project" should land. For aggregated
* groups (same repo on several machines) this is the member that owns the
* group's most recent thread — the machine the user last worked on — rather
* than the arbitrary first member; the draft's computer picker covers
* switching from there. Null only for synthetic pending-project groups,
* whose single "project" is a placeholder built from queued-task metadata.
*/
readonly newThreadTarget: EnvironmentProject | null;
}
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);
}
/**
* Trims a group's threads to recent activity for the default home view.
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
*/
function selectRecentThreads(
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
threadSortOrder: SidebarThreadSortOrder,
now: number,
): ReadonlyArray<EnvironmentThreadShell> {
const cutoff = now - RECENT_THREAD_WINDOW_MS;
const recent = sortedThreads.filter(
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
);
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
}
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;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
/** Current time used for the recency window; defaults to now. Injectable for tests. */
readonly now?: number;
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
@@ -68,10 +118,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 +182,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,17 +197,56 @@ 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;
}
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
// An active search should reach the full history, so the recency window
// only trims the default (no-query) view.
const recentThreads =
query.length === 0
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// Sorted newest-first, so the first thread whose project is a group member
// marks the machine the user last worked on. Derived from the FULL history
// (not the search-filtered subset) so the target is stable across queries.
const lastActiveProject = Arr.findFirst(
sortThreads(group.threads, input.threadSortOrder),
(thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
group.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.getOrNull,
);
result.push({
key: group.key,
title,
representative,
projects: group.projects,
threads: sortThreads(matchingThreads, input.threadSortOrder),
pendingTasks: matchingPendingTasks,
threads: sortedThreads,
recentThreads,
newThreadTarget: group.key.startsWith("pending-project:")
? null
: (lastActiveProject ?? representative),
});
}
@@ -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 };
}
@@ -1,4 +1,7 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useFocusEffect } from "@react-navigation/native";
import {
@@ -401,6 +404,20 @@ export function AdaptiveWorkspaceLayout(props: {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
}, [navigation]);
const handleNewThreadInProject = useCallback(
(project: EnvironmentProject) => {
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: String(project.environmentId),
projectId: String(project.id),
title: project.title,
},
});
},
[navigation],
);
const renderedSidebarWidth = useSharedValue(
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
);
@@ -477,6 +494,7 @@ export function AdaptiveWorkspaceLayout(props: {
selectedThreadKey={selectedThreadKey}
onOpenSettings={handleOpenSettings}
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
onNewThreadInProject={handleNewThreadInProject}
onSelectThread={handleSelectThread}
onSearchQueryChange={setPrimarySidebarSearchQuery}
searchQuery={primarySidebarSearchQuery}
@@ -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
}
/>
</>
);
@@ -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,24 +68,84 @@ 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 headlineText = useScaledTextRole("headline");
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(() => {
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
// 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;
}
const initialEnvironmentId = props.initialProjectRef?.environmentId;
const initialProjectId = props.initialProjectRef?.projectId;
if (initialEnvironmentId && initialProjectId) {
const directProject =
projects.find(
(project) =>
project.environmentId === props.initialProjectRef?.environmentId &&
project.id === props.initialProjectRef?.projectId,
project.environmentId === initialEnvironmentId && project.id === initialProjectId,
) ?? 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 +170,8 @@ export function NewTaskDraftScreen(props: {
}, [
logicalProjects,
projects,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
props.initialProjectRef,
props.pendingTaskId,
navigation,
selectedProject,
setProject,
@@ -274,12 +338,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 +420,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 +459,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 +483,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 +530,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 +559,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),
@@ -463,7 +603,7 @@ export function NewTaskDraftScreen(props: {
onPasteImages={(uris) => void handleNativePasteImages(uris)}
placeholder={`Describe a coding task in ${selectedProject.title}`}
style={{ flex: 1, minHeight: 0 }}
textStyle={bodyText}
textStyle={headlineText}
/>
</View>
@@ -538,8 +678,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}
@@ -18,10 +18,8 @@ import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { runOnJS } from "react-native-reanimated";
import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
@@ -73,7 +71,6 @@ export interface ThreadDetailScreenProps {
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
@@ -208,8 +205,6 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
});
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const { onOpenDrawer } = props;
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
@@ -263,28 +258,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[props.serverConfig, selectedInstanceId],
);
const completeDrawerGesture = useCallback(() => {
void Haptics.selectionAsync();
onOpenDrawer();
}, [onOpenDrawer]);
const drawerGestureThreshold = 80;
const headerDrawerGesture = useMemo(
() =>
Gesture.Pan()
.enabled(!isSplitLayout)
.hitSlop({ left: 0, width: 40 })
.activeOffsetX([10, 999])
.failOffsetY([-24, 24])
.onEnd((event) => {
const translationX = Math.max(event.translationX, 0);
if (event.y < drawerGestureThreshold && translationX > 56) {
runOnJS(completeDrawerGesture)();
}
}),
[completeDrawerGesture, isSplitLayout],
);
useLayoutEffect(() => {
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
@@ -311,16 +284,31 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
return;
}
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
});
// Wait for the keyboard dismissal (started by blur() on send) to finish
// before scrolling: scrollMessageToEnd freezes keyboard-driven inset
// updates while it runs, and a close event swallowed by that freeze
// leaves the keyboard padding permanently applied — overshooting the
// anchor and leaving a phantom bottom inset once the reply streams in.
void KeyboardController.dismiss()
.then(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
return scrollMessageToEnd({ animated: true, closeKeyboard: false });
})
.catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
});
});
return () => cancelAnimationFrame(frame);
}, [
@@ -379,115 +367,113 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
}, []);
return (
<GestureDetector gesture={headerDrawerGesture}>
<View className="flex-1">
{showContent ? (
<View className="flex-1">
{showContent ? (
<View
style={{ flex: 1 }}
onTouchStart={handleFeedTouchStart}
onTouchMove={handleFeedTouchMove}
onTouchEnd={handleFeedTouchEnd}
onTouchCancel={handleFeedTouchCancel}
>
<ThreadFeed
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
/>
</View>
) : (
<View style={{ flex: 1 }} />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
style={{ flex: 1 }}
onTouchStart={handleFeedTouchStart}
onTouchMove={handleFeedTouchMove}
onTouchEnd={handleFeedTouchEnd}
onTouchCancel={handleFeedTouchCancel}
ref={composerOverlayRef}
onLayout={onComposerLayout}
style={{ width: "100%", paddingTop: 8 }}
>
<ThreadFeed
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
) : (
<View style={{ flex: 1 }} />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
ref={composerOverlayRef}
onLayout={onComposerLayout}
style={{ width: "100%", paddingTop: 8 }}
>
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
/>
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
onSelectOption={props.onSelectUserInputOption}
onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
</KeyboardStickyView>
) : null}
</View>
</GestureDetector>
</KeyboardStickyView>
) : null}
</View>
);
});
@@ -1508,6 +1508,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// mount positions during attach, where UIKit applies the inset.
key={`${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`}
style={{ flex: 1 }}
// RN 0.81+ drops touches inside the contentInset area
// (facebook/react-native#54123); the anchored end space after a send
// is pure inset, so without this the blank region can't be scrolled.
applyWorkaroundForContentInsetHitTestBug
contentInsetAdjustmentBehavior={usesNativeAutomaticInsets ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
{...(usesNativeAutomaticInsets
@@ -1,255 +0,0 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
type ColorValue,
Modal,
Pressable,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { useProjects, useThreadShells } from "../../state/entities";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { resolveThreadStatus } from "./threadPresentation";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onStartNewTask: () => void;
}) {
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const drawerWidth = Math.min(width * 0.84, 360);
const [mounted, setMounted] = useState(props.visible);
const translateX = useSharedValue(-drawerWidth);
const overlayOpacity = useSharedValue(0);
const backdropColor = useThemeColor("--color-backdrop");
const drawerBg = useThemeColor("--color-drawer");
const drawerShadow = useThemeColor("--color-drawer-shadow");
const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle");
useEffect(() => {
if (props.visible) {
setMounted(true);
translateX.value = withTiming(0, { duration: 240 });
overlayOpacity.value = withTiming(1, { duration: 220 });
return;
}
overlayOpacity.value = withTiming(0, { duration: 180 });
translateX.value = withTiming(-drawerWidth, { duration: 220 }, (finished) => {
if (finished) {
runOnJS(setMounted)(false);
}
});
}, [drawerWidth, overlayOpacity, props.visible, translateX]);
const closeDrawer = useCallback(() => {
props.onClose();
}, [props]);
const panGesture = useMemo(
() =>
Gesture.Pan()
.activeOffsetX([-12, 12])
.failOffsetY([-24, 24])
.onUpdate((event) => {
translateX.value = Math.min(0, event.translationX);
})
.onEnd((event) => {
const shouldClose = event.translationX < -drawerWidth * 0.2 || event.velocityX < -500;
if (shouldClose) {
runOnJS(closeDrawer)();
return;
}
translateX.value = withTiming(0, { duration: 180 });
}),
[closeDrawer, drawerWidth, translateX],
);
const drawerStyle = useAnimatedStyle(() => ({
transform: [{ translateX: translateX.value }],
}));
const backdropStyle = useAnimatedStyle(() => ({
opacity: overlayOpacity.value,
}));
if (!mounted) {
return null;
}
return (
<Modal transparent visible={mounted} onRequestClose={props.onClose} statusBarTranslucent>
<View style={{ flex: 1 }}>
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: backdropColor,
},
backdropStyle,
]}
/>
<Pressable
style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0 }}
onPress={props.onClose}
/>
<GestureDetector gesture={panGesture}>
<Animated.View
style={[
{
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: drawerWidth,
backgroundColor: drawerBg,
paddingTop: insets.top + 10,
paddingBottom: Math.max(insets.bottom, 18),
boxShadow: `20px 0 36px ${String(drawerShadow)}`,
},
drawerStyle,
]}
>
<View className="flex-row items-center justify-between px-4 pb-5">
<Text className="text-2xl font-t3-bold">Threads</Text>
<Pressable
onPress={() => {
props.onClose();
props.onStartNewTask();
}}
className="h-11 w-11 items-center justify-center rounded-full bg-primary"
>
<SymbolView
name="square.and.pencil"
size={17}
tintColor={primaryForeground}
type="monochrome"
/>
</Pressable>
</View>
<ThreadNavigationDrawerContent
bottomInset={Math.max(insets.bottom, 18)}
borderSubtleColor={borderSubtleColor}
selectedThreadKey={props.selectedThreadKey}
onClose={props.onClose}
onSelectThread={props.onSelectThread}
/>
</Animated.View>
</GestureDetector>
</View>
</Modal>
);
}
function ThreadNavigationDrawerContent(props: {
readonly bottomInset: number;
readonly borderSubtleColor: ColorValue;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
}) {
const projects = useProjects();
const threads = useThreadShells();
const groupedThreads = useMemo(
() => buildThreadNavigationGroups({ projects, threads }),
[projects, threads],
);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: props.bottomInset + 12 }}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-base font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-sm font-medium text-foreground-tertiary">No threads yet</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
const status = resolveThreadStatus(thread);
return (
<Pressable
key={threadKey}
onPress={() => {
props.onSelectThread(thread);
props.onClose();
}}
style={{
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: props.borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-base font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-sm font-medium text-foreground-muted"
numberOfLines={1}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
{status ? <StatusPill {...status} /> : null}
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
);
}
@@ -1,5 +1,8 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "expo-symbols";
@@ -18,6 +21,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 +44,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 +52,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
@@ -100,6 +110,7 @@ interface ThreadNavigationSidebarProps {
readonly selectedThreadKey: string | null;
readonly onOpenSettings: () => void;
readonly onOpenEnvironmentSettings: () => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onRequestVisibility: () => void;
@@ -162,6 +173,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 +201,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>
@@ -403,11 +417,30 @@ function ThreadNavigationSidebarPane(
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Same gating as the compact Home list: aggregated groups have no
// single target project, and pending-project groups hold a
// placeholder shell rather than a real project.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
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,11 +482,14 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
confirmDeletePendingTask,
confirmDeleteThread,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
projectCwdByKey,
props.onNewThreadInProject,
props.selectedThreadKey,
props.width,
savedConnectionsById,
@@ -49,7 +49,6 @@ import {
useThreadGitRightHeaderItems,
} from "./ThreadGitControls";
import { GitOverviewSheet } from "./git/GitOverviewSheet";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
@@ -197,7 +196,6 @@ function ThreadRouteContent(
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const navigation = useNavigation();
const params = props.route.params;
const [drawerVisible, setDrawerVisible] = useState(false);
const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const threadId = firstRouteParam(params.threadId);
@@ -326,18 +324,6 @@ function ThreadRouteContent(
);
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
const handleOpenDrawer = useCallback(() => {
if (!layout.usesSplitView) {
setDrawerVisible(true);
}
}, [layout.usesSplitView]);
useEffect(() => {
if (layout.usesSplitView) {
setDrawerVisible(false);
}
}, [layout.usesSplitView]);
const handleOpenGitInspector = useCallback(() => {
setInspectorSelection({ routeThreadIdentity, mode: "git" });
showAuxiliaryPane("inspector");
@@ -655,6 +641,22 @@ function ThreadRouteContent(
],
[panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
);
// Deep links / cold starts land with Thread as the ONLY route, where the
// native back button does not render. Provide an explicit Home escape for
// that case; when history exists the native back button is used instead.
const canGoBack = navigation.canGoBack();
const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
() => [
withNativeGlassHeaderItem({
accessibilityLabel: "Go to threads list",
icon: { name: "list.bullet", type: "sfSymbol" as const },
identifier: "thread-left-home",
onPress: () => navigation.dispatch(StackActions.replace("Home")),
type: "button" as const,
}),
],
[navigation],
);
if (!environmentId || !threadId) {
return <OpeningThreadLoadingScreen />;
@@ -704,7 +706,6 @@ function ThreadRouteContent(
selectedThreadQueueCount={composer.selectedThreadQueueCount}
layoutVariant={layout.variant}
usesAutomaticContentInsets={usesNativeHeaderGlass}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
onPickDraftImages={composer.onPickDraftImages}
@@ -722,23 +723,6 @@ function ThreadRouteContent(
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
onSubmitUserInput={requests.onSubmitUserInput}
/>
{layout.usesSplitView ? null : (
<ThreadNavigationDrawer
visible={drawerVisible}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(thread.environmentId),
threadId: String(thread.id),
}),
);
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
/>
)}
</View>
</>
);
@@ -757,11 +741,17 @@ function ThreadRouteContent(
: undefined,
title: selectedThread.title,
headerBackVisible: !layout.usesSplitView,
// Compact uses the NATIVE back button (Thread lives flat in the root
// stack now, so a real previous route exists); only split view needs
// custom left items.
// Compact uses the NATIVE back button when a previous route exists;
// deep links / cold starts get an explicit Home button instead.
// Split view always uses its custom left items.
unstable_headerLeftItems:
Platform.OS === "ios" && layout.usesSplitView ? () => splitLeftHeaderItems : undefined,
Platform.OS === "ios"
? layout.usesSplitView
? () => splitLeftHeaderItems
: canGoBack
? undefined
: () => compactHomeHeaderItems
: undefined,
// Search lives in the persistent sidebar, so the split header keeps
// the git controls on the RIGHT (no center items — center space is
// reserved for future breadcrumbs/status).
@@ -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,42 +220,17 @@ 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(
() =>
pipe(
[
...new Set(
pipe(
projects,
Arr.map((project) => project.environmentId),
),
),
],
Arr.map((environmentId) => {
const environment = savedConnectionsById[environmentId];
if (!environment) {
return null;
}
return {
environmentId,
environmentLabel: environment.environmentLabel,
};
}),
Arr.filter(
(
entry,
): entry is {
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
} => entry !== null,
),
),
[projects, savedConnectionsById],
);
const projectsForEnvironment = useMemo(
() =>
pipe(
@@ -214,24 +240,115 @@ 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));
// Only offer machines that actually host the currently selected repository, so
// switching computers moves the same repo across machines instead of jumping to
// whatever unrelated project happens to be first on the other machine. Repository
// identity is the primary signal; projects that haven't reported one yet (still
// indexing) fall back to workspace basename / title so a valid host isn't hidden.
const selectedRepositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
// `|| null` (not `??`): a pending-task placeholder project can have an empty
// workspaceRoot, and an "" basename would reject every real host below.
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
const selectedProjectTitle = selectedProject?.title ?? null;
const environments = useMemo(() => {
const seen = new Set<EnvironmentId>();
const result: Array<{
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
}> = [];
const hostsSelectedRepository = (project: EnvironmentProject) => {
if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
return true;
}
const projectKey = project.repositoryIdentity?.canonicalKey ?? null;
if (selectedRepositoryKey !== null && projectKey !== null) {
return projectKey === selectedRepositoryKey;
}
return (
project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
(selectedProjectTitle !== null && project.title === selectedProjectTitle)
);
};
for (const project of projects) {
if (!hostsSelectedRepository(project)) {
continue;
}
if (seen.has(project.environmentId)) {
continue;
}
const environment = savedConnectionsById[project.environmentId];
if (!environment) {
continue;
}
seen.add(project.environmentId);
result.push({
environmentId: project.environmentId,
environmentLabel: environment.environmentLabel,
});
}
return result;
}, [
projects,
savedConnectionsById,
selectedRepositoryKey,
selectedWorkspaceBasename,
selectedProjectTitle,
]);
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 +467,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],
@@ -384,10 +502,36 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedProjectKey(nextProjectKey);
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
}, []);
const selectEnvironment = useCallback(
(environmentId: EnvironmentId) => {
const projectsOnTarget = projects.filter(
(project) => project.environmentId === environmentId,
);
const repositoryKey = selectedProject?.repositoryIdentity?.canonicalKey ?? null;
// Prefer the repository identity; projects without one (e.g. not yet
// indexed) fall back to workspace basename, then title, so switching
// computers still follows the same repo instead of resetting to
// whatever project is first on the target machine.
const workspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
const match =
(repositoryKey !== null
? projectsOnTarget.find(
(project) => (project.repositoryIdentity?.canonicalKey ?? null) === repositoryKey,
)
: undefined) ??
(workspaceBasename !== null
? projectsOnTarget.find(
(project) => project.workspaceRoot.split("/").at(-1) === workspaceBasename,
)
: undefined) ??
(selectedProject !== null
? projectsOnTarget.find((project) => project.title === selectedProject.title)
: undefined);
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
},
[projects, selectedProject],
);
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
@@ -399,10 +543,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 +560,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 +623,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 +809,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode,
selectedBranchName,
selectedWorktreePath,
startFromOrigin,
draftKey: selectedProjectDraftKey,
editingPendingTask,
prompt,
attachments,
submitting,
@@ -492,6 +835,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedModelKey,
setWorkspaceMode,
selectBranch,
setStartFromOrigin,
beginEditingPendingTask,
finishEditingPendingTask,
cancelEditingPendingTask,
buildPendingTaskMessage,
setPrompt,
replaceAttachments,
appendAttachments,
@@ -508,11 +856,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[
attachments,
availableBranches,
beginEditingPendingTask,
branchQuery,
branchesLoading,
buildPendingTaskMessage,
cancelEditingPendingTask,
editingPendingTask,
environments,
expandedProvider,
filteredBranches,
finishEditingPendingTask,
interactionMode,
loadBranches,
logicalProjects,
@@ -527,6 +880,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedModelKey,
selectedModelOption,
selectedProjectDraftKey,
selectedProviderSkills,
setSelectedModelOptions,
selectedProject,
@@ -539,7 +893,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setStartFromOrigin,
setWorkspaceMode,
startFromOrigin,
submitting,
workspaceMode,
appendAttachments,
@@ -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";
@@ -42,31 +43,54 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
readonly isFirst: boolean;
readonly groupKey: string;
readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void;
/** Project a quick new thread should target; null hides the button. */
readonly newThreadTarget?: EnvironmentProject | null;
readonly onNewThread?: (project: EnvironmentProject) => void;
}) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const { groupKey, onGroupAction } = props;
const iconMutedColor = useThemeColor("--color-icon-muted");
const { groupKey, onGroupAction, onNewThread } = props;
const newThreadTarget = props.newThreadTarget ?? null;
const compact = props.variant === "compact";
const handleToggle = useCallback(
() => onGroupAction(groupKey, "toggle-collapsed"),
[groupKey, onGroupAction],
);
const handleNewThread = useCallback(() => {
if (newThreadTarget) {
onNewThread?.(newThreadTarget);
}
}, [newThreadTarget, onNewThread]);
const showNewThreadButton = onNewThread !== undefined && newThreadTarget !== null;
// The new-thread button is a SIBLING of the collapse toggle, not a child:
// nested touchables are unreachable to VoiceOver/TalkBack (the parent
// swallows focus). Row padding lives on the container (explicit styles —
// dynamic padding classes on Pressable did not apply reliably) so both
// children share one centerline; hitSlop restores the padded tap area.
const verticalHitSlop = { top: props.isFirst ? 8 : 24, bottom: 12 };
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: !props.collapsed }}
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
className={compact ? "bg-screen" : undefined}
onPress={handleToggle}
<View
className={compact ? "flex-row items-center bg-screen" : "flex-row items-center"}
style={{
minHeight: compact ? 44 : 36,
paddingLeft: compact ? 20 : 12,
// Compact right padding centers the 20pt plus glyph on the thread
// rows' trailing chevron column (18 + 13/2 ≈ 24.5 from the edge).
paddingRight: compact ? 14 : 12,
paddingBottom: compact ? 12 : 8,
paddingTop: props.isFirst ? (compact ? 8 : 4) : compact ? 24 : 20,
}}
>
<View
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: !props.collapsed }}
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
className={
compact
? `flex-row items-center gap-2.5 px-5 pb-3 ${props.isFirst ? "pt-2" : "pt-6"}`
: `flex-row items-center gap-2 px-3 pb-2 ${props.isFirst ? "pt-1" : "pt-5"}`
compact ? "flex-1 flex-row items-center gap-2.5" : "flex-1 flex-row items-center gap-2"
}
style={{ minHeight: compact ? 44 : 36 }}
hitSlop={{ ...verticalHitSlop, left: compact ? 20 : 12 }}
onPress={handleToggle}
>
<ProjectFavicon
environmentId={props.project.environmentId}
@@ -94,15 +118,25 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
>
{props.threadCount}
</Text>
<SymbolView
name={props.collapsed ? "chevron.right" : "chevron.down"}
size={compact ? 13 : 11}
tintColor={iconSubtleColor}
type="monochrome"
weight="semibold"
/>
</View>
</Pressable>
</Pressable>
{showNewThreadButton ? (
<Pressable
accessibilityLabel={`Create new thread in ${props.title}`}
accessibilityRole="button"
hitSlop={{ ...verticalHitSlop, left: 10, right: 14 }}
onPress={handleNewThread}
style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1, paddingLeft: 12 })}
>
<SymbolView
name="plus"
size={compact ? 20 : 16}
tintColor={iconMutedColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
</View>
);
});
@@ -180,6 +214,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[] = [
@@ -1,111 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildThreadNavigationGroups } from "./thread-navigation-groups";
const environmentId = EnvironmentId.make("environment-1");
function makeProject(input: Pick<EnvironmentProject, "id" | "title">): EnvironmentProject {
return {
environmentId,
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Pick<EnvironmentThreadShell, "id" | "projectId" | "title"> &
Partial<EnvironmentThreadShell>,
): EnvironmentThreadShell {
return {
environmentId,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
describe("buildThreadNavigationGroups", () => {
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const threads = [
makeThread({
id: ThreadId.make("older"),
projectId: project.id,
title: "Fix reconnect flow",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
makeThread({
id: ThreadId.make("newer"),
projectId: project.id,
title: "Build adaptive sidebar",
updatedAt: "2026-06-03T00:00:00.000Z",
}),
];
it("sorts each group by recent activity", () => {
expect(
buildThreadNavigationGroups({ projects: [project], threads })[0]?.threads.map(
(thread) => thread.id,
),
).toEqual(["newer", "older"]);
});
it("matches thread titles without dropping their group", () => {
const groups = buildThreadNavigationGroups({
projects: [project],
threads,
searchQuery: "reconnect",
});
expect(groups).toHaveLength(1);
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual(["older"]);
});
it("keeps every thread when the project title matches", () => {
expect(
buildThreadNavigationGroups({
projects: [project],
threads,
searchQuery: "t3 code",
})[0]?.threads.map((thread) => thread.id),
).toEqual(["newer", "older"]);
});
it("excludes archived threads from the navigation sidebar", () => {
const archived = makeThread({
id: ThreadId.make("archived"),
projectId: project.id,
title: "Archived work",
archivedAt: "2026-06-04T00:00:00.000Z",
updatedAt: "2026-06-04T00:00:00.000Z",
});
expect(
buildThreadNavigationGroups({
projects: [project],
threads: [...threads, archived],
})[0]?.threads.map((thread) => thread.id),
).toEqual(["newer", "older"]);
});
});
@@ -1,64 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
export interface ThreadNavigationGroup {
readonly key: string;
readonly title: string;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
const threadActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
title: Order.String,
}),
(thread: EnvironmentThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
title: thread.title,
}),
);
export function buildThreadNavigationGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly searchQuery?: string;
}): ReadonlyArray<ThreadNavigationGroup> {
const query = input.searchQuery?.trim().toLocaleLowerCase() ?? "";
const activeThreads = input.threads.filter((thread) => thread.archivedAt === null);
return groupProjectsByRepository({ ...input, threads: activeThreads }).flatMap((group) => {
const threads = Arr.sort(
group.projects.flatMap((projectGroup) => projectGroup.threads),
threadActivityOrder,
);
const title = group.projects[0]?.project.title ?? group.title;
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
group.title.toLocaleLowerCase().includes(query) ||
group.projects.some((projectGroup) =>
projectGroup.project.title.toLocaleLowerCase().includes(query),
);
const matchingThreads = groupMatches
? threads
: threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
if (query.length > 0 && matchingThreads.length === 0) {
return [];
}
return [
{
key: group.key,
title,
threads: matchingThreads,
},
];
});
}
@@ -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);
@@ -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,
};
}
+4 -3
View File
@@ -1,12 +1,13 @@
export function relativeTime(input: string): string {
const timestamp = Date.parse(input);
if (Number.isNaN(timestamp)) {
return "now";
return "<1m";
}
// Anything under a minute renders as "<1m" rather than a live seconds count.
// The seconds ticker changed width every second and reflowed the surrounding row.
const deltaSeconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000));
if (deltaSeconds < 10) return "now";
if (deltaSeconds < 60) return `${deltaSeconds}s`;
if (deltaSeconds < 60) return "<1m";
const deltaMinutes = Math.floor(deltaSeconds / 60);
if (deltaMinutes < 60) return `${deltaMinutes}m`;
+6
View File
@@ -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(
"",
);
@@ -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,
};
+56 -2
View File
@@ -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;
+121
View File
@@ -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(
+5
View File
@@ -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);
}
@@ -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 &&
@@ -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]);
}
+174 -62
View File
@@ -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,
+31 -1
View File
@@ -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);
}
@@ -1,10 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe, expect } from "@effect/vitest";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -31,34 +30,6 @@ const TestLayer = Layer.empty.pipe(
Layer.provideMerge(NodeServices.layer),
);
const OpenFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
open: (path, options) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "open",
pathOrDescriptor: String(path),
description: `open intercepted by FileSystem test layer (options: ${String(Boolean(options))})`,
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const WorkspaceFileSystemOpenFailureLayer = WorkspaceFileSystem.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(Layer.mock(WorkspaceEntries.WorkspaceEntries)({})),
Layer.provideMerge(OpenFailureFileSystemLayer),
Layer.provideMerge(Path.layer),
);
const makeTempDir = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({
@@ -80,26 +51,6 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
});
it.effect("WorkspaceFileSystem.readFile opens files through the injected FileSystem service", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n");
const fileSystem = yield* FileSystem.FileSystem;
const resolvedPath = yield* fileSystem.realPath(`${cwd}/src/index.ts`);
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: "src/index.ts" })
.pipe(Effect.flip);
assert.instanceOf(error, WorkspaceFileSystem.WorkspaceFileSystemOperationError);
assert.equal(error.operation, "open");
assert.equal(error.operationPath, resolvedPath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(WorkspaceFileSystemOpenFailureLayer)),
);
it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => {
describe("readFile", () => {
it.effect("reads UTF-8 files relative to the workspace root", () =>
@@ -234,8 +185,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound");
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
}),
);
});
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -6,6 +7,8 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -16,7 +19,6 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -138,28 +140,30 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const toOperationError =
(
operation: WorkspaceFileSystemOperationError["operation"],
operationPath: string,
resolvedPath = target.absolutePath,
) =>
(cause: unknown) =>
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath,
operationPath,
operation,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
});
const realWorkspaceRoot = yield* fileSystem
.realPath(input.cwd)
.pipe(Effect.mapError(toOperationError("realpath-workspace-root", input.cwd)));
const realTargetPath = yield* fileSystem
.realPath(target.absolutePath)
.pipe(Effect.mapError(toOperationError("realpath-target", target.absolutePath)));
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -174,49 +178,84 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem
.open(realTargetPath, { flag: "r" })
.pipe(Effect.mapError(toOperationError("open", realTargetPath, realTargetPath)));
const stat = yield* file.stat.pipe(
Effect.mapError(toOperationError("stat", realTargetPath, realTargetPath)),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const byteLength = Number(stat.size);
const truncated = stat.size > BigInt(PROJECT_READ_FILE_MAX_BYTES);
const bytesToRead = truncated ? PROJECT_READ_FILE_MAX_BYTES : byteLength;
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: Option.getOrElse(
yield* file
.readAlloc(bytesToRead)
.pipe(Effect.mapError(toOperationError("read", realTargetPath, realTargetPath))),
() => new Uint8Array(),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated,
};
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
+9
View File
@@ -38,6 +38,12 @@ const configuredHostedAppUrl = (() => {
})();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
// dev for much faster startup/reload on large module graphs, with HMR served
// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
const buildSourcemap: boolean | "hidden" =
sourcemapEnv === "0" || sourcemapEnv === "false"
? false
@@ -128,6 +134,9 @@ export default defineConfig(() => {
tsconfigPaths: true,
dedupe: ["react", "react-dom"],
},
experimental: {
bundledDev,
},
server: {
host,
port,
+1 -1
View File
@@ -3,7 +3,7 @@
"private": true,
"type": "module",
"scripts": {
"prepare": "effect-tsgo patch",
"prepare": "effect-tsgo patch && vp config --no-agent",
"dev": "node scripts/dev-runner.ts dev",
"dev:server": "node scripts/dev-runner.ts dev:server",
"dev:web": "node scripts/dev-runner.ts dev:web",
+317 -326
View File
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -44,8 +44,8 @@ catalog:
effect: 4.0.0-beta.78
jose: 6.2.2
typescript: ~6.0.3
vite: npm:@voidzero-dev/[email protected].1
vite-plus: 0.2.1
vite: npm:@voidzero-dev/[email protected].2
vite-plus: 0.2.2
yaml: ^2.9.0
ignoredBuiltDependencies:
@@ -84,6 +84,9 @@ overrides:
"@pierre/diffs>@shikijs/transformers": ^4.2.0
"@types/node": "catalog:"
effect: "catalog:"
# Pin to the version our patch targets; expo-modules-core's ~56.0.10 range
# otherwise floats to newer releases on fresh resolves (ERR_PNPM_UNUSED_PATCH).
expo-modules-jsi: 56.0.10
vite: "catalog:"
yaml: "catalog:"
+4
View File
@@ -20,6 +20,10 @@ export default defineConfig({
hookTimeout: 60_000,
testTimeout: 60_000,
},
staged: {
// Formatter only for now — no lint or typecheck on commit.
"*": "vp fmt",
},
fmt: {
ignorePatterns: [
".reference",