Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge e72791d6b8 Format workspace filesystem effect chains
Co-authored-by: Julius Marminge <[email protected]>
2026-07-03 16:07:37 +00:00
Cursor AgentandJulius Marminge b356b22c76 Provide path service in workspace filesystem test
Co-authored-by: Julius Marminge <[email protected]>
2026-07-03 16:07:06 +00:00
Cursor AgentandJulius Marminge ccfad54d73 Test workspace reads use injected filesystem
Co-authored-by: Julius Marminge <[email protected]>
2026-07-03 16:06:46 +00:00
Cursor AgentandJulius Marminge ddf731d112 Use Effect FileSystem for workspace reads
Co-authored-by: Julius Marminge <[email protected]>
2026-07-03 16:05:48 +00:00
32 changed files with 593 additions and 2203 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
vp staged
@@ -5,7 +5,6 @@ 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";
@@ -14,7 +13,6 @@ 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 ───────────────────────────────────────────────────── */
@@ -28,8 +26,6 @@ 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(
@@ -120,11 +116,8 @@ export function HomeRouteScreen() {
threadId: thread.id,
});
}}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
+2 -26
View File
@@ -22,9 +22,7 @@ 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,
@@ -49,7 +47,6 @@ 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>;
@@ -70,8 +67,6 @@ interface HomeScreenProps {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}
/* ─── Layout constants ───────────────────────────────────────────────── */
@@ -194,7 +189,6 @@ export function HomeScreen(props: HomeScreenProps) {
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
pendingTasks: props.pendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -202,7 +196,6 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
@@ -249,24 +242,10 @@ export function HomeScreen(props: HomeScreenProps) {
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
threadCount={item.group.threads.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 (
@@ -306,9 +285,7 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
@@ -318,8 +295,7 @@ export function HomeScreen(props: HomeScreenProps) {
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
@@ -57,31 +57,17 @@ 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],
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,
threads: Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
),
};
}
function makeGroupWithRecentCount(
key: string,
threadCount: number,
recentCount: number,
): HomeThreadGroup {
const group = makeGroup(key, threadCount);
return { ...group, recentThreads: group.threads.slice(0, recentCount) };
}
function itemTypes(items: ReadonlyArray<HomeListItem>): string[] {
return items.map((item) => item.type);
}
@@ -203,88 +189,4 @@ describe("buildHomeListLayout", () => {
expect(layout.stickyHeaderIndices).toEqual([0, 8]);
expect(layout.items[8]).toMatchObject({ type: "header", isFirst: false });
});
it("uses the group's recent-thread count as the default baseline when smaller than the page size", () => {
// Only 2 of the 10 threads are "recent"; the rest should stay hidden
// behind a show-more row until the user asks for more, even though the
// page size constant (6) is larger than the recent count.
const layout = buildHomeListLayout({
groups: [makeGroupWithRecentCount("alpha", 10, 2)],
displayStates: displayStates({}),
});
const threadItems = layout.items.filter((item) => item.type === "thread");
expect(threadItems).toHaveLength(2);
expect(layout.items.at(-1)).toMatchObject({
type: "show-more",
groupKey: "alpha",
hiddenCount: 8,
canShowLess: false,
});
});
it("does not shrink the baseline below the page size when recent threads exceed it", () => {
// 9 of 10 threads are "recent", which is still capped at the initial
// page size constant rather than showing all 9 by default.
const layout = buildHomeListLayout({
groups: [makeGroupWithRecentCount("alpha", 10, 9)],
displayStates: displayStates({}),
});
const threadItems = layout.items.filter((item) => item.type === "thread");
expect(threadItems).toHaveLength(HOME_INITIAL_VISIBLE_THREADS);
expect(layout.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 10 - HOME_INITIAL_VISIBLE_THREADS,
});
});
it("shows no show-more row when the recent-thread baseline covers every thread", () => {
const layout = buildHomeListLayout({
groups: [makeGroupWithRecentCount("alpha", 3, 3)],
displayStates: displayStates({}),
});
expect(itemTypes(layout.items)).toEqual(["header", "thread", "thread", "thread"]);
expect(layout.items.some((item) => item.type === "show-more")).toBe(false);
});
it("expands past a small recent-thread baseline once show-more is tapped", () => {
const group = makeGroupWithRecentCount("alpha", 10, 2);
const expanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
// show-more adds HOME_SHOW_MORE_STEP on top of the initial page size
// constant, not the smaller recency baseline, so every thread is now
// visible even though the group only had 2 "recent" threads.
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
// The show-more row still renders (canShowLess) because the baseline used
// to decide whether to offer it is fixed at the recency count, not the
// currently revealed count; there's simply nothing left hidden.
expect(expanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
});
it("resets an expanded group back to the recent-thread baseline on show-less", () => {
const group = makeGroupWithRecentCount("alpha", 10, 2);
const expandedState = nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more");
const resetState = nextGroupDisplayState(expandedState, "show-less");
const layout = buildHomeListLayout({
groups: [group],
displayStates: displayStates({ alpha: resetState }),
});
const threadItems = layout.items.filter((item) => item.type === "thread");
expect(threadItems).toHaveLength(2);
expect(layout.items.at(-1)).toMatchObject({ type: "show-more", hiddenCount: 8 });
});
});
+1 -32
View File
@@ -1,6 +1,5 @@
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. */
@@ -34,13 +33,6 @@ 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;
@@ -51,11 +43,7 @@ export interface HomeShowMoreListItem {
readonly canShowLess: boolean;
}
export type HomeListItem =
| HomeHeaderListItem
| HomePendingTaskListItem
| HomeThreadListItem
| HomeShowMoreListItem;
export type HomeListItem = HomeHeaderListItem | HomeThreadListItem | HomeShowMoreListItem;
export interface HomeListLayout {
readonly items: ReadonlyArray<HomeListItem>;
@@ -94,12 +82,6 @@ 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" &&
@@ -152,19 +134,6 @@ export function buildHomeListLayout(input: {
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > HOME_INITIAL_VISIBLE_THREADS;
// Pending (unsent) tasks lead the group and are never paginated away.
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
items.push({
type: "pending-task",
key: `pending-task:${pendingTask.message.messageId}`,
pendingTask,
isLast:
pendingIndex === group.pendingTasks.length - 1 &&
visibleThreads.length === 0 &&
!hasShowMoreRow,
});
}
for (const [threadIndex, thread] of visibleThreads.entries()) {
items.push({
type: "thread",
@@ -2,17 +2,9 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
CommandId,
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { buildHomeThreadGroups } from "./homeThreadList";
function makeProject(
@@ -52,33 +44,6 @@ function makeThread(
};
}
function makePendingTask(
input: Pick<EnvironmentProject, "environmentId" | "id" | "title" | "workspaceRoot">,
): PendingNewTask {
return {
title: input.title,
message: {
environmentId: input.environmentId,
threadId: ThreadId.make(`pending-thread-${input.id}`),
messageId: MessageId.make(`pending-message-${input.id}`),
commandId: CommandId.make(`pending-command-${input.id}`),
text: input.title,
attachments: [],
createdAt: "2026-06-29T00:00:00.000Z",
},
creation: {
projectId: input.id,
projectTitle: input.title,
projectCwd: input.workspaceRoot,
workspaceMode: "local",
branch: null,
worktreePath: null,
},
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
@@ -92,7 +57,6 @@ function buildGroups(
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
now: NOW,
...overrides,
});
}
@@ -256,141 +220,4 @@ 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("includes a thread exactly at the 5-day cutoff", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const exactlyAtCutoff = new Date(NOW - 5 * 24 * 60 * 60 * 1000).toISOString();
const justPastCutoff = new Date(NOW - 5 * 24 * 60 * 60 * 1000 - 1).toISOString();
const threads = [
makeThread({
environmentId,
id: ThreadId.make("at-cutoff"),
projectId: project.id,
title: "At cutoff",
updatedAt: exactlyAtCutoff,
}),
makeThread({
environmentId,
id: ThreadId.make("past-cutoff"),
projectId: project.id,
title: "Past cutoff",
updatedAt: justPastCutoff,
}),
];
const group = buildGroups([project], threads)[0];
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["at-cutoff"]);
});
it("returns an empty recentThreads list for a group with no threads", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const group = buildGroups([project], [], {
pendingTasks: [makePendingTask(project)],
})[0];
expect(group?.threads).toEqual([]);
expect(group?.recentThreads).toEqual([]);
});
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),
);
});
});
@@ -17,7 +17,6 @@ import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
@@ -26,32 +25,25 @@ export interface HomeThreadGroup {
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
readonly pendingTasks: PendingNewTask[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
const latestThread = group.threads.reduce(
return group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
return group.pendingTasks.reduce((latest, pendingTask) => {
const timestamp = Date.parse(pendingTask.message.createdAt);
return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
}, latestThread);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
@@ -76,49 +68,10 @@ export function buildHomeThreadGroups(input: {
if (existing) {
existing.projects.push(project);
} else {
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
groups.set(groupKey, { key: groupKey, projects: [project], 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;
@@ -140,7 +93,7 @@ export function buildHomeThreadGroups(input: {
for (const group of groups.values()) {
const representative = group.projects[0];
if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
if (!representative || group.threads.length === 0) {
continue;
}
@@ -155,13 +108,8 @@ 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 && matchingPendingTasks.length === 0) {
if (matchingThreads.length === 0) {
continue;
}
@@ -170,7 +118,6 @@ export function buildHomeThreadGroups(input: {
title,
representative,
projects: group.projects,
pendingTasks: matchingPendingTasks,
threads: sortThreads(matchingThreads, input.threadSortOrder),
});
}
@@ -1,57 +0,0 @@
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,5 +1,4 @@
import type { StaticScreenProps } from "@react-navigation/native";
import { useMemo } from "react";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
@@ -8,25 +7,11 @@ 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
@@ -35,10 +20,12 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
}}
/>
<NewTaskDraftScreen
initialProjectRef={initialProjectRef}
pendingTaskId={
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
}
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
? params.environmentId[0]
: params.environmentId,
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
}}
/>
</>
);
@@ -23,7 +23,6 @@ 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,
@@ -31,11 +30,10 @@ 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";
@@ -56,8 +54,6 @@ 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();
@@ -68,67 +64,15 @@ export function NewTaskDraftScreen(props: {
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const environmentConnected =
selectedProject !== null &&
connectedEnvironments.find(
(environment) => environment.environmentId === selectedProject.environmentId,
)?.connectionState === "connected";
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const appliedInitialProjectKeyRef = useRef<string | null>(null);
useEffect(() => {
return () => {
appliedInitialProjectKeyRef.current = null;
};
}, []);
const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
const attemptedPendingTaskIdRef = useRef<string | null>(null);
useEffect(() => {
if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
return;
}
// Attempt each pending task once: after it is delivered or deleted the
// editing session legitimately ends, and re-running must not navigate.
if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
return;
}
attemptedPendingTaskIdRef.current = props.pendingTaskId;
if (!beginEditingPendingTask(props.pendingTaskId)) {
// The queued task no longer exists (sent or deleted before opening).
navigation.dispatch(StackActions.replace("NewTask"));
}
}, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
useEffect(() => {
if (!props.pendingTaskId) return;
return () => {
// Allow a later navigation for the same pending task to re-hydrate it.
attemptedPendingTaskIdRef.current = null;
cancelEditingPendingTask();
};
}, [props.pendingTaskId, cancelEditingPendingTask]);
const borderColor = useThemeColor("--color-border");
const bodyText = useScaledTextRole("body");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
// A new navigation to this mounted screen delivers a fresh initialProjectRef
// reference — treat it as a new request and let it apply again.
const lastInitialProjectRefRef = useRef(props.initialProjectRef);
useEffect(() => {
// Pending-task editing owns project selection (and must not fall through
// to the replace("NewTask") fallback while its hydration is in flight).
if (props.pendingTaskId) {
return;
}
if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
lastInitialProjectRefRef.current = props.initialProjectRef;
appliedInitialProjectKeyRef.current = null;
}
if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
const directProject =
projects.find(
@@ -138,13 +82,6 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
// Apply the route's project once. Re-applying on every change would
// instantly revert environment/project switches made in the picker.
const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
if (appliedInitialProjectKeyRef.current === directProjectKey) {
return;
}
appliedInitialProjectKeyRef.current = directProjectKey;
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
@@ -169,8 +106,8 @@ export function NewTaskDraftScreen(props: {
}, [
logicalProjects,
projects,
props.initialProjectRef,
props.pendingTaskId,
props.initialProjectRef?.environmentId,
props.initialProjectRef?.projectId,
navigation,
selectedProject,
setProject,
@@ -337,24 +274,12 @@ 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,
]);
@@ -419,10 +344,6 @@ 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);
@@ -458,17 +379,17 @@ export function NewTaskDraftScreen(props: {
async function handleStart(): Promise<void> {
const selectedProject = flow.selectedProject;
const draftKey = flow.draftKey;
if (!selectedProject || !draftKey) {
if (!selectedProject) {
return;
}
const draft = getComposerDraftSnapshot(draftKey);
const draft = getComposerDraftSnapshot(
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
);
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();
@@ -482,46 +403,6 @@ 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,
@@ -529,21 +410,10 @@ 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);
@@ -558,17 +428,8 @@ export function NewTaskDraftScreen(props: {
return;
}
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();
}
flow.setPrompt("");
flow.clearAttachments();
navigation.dispatch(
StackActions.replace("Thread", {
environmentId: String(result.value.environmentId),
@@ -677,14 +538,8 @@ export function NewTaskDraftScreen(props: {
</ControlPillMenu>
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={
flow.submitting
? "Starting task"
: environmentConnected
? "Start task"
: "Queue task"
}
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
accessibilityLabel={flow.submitting ? "Starting task" : "Start task"}
icon="arrow.up"
onPress={() => void handleStart()}
variant="primary"
showChevron={false}
@@ -18,7 +18,6 @@ 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";
@@ -41,7 +40,6 @@ 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";
@@ -49,12 +47,7 @@ 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 {
PendingTaskListRow,
ThreadListGroupHeader,
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import { ThreadListGroupHeader, ThreadListRow, ThreadListShowMoreRow } from "./thread-list-items";
/**
* Shared capsule behind the sidebar header buttons — a native liquid-glass
@@ -169,8 +162,6 @@ 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)
@@ -197,14 +188,13 @@ function ThreadNavigationSidebarPane(
buildHomeThreadGroups({
projects,
threads,
pendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[options, pendingTasks, projects, props.searchQuery, threads],
[options, projects, props.searchQuery, threads],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -414,24 +404,10 @@ function ThreadNavigationSidebarPane(
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
threadCount={item.group.threads.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 (
@@ -473,12 +449,10 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
confirmDeletePendingTask,
confirmDeleteThread,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
projectCwdByKey,
props.selectedThreadKey,
props.width,
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
@@ -8,29 +8,18 @@ import type {
RuntimeMode,
ServerProviderSkill,
} from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
ThreadId,
} from "@t3tools/contracts";
import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } 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,
@@ -38,17 +27,6 @@ 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,
@@ -58,23 +36,6 @@ 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;
@@ -113,9 +74,6 @@ 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;
@@ -142,11 +100,6 @@ 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;
@@ -209,10 +162,6 @@ 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);
@@ -220,15 +169,6 @@ 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(
@@ -274,59 +214,24 @@ 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,
) ??
// 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));
projectsForEnvironment[0] ??
null;
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? 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 selectedProjectDraftKey = 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;
@@ -445,8 +350,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const branchTarget = useMemo(
() => ({
environmentId: selectedProject?.environmentId ?? null,
// `|| null` also skips the stand-in project's empty workspaceRoot.
cwd: selectedProject?.workspaceRoot || null,
cwd: selectedProject?.workspaceRoot ?? null,
query: null,
}),
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
@@ -495,11 +399,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -512,28 +415,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
},
});
},
[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],
[selectedProject, selectedProjectDraftKey, workspaceMode],
);
const refreshBranches = branchState.refresh;
@@ -575,183 +460,6 @@ 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,
@@ -761,9 +469,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode,
selectedBranchName,
selectedWorktreePath,
startFromOrigin,
draftKey: selectedProjectDraftKey,
editingPendingTask,
prompt,
attachments,
submitting,
@@ -787,11 +492,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedModelKey,
setWorkspaceMode,
selectBranch,
setStartFromOrigin,
beginEditingPendingTask,
finishEditingPendingTask,
cancelEditingPendingTask,
buildPendingTaskMessage,
setPrompt,
replaceAttachments,
appendAttachments,
@@ -808,16 +508,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[
attachments,
availableBranches,
beginEditingPendingTask,
branchQuery,
branchesLoading,
buildPendingTaskMessage,
cancelEditingPendingTask,
editingPendingTask,
environments,
expandedProvider,
filteredBranches,
finishEditingPendingTask,
interactionMode,
loadBranches,
logicalProjects,
@@ -832,7 +527,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedModelKey,
selectedModelOption,
selectedProjectDraftKey,
selectedProviderSkills,
setSelectedModelOptions,
selectedProject,
@@ -845,9 +539,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setStartFromOrigin,
setWorkspaceMode,
startFromOrigin,
submitting,
workspaceMode,
appendAttachments,
@@ -14,7 +14,6 @@ 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";
@@ -181,173 +180,6 @@ 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[] = [
@@ -4,6 +4,8 @@ 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,
@@ -15,13 +17,22 @@ import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
import { randomHex } from "../../lib/uuid";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { uuidv4 } 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 });
@@ -32,17 +43,15 @@ 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 = input.turnMetadata ?? makeTurnCommandMetadata();
const metadata = makeTurnCommandMetadata();
const threadId = ThreadId.make(metadata.threadId);
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
const validationError = validateProjectThreadCreation({
environmentId: input.project.environmentId,
@@ -56,26 +65,46 @@ export function useCreateProjectThread() {
return AsyncResult.failure(Cause.fail(validationError));
}
const isWorktree = input.envMode === "worktree";
const result = await startTurn({
environmentId: input.project.environmentId,
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,
input: {
commandId: CommandId.make(metadata.commandId),
threadId,
message: {
messageId: MessageId.make(metadata.messageId),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
},
modelSelection: input.modelSelection,
titleSeed: nextTitle,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
workspaceMode: input.envMode,
branch: input.branch,
worktreePath: input.worktreePath,
startFromOrigin: input.startFromOrigin ?? false,
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
}),
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,
},
});
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
@@ -1,89 +0,0 @@
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,
};
}
-49
View File
@@ -1,49 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { relativeTime } from "./time";
const NOW = Date.parse("2026-06-29T12:00:00.000Z");
describe("relativeTime", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(NOW);
});
afterEach(() => {
vi.useRealTimers();
});
it("returns '<1m' for unparseable input", () => {
expect(relativeTime("not-a-date")).toBe("<1m");
});
it("returns '<1m' for a timestamp that is right now", () => {
expect(relativeTime(new Date(NOW).toISOString())).toBe("<1m");
});
it("returns '<1m' for anything under a minute old, instead of a live seconds count", () => {
expect(relativeTime(new Date(NOW - 1_000).toISOString())).toBe("<1m");
expect(relativeTime(new Date(NOW - 59_000).toISOString())).toBe("<1m");
});
it("clamps timestamps in the future to '<1m' rather than a negative duration", () => {
expect(relativeTime(new Date(NOW + 60_000).toISOString())).toBe("<1m");
});
it("renders whole minutes once a minute has elapsed", () => {
expect(relativeTime(new Date(NOW - 60_000).toISOString())).toBe("1m");
expect(relativeTime(new Date(NOW - 90_000).toISOString())).toBe("1m");
expect(relativeTime(new Date(NOW - 59 * 60_000).toISOString())).toBe("59m");
});
it("switches to hours once 60 minutes have elapsed", () => {
expect(relativeTime(new Date(NOW - 60 * 60_000).toISOString())).toBe("1h");
expect(relativeTime(new Date(NOW - 23 * 60 * 60_000).toISOString())).toBe("23h");
});
it("switches to days once 24 hours have elapsed", () => {
expect(relativeTime(new Date(NOW - 24 * 60 * 60_000).toISOString())).toBe("1d");
expect(relativeTime(new Date(NOW - 9 * 24 * 60 * 60_000).toISOString())).toBe("9d");
});
});
-6
View File
@@ -1,9 +1,3 @@
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,7 +15,6 @@ export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutb
operation: Schema.Literals([
"load",
"enqueue",
"update",
"remove",
"clear-environment-load",
"clear-environment-remove",
@@ -104,35 +103,6 @@ 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 {
@@ -201,7 +171,6 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
serialize,
load,
enqueue,
update,
remove,
clearEnvironment,
};
+2 -56
View File
@@ -6,12 +6,10 @@ 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";
@@ -21,23 +19,11 @@ import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
const THREAD_OUTBOX_SCHEMA_VERSION = 3;
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
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, 2, THREAD_OUTBOX_SCHEMA_VERSION]),
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
environmentId: EnvironmentId,
threadId: ThreadId,
messageId: MessageId,
@@ -47,25 +33,12 @@ 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;
@@ -76,7 +49,6 @@ export interface QueuedThreadMessage {
readonly modelSelection?: ModelSelectionType;
readonly runtimeMode?: RuntimeModeType;
readonly interactionMode?: ProviderInteractionModeType;
readonly creation?: QueuedThreadCreation;
readonly createdAt: string;
}
@@ -149,43 +121,17 @@ 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,7 +3,6 @@ import {
CommandId,
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
@@ -13,7 +12,6 @@ import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
isQueuedThreadCreationSendable,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
@@ -294,43 +292,9 @@ 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,
@@ -339,7 +303,6 @@ describe("thread outbox", () => {
).toBe("wait");
expect(
resolveThreadOutboxDeliveryAction({
isCreation: false,
threadExists: false,
shellStatus: "live",
environmentConnected: true,
@@ -348,7 +311,6 @@ describe("thread outbox", () => {
).toBe("remove");
expect(
resolveThreadOutboxDeliveryAction({
isCreation: false,
threadExists: true,
shellStatus: "live",
environmentConnected: true,
@@ -357,89 +319,6 @@ 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,11 +20,6 @@ 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,7 +48,6 @@ export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
readonly startFromOrigin?: boolean;
}
export type ComposerDraftSettingsUpdate = Pick<
@@ -60,7 +59,6 @@ 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({
@@ -109,10 +107,6 @@ 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 &&
@@ -1,35 +0,0 @@
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]);
}
+64 -176
View File
@@ -1,44 +1,27 @@
import { useAtomValue } from "@effect/atom-react";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type MessageId,
} from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { CommandId, type MessageId } from "@t3tools/contracts";
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 { useProjects, useThreadShells } from "./entities";
import { 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 {
editingQueuedMessageIdsAtom,
useThreadOutboxMessages,
useThreadOutboxShellStatuses,
} from "./use-thread-outbox";
import { useThreadOutboxMessages, useThreadOutboxShellStatuses } from "./use-thread-outbox";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
@@ -65,17 +48,6 @@ 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}`);
}
@@ -92,11 +64,9 @@ 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>());
@@ -113,57 +83,52 @@ export function useThreadOutboxDrain(): void {
};
}, []);
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,
error,
});
return false;
}
};
return { reportFailure, completeDelivery };
}, []);
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
const { reportFailure, completeDelivery } = makeDeliveryHelpers(queuedMessage);
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,
error,
});
return false;
}
};
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
const updateResult = await updateThreadMetadata({
@@ -231,50 +196,7 @@ export function useThreadOutboxDrain(): void {
});
return completeDelivery(deliveryResult);
},
[
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],
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
);
useEffect(() => {
@@ -287,9 +209,6 @@ export function useThreadOutboxDrain(): void {
if (!nextQueuedMessage) {
continue;
}
if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
continue;
}
if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
continue;
}
@@ -299,65 +218,37 @@ 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,
shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty",
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"
? 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);
? 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);
void delivery
.then((sent) => {
if (sent) {
@@ -393,11 +284,8 @@ export function useThreadOutboxDrain(): void {
}, [
connectedEnvironments,
dispatchingQueuedMessageId,
editingQueuedMessageIds,
projects,
queuedMessagesByThreadKey,
retryTick,
sendQueuedCreation,
sendQueuedMessage,
shellStatuses,
threads,
+1 -31
View File
@@ -1,9 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, MessageId } from "@t3tools/contracts";
import type { EnvironmentId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "./atom-registry";
import { environmentShell } from "./shell";
import { threadOutboxManager } from "./thread-outbox";
@@ -20,35 +19,6 @@ 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,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, 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";
@@ -30,6 +31,34 @@ 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({
@@ -51,6 +80,26 @@ 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", () =>
@@ -185,8 +234,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound");
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ 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";
@@ -140,30 +138,28 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
const toOperationError =
(
operation: WorkspaceFileSystemOperationError["operation"],
operationPath: string,
resolvedPath = target.absolutePath,
) =>
(cause: unknown) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
resolvedPath,
operationPath,
operation,
cause,
}),
});
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 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 relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,84 +174,49 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
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({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
});
}
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,
};
}),
(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,12 +38,6 @@ 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
@@ -134,9 +128,6 @@ 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 && vp config --no-agent",
"prepare": "effect-tsgo patch",
"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",
+321 -312
View File
File diff suppressed because it is too large. Load diff
+2 -5
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].2
vite-plus: 0.2.2
vite: npm:@voidzero-dev/[email protected].1
vite-plus: 0.2.1
yaml: ^2.9.0
ignoredBuiltDependencies:
@@ -84,9 +84,6 @@ 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,10 +20,6 @@ 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",