Compare commits

...
21 changed files with 1331 additions and 546 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+7 -7
View File
@@ -34,15 +34,15 @@ export default function BranchToolbar({
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarProps) {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const serverThread = useStore((store) => store.threadShellById[threadId]);
const serverSession = useStore((store) => store.threadSessionById[threadId] ?? null);
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const serverThread = threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = projects.find((project) => project.id === activeProjectId);
const activeProject = useStore((store) =>
activeProjectId ? store.projectById[activeProjectId] : undefined,
);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
@@ -60,7 +60,7 @@ export default function BranchToolbar({
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
if (serverThread?.session && worktreePath !== activeWorktreePath && api) {
if (serverSession && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
@@ -96,7 +96,7 @@ export default function BranchToolbar({
},
[
activeThreadId,
serverThread?.session,
serverSession,
activeWorktreePath,
hasServerThread,
setThreadBranchAction,
+16 -2
View File
@@ -1167,8 +1167,22 @@ describe("ChatView timeline estimator parity (full app)", () => {
stickyActiveProvider: null,
});
useStore.setState({
projects: [],
threads: [],
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: false,
});
useTerminalStateStore.persist.clearStorage();
+140 -64
View File
@@ -1,6 +1,7 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { type Thread } from "../types";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -178,7 +179,7 @@ const makeThread = (input?: {
startedAt: string | null;
completedAt: string | null;
} | null;
}) => ({
}): Thread => ({
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
@@ -205,94 +206,172 @@ const makeThread = (input?: {
activities: [],
});
function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>) {
const projectId = ProjectId.makeUnsafe("project-1");
useStore.setState({
projectIds: [projectId],
projectById: {
[projectId]: {
id: projectId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
},
createdAt: "2026-03-29T00:00:00.000Z",
updatedAt: "2026-03-29T00:00:00.000Z",
scripts: [],
},
},
threadIds: threads.map((thread) => thread.id),
threadIdsByProjectId: {
[projectId]: threads.map((thread) => thread.id),
},
threadShellById: Object.fromEntries(
threads.map((thread) => [
thread.id,
{
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
error: thread.error,
createdAt: thread.createdAt,
archivedAt: thread.archivedAt,
updatedAt: thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
},
]),
),
threadSessionById: Object.fromEntries(threads.map((thread) => [thread.id, thread.session])),
threadTurnStateById: Object.fromEntries(
threads.map((thread) => [
thread.id,
{
latestTurn: thread.latestTurn,
...(thread.pendingSourceProposedPlan
? { pendingSourceProposedPlan: thread.pendingSourceProposedPlan }
: {}),
},
]),
),
messageIdsByThreadId: Object.fromEntries(
threads.map((thread) => [thread.id, thread.messages.map((message) => message.id)]),
),
messageByThreadId: Object.fromEntries(
threads.map((thread) => [
thread.id,
Object.fromEntries(thread.messages.map((message) => [message.id, message])),
]),
),
activityIdsByThreadId: Object.fromEntries(
threads.map((thread) => [thread.id, thread.activities.map((activity) => activity.id)]),
),
activityByThreadId: Object.fromEntries(
threads.map((thread) => [
thread.id,
Object.fromEntries(thread.activities.map((activity) => [activity.id, activity])),
]),
),
proposedPlanIdsByThreadId: Object.fromEntries(
threads.map((thread) => [thread.id, thread.proposedPlans.map((plan) => plan.id)]),
),
proposedPlanByThreadId: Object.fromEntries(
threads.map((thread) => [
thread.id,
Object.fromEntries(thread.proposedPlans.map((plan) => [plan.id, plan])),
]),
),
turnDiffIdsByThreadId: Object.fromEntries(
threads.map((thread) => [
thread.id,
thread.turnDiffSummaries.map((summary) => summary.turnId),
]),
),
turnDiffSummaryByThreadId: Object.fromEntries(
threads.map((thread) => [
thread.id,
Object.fromEntries(thread.turnDiffSummaries.map((summary) => [summary.turnId, summary])),
]),
),
sidebarThreadSummaryById: {},
bootstrapComplete: true,
});
}
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
useStore.setState((state) => ({
...state,
projects: [],
threads: [],
bootstrapComplete: true,
}));
setStoreThreads([]);
});
describe("waitForStartedServerThread", () => {
it("resolves immediately when the thread is already started", async () => {
const threadId = ThreadId.makeUnsafe("thread-started");
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
setStoreThreads([
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
]);
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
});
it("waits for the thread to start via subscription updates", async () => {
const threadId = ThreadId.makeUnsafe("thread-wait");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
setStoreThreads([makeThread({ id: threadId })]);
const promise = waitForStartedServerThread(threadId, 500);
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
setStoreThreads([
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
]);
await expect(promise).resolves.toBe(true);
});
it("handles the thread starting between the initial read and subscription setup", async () => {
const threadId = ThreadId.makeUnsafe("thread-race");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
setStoreThreads([makeThread({ id: threadId })]);
const originalSubscribe = useStore.subscribe.bind(useStore);
let raced = false;
vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
if (!raced) {
raced = true;
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-race"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
setStoreThreads([
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-race"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
]);
}
return originalSubscribe(listener);
});
@@ -304,10 +383,7 @@ describe("waitForStartedServerThread", () => {
vi.useFakeTimers();
const threadId = ThreadId.makeUnsafe("thread-timeout");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
setStoreThreads([makeThread({ id: threadId })]);
const promise = waitForStartedServerThread(threadId, 500);
await vi.advanceTimersByTimeAsync(500);
+3 -3
View File
@@ -3,7 +3,7 @@ import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession }
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { useStore } from "../store";
import { selectThreadById, useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -202,7 +202,7 @@ export async function waitForStartedServerThread(
threadId: ThreadId,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId);
const getThread = () => selectThreadById(threadId)(useStore.getState());
const thread = getThread();
if (threadHasStarted(thread)) {
@@ -225,7 +225,7 @@ export async function waitForStartedServerThread(
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) {
if (!threadHasStarted(selectThreadById(threadId)(state))) {
return;
}
finish(true);
+36 -78
View File
@@ -64,7 +64,7 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
import { useProjectById, useThreadById } from "../storeSelectors";
import { createThreadSelector } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
@@ -82,8 +82,6 @@ import {
type Thread,
type TurnDiffSummary,
} from "../types";
import { LRUCache } from "../lib/lruCache";
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -210,77 +208,28 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500;
const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024;
const threadPlanCatalogCache = new LRUCache<{
proposedPlans: Thread["proposedPlans"];
entry: ThreadPlanCatalogEntry;
}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES);
function estimateThreadPlanCatalogEntrySize(thread: Thread): number {
return Math.max(
64,
thread.id.length +
thread.proposedPlans.reduce(
(total, plan) =>
total +
plan.id.length +
plan.planMarkdown.length +
plan.updatedAt.length +
(plan.turnId?.length ?? 0),
0,
),
);
}
function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry {
const cached = threadPlanCatalogCache.get(thread.id);
if (cached && cached.proposedPlans === thread.proposedPlans) {
return cached.entry;
}
const entry: ThreadPlanCatalogEntry = {
id: thread.id,
proposedPlans: thread.proposedPlans,
};
threadPlanCatalogCache.set(
thread.id,
{
proposedPlans: thread.proposedPlans,
entry,
},
estimateThreadPlanCatalogEntrySize(thread),
);
return entry;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
const selector = useMemo(() => {
let previousThreads: Array<Thread | undefined> | null = null;
let previousEntries: ThreadPlanCatalogEntry[] = [];
const threadShellById = useStore((state) => state.threadShellById);
const proposedPlanIdsByThreadId = useStore((state) => state.proposedPlanIdsByThreadId);
const proposedPlanByThreadId = useStore((state) => state.proposedPlanByThreadId);
return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => {
const nextThreads = threadIds.map((threadId) =>
state.threads.find((thread) => thread.id === threadId),
);
const cachedThreads = previousThreads;
if (
cachedThreads &&
nextThreads.length === cachedThreads.length &&
nextThreads.every((thread, index) => thread === cachedThreads[index])
) {
return previousEntries;
}
return useMemo(
() =>
threadIds.flatMap((threadId) => {
if (!threadShellById[threadId]) {
return [];
}
previousThreads = nextThreads;
previousEntries = nextThreads.flatMap((thread) =>
thread ? [toThreadPlanCatalogEntry(thread)] : [],
);
return previousEntries;
};
}, [threadIds]);
const proposedPlans =
proposedPlanIdsByThreadId[threadId]?.flatMap((planId) => {
const plan = proposedPlanByThreadId[threadId]?.[planId];
return plan ? [plan] : [];
}) ?? [];
return useStore(selector);
return [{ id: threadId, proposedPlans }];
}),
[proposedPlanByThreadId, proposedPlanIdsByThreadId, threadIds, threadShellById],
);
}
function formatOutgoingPrompt(params: {
@@ -428,11 +377,17 @@ function PersistentThreadTerminalDrawer({
closeShortcutLabel,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const serverThread = useThreadById(threadId);
const serverThread = useStore(useMemo(() => createThreadSelector(threadId), [threadId]));
const draftThread = useComposerDraftStore(
(store) => store.draftThreadsByThreadId[threadId] ?? null,
);
const project = useProjectById(serverThread?.projectId ?? draftThread?.projectId);
const project = useStore((state) =>
serverThread?.projectId
? state.projectById[serverThread.projectId]
: draftThread?.projectId
? state.projectById[draftThread.projectId]
: undefined,
);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, threadId),
);
@@ -575,7 +530,7 @@ function PersistentThreadTerminalDrawer({
}
export default function ChatView({ threadId }: ChatViewProps) {
const serverThread = useThreadById(threadId);
const serverThread = useStore(useMemo(() => createThreadSelector(threadId), [threadId]));
const setStoreThreadError = useStore((store) => store.setError);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
@@ -750,14 +705,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const serverThreadIds = useStore((state) => state.threadIds);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadId[threadId] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const threads = useStore((state) => state.threads);
const serverThreadIds = useMemo(() => threads.map((thread) => thread.id), [threads]);
const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId);
const draftThreadIds = useMemo(
() => Object.keys(draftThreadsByThreadId) as ThreadId[],
@@ -818,7 +772,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
);
const fallbackDraftProject = useProjectById(draftThread?.projectId);
const fallbackDraftProject = useStore((state) =>
draftThread?.projectId ? state.projectById[draftThread.projectId] : undefined,
);
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
const localDraftThread = useMemo(
() =>
@@ -883,7 +839,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}, [activeThreadId, existingOpenTerminalThreadIds, terminalState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = useProjectById(activeThread?.projectId);
const activeProject = useStore((state) =>
activeThread?.projectId ? state.projectById[activeThread.projectId] : undefined,
);
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -1602,7 +1560,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
const nextError = sanitizeThreadErrorMessage(error);
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
if (useStore.getState().threadShellById[targetThreadId] !== undefined) {
setStoreThreadError(targetThreadId, nextError);
return;
}
+4 -3
View File
@@ -30,6 +30,7 @@ import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useStore } from "../store";
import { createThreadSelector } from "../storeSelectors";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
@@ -181,12 +182,12 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const diffOpen = diffSearch.diff === "1";
const activeThreadId = routeThreadId;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
const activeThread = useStore(
useMemo(() => createThreadSelector(activeThreadId), [activeThreadId]),
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore((store) =>
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
activeProjectId ? store.projectById[activeProjectId] : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitStatusQuery = useGitStatus(activeCwd ?? null);
@@ -141,10 +141,10 @@ vi.mock("~/store", () => ({
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
threads: [
{ id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
{ id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
],
threadShellById: {
[THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
[THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
},
}),
}));
@@ -212,7 +212,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[activeThreadId],
);
const activeServerThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
activeThreadId ? store.threadShellById[activeThreadId] : undefined,
);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
@@ -356,8 +356,22 @@ describe("Keybindings update toast", () => {
projectDraftThreadIdByProjectId: {},
});
useStore.setState({
projects: [],
threads: [],
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: false,
});
});
+12 -4
View File
@@ -128,7 +128,6 @@ import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "../rpc/serverState";
import { useSidebarThreadSummaryById } from "../storeSelectors";
import type { Project } from "../types";
const THREAD_PREVIEW_LIMIT = 6;
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
@@ -291,7 +290,7 @@ interface SidebarThreadRowProps {
}
function SidebarThreadRow(props: SidebarThreadRowProps) {
const thread = useSidebarThreadSummaryById(props.threadId);
const thread = useStore((state) => state.sidebarThreadSummaryById[props.threadId]);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[props.threadId]);
const runningTerminalIds = useTerminalStateStore(
(state) =>
@@ -679,8 +678,9 @@ function SortableProjectItem({
}
export default function Sidebar() {
const projects = useStore((store) => store.projects);
const sidebarThreadsById = useStore((store) => store.sidebarThreadsById);
const projectIds = useStore((store) => store.projectIds);
const projectById = useStore((store) => store.projectById);
const sidebarThreadsById = useStore((store) => store.sidebarThreadSummaryById);
const threadIdsByProjectId = useStore((store) => store.threadIdsByProjectId);
const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore(
useShallow((store) => ({
@@ -742,6 +742,14 @@ export default function Sidebar() {
const platform = navigator.platform;
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const projects = useMemo(
() =>
projectIds.flatMap((projectId) => {
const project = projectById[projectId];
return project ? [project] : [];
}),
[projectById, projectIds],
);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
@@ -95,7 +95,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
});
}, 10_000);
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
@@ -1479,12 +1479,21 @@ export function GeneralSettingsPanel() {
}
export function ArchivedThreadsPanel() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const projectIds = useStore((store) => store.projectIds);
const projectById = useStore((store) => store.projectById);
const threadIds = useStore((store) => store.threadIds);
const threadShellById = useStore((store) => store.threadShellById);
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const archivedGroups = useMemo(() => {
const projectById = new Map(projects.map((project) => [project.id, project] as const));
return [...projectById.values()]
const projects = projectIds.flatMap((projectId) => {
const project = projectById[projectId];
return project ? [project] : [];
});
const threads = threadIds.flatMap((threadId) => {
const thread = threadShellById[threadId];
return thread ? [thread] : [];
});
return projects
.map((project) => ({
project,
threads: threads
@@ -1496,7 +1505,7 @@ export function ArchivedThreadsPanel() {
}),
}))
.filter((group) => group.threads.length > 0);
}, [projects, threads]);
}, [projectById, projectIds, threadIds, threadShellById]);
const handleArchivedThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
+5 -3
View File
@@ -10,18 +10,20 @@ import {
import { newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { useStore } from "../store";
import { useThreadById } from "../storeSelectors";
import { createThreadSelector } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
const projectIds = useStore(useShallow((store) => store.projectIds));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const navigate = useNavigate();
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const activeThread = useThreadById(routeThreadId);
const activeThread = useStore(
useMemo(() => createThreadSelector(routeThreadId), [routeThreadId]),
);
const activeDraftThread = useComposerDraftStore((store) =>
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
);
+7 -6
View File
@@ -9,7 +9,7 @@ import { useHandleNewThread } from "./useHandleNewThread";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { newCommandId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { selectProjectById, selectThreadById, selectThreads, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { toastManager } from "../components/ui/toast";
@@ -35,7 +35,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = selectThreadById(threadId)(useStore.getState());
if (!thread) return;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
@@ -68,10 +68,11 @@ export function useThreadActions() {
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
if (!api) return;
const { projects, threads } = useStore.getState();
const thread = threads.find((entry) => entry.id === threadId);
const state = useStore.getState();
const threads = selectThreads(state);
const thread = selectThreadById(threadId)(state);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
const threadProject = selectProjectById(thread.projectId)(state);
const deletedIds = opts.deletedThreadIds;
const survivingThreads =
deletedIds && deletedIds.size > 0
@@ -179,7 +180,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = selectThreadById(threadId)(useStore.getState());
if (!thread) return;
if (appSettings.confirmThreadDelete) {
+8 -7
View File
@@ -1,7 +1,7 @@
import {
OrchestrationEvent,
type ServerLifecycleWelcomePayload,
type ThreadId,
ThreadId,
} from "@t3tools/contracts";
import {
Outlet,
@@ -38,7 +38,7 @@ import {
clearPromotedDraftThreads,
useComposerDraftStore,
} from "../composerDraftStore";
import { useStore } from "../store";
import { selectProjects, selectThreadById, selectThreads, useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
@@ -328,8 +328,9 @@ function EventRouter() {
let flushPendingDomainEventsScheduled = false;
const reconcileSnapshotDerivedState = () => {
const threads = useStore.getState().threads;
const projects = useStore.getState().projects;
const storeState = useStore.getState();
const threads = selectThreads(storeState);
const projects = selectProjects(storeState);
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
syncThreads(
threads.map((thread) => ({
@@ -392,14 +393,14 @@ function EventRouter() {
applyOrchestrationEvents(uiEvents);
if (needsProjectUiSync) {
const projects = useStore.getState().projects;
const projects = selectProjects(useStore.getState());
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
}
const needsThreadUiSync = nextEvents.some(
(event) => event.type === "thread.created" || event.type === "thread.deleted",
);
if (needsThreadUiSync) {
const threads = useStore.getState().threads;
const threads = selectThreads(useStore.getState());
syncThreads(
threads.map((thread) => ({
id: thread.id,
@@ -555,7 +556,7 @@ function EventRouter() {
},
);
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const thread = useStore.getState().threads.find((entry) => entry.id === event.threadId);
const thread = selectThreadById(ThreadId.makeUnsafe(event.threadId))(useStore.getState());
if (thread && thread.archivedAt !== null) {
return;
}
+1 -1
View File
@@ -167,7 +167,7 @@ function ChatThreadRouteView() {
select: (params) => ThreadId.makeUnsafe(params.threadId),
});
const search = Route.useSearch();
const threadExists = useStore((store) => store.threads.some((thread) => thread.id === threadId));
const threadExists = useStore((store) => store.threadShellById[threadId] !== undefined);
const draftThreadExists = useComposerDraftStore((store) =>
Object.hasOwn(store.draftThreadsByThreadId, threadId),
);
+242 -72
View File
@@ -14,6 +14,8 @@ import { describe, expect, it } from "vitest";
import {
applyOrchestrationEvent,
applyOrchestrationEvents,
selectProjects,
selectThreads,
syncServerReadModel,
type AppState,
} from "./store";
@@ -47,29 +49,125 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
}
function makeState(thread: Thread): AppState {
const projectId = ProjectId.makeUnsafe("project-1");
const project = {
id: projectId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
createdAt: "2026-02-13T00:00:00.000Z",
updatedAt: "2026-02-13T00:00:00.000Z",
scripts: [],
};
const threadIdsByProjectId: AppState["threadIdsByProjectId"] = {
[thread.projectId]: [thread.id],
};
return {
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
scripts: [],
},
],
threads: [thread],
sidebarThreadsById: {},
projectIds: [projectId],
projectById: {
[projectId]: project,
},
threadIds: [thread.id],
threadIdsByProjectId,
threadShellById: {
[thread.id]: {
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
error: thread.error,
createdAt: thread.createdAt,
archivedAt: thread.archivedAt,
updatedAt: thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
},
},
threadSessionById: {
[thread.id]: thread.session,
},
threadTurnStateById: {
[thread.id]: {
latestTurn: thread.latestTurn,
...(thread.pendingSourceProposedPlan
? { pendingSourceProposedPlan: thread.pendingSourceProposedPlan }
: {}),
},
},
messageIdsByThreadId: {
[thread.id]: thread.messages.map((message) => message.id),
},
messageByThreadId: {
[thread.id]: Object.fromEntries(
thread.messages.map((message) => [message.id, message] as const),
) as AppState["messageByThreadId"][ThreadId],
},
activityIdsByThreadId: {
[thread.id]: thread.activities.map((activity) => activity.id),
},
activityByThreadId: {
[thread.id]: Object.fromEntries(
thread.activities.map((activity) => [activity.id, activity] as const),
) as AppState["activityByThreadId"][ThreadId],
},
proposedPlanIdsByThreadId: {
[thread.id]: thread.proposedPlans.map((plan) => plan.id),
},
proposedPlanByThreadId: {
[thread.id]: Object.fromEntries(
thread.proposedPlans.map((plan) => [plan.id, plan] as const),
) as AppState["proposedPlanByThreadId"][ThreadId],
},
turnDiffIdsByThreadId: {
[thread.id]: thread.turnDiffSummaries.map((summary) => summary.turnId),
},
turnDiffSummaryByThreadId: {
[thread.id]: Object.fromEntries(
thread.turnDiffSummaries.map((summary) => [summary.turnId, summary] as const),
) as AppState["turnDiffSummaryByThreadId"][ThreadId],
},
sidebarThreadSummaryById: {},
bootstrapComplete: true,
};
}
function makeEmptyState(overrides: Partial<AppState> = {}): AppState {
return {
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: true,
...overrides,
};
}
function projectsOf(state: AppState) {
return selectProjects(state);
}
function threadsOf(state: AppState) {
return selectThreads(state);
}
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
@@ -191,7 +289,7 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.threads[0]?.modelSelection.model).toBe("claude-opus-4-6");
expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-opus-4-6");
});
it("resolves claude aliases when session provider is claudeAgent", () => {
@@ -216,7 +314,7 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.threads[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
});
it("preserves project and thread updatedAt timestamps from the read model", () => {
@@ -229,8 +327,8 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
expect(projectsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
expect(threadsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
});
it("maps archivedAt from the read model", () => {
@@ -245,16 +343,17 @@ describe("store read model sync", () => {
),
);
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
expect(threadsOf(next)[0]?.archivedAt).toBe(archivedAt);
});
it("replaces projects using snapshot order during recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState: AppState = {
projects: [
{
const initialState: AppState = makeEmptyState({
projectIds: [project2, project1],
projectById: {
[project2]: {
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
@@ -262,9 +361,11 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
scripts: [],
},
{
[project1]: {
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
@@ -272,14 +373,12 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
scripts: [],
},
],
threads: [],
sidebarThreadsById: {},
threadIdsByProjectId: {},
bootstrapComplete: true,
};
},
});
const readModel: OrchestrationReadModel = {
snapshotSequence: 2,
updatedAt: "2026-02-27T00:00:00.000Z",
@@ -305,7 +404,7 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
expect(projectsOf(next).map((project) => project.id)).toEqual([project1, project2, project3]);
});
});
@@ -354,9 +453,10 @@ describe("incremental orchestration updates", () => {
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const state: AppState = {
projects: [
{
const state: AppState = makeEmptyState({
projectIds: [originalProjectId],
projectById: {
[originalProjectId]: {
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
@@ -364,14 +464,12 @@ describe("incremental orchestration updates", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
scripts: [],
},
],
threads: [],
sidebarThreadsById: {},
threadIdsByProjectId: {},
bootstrapComplete: true,
};
},
});
const next = applyOrchestrationEvent(
state,
@@ -389,10 +487,13 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe(recreatedProjectId);
expect(next.projects[0]?.cwd).toBe("/tmp/project");
expect(next.projects[0]?.name).toBe("Project Recreated");
expect(projectsOf(next)).toHaveLength(1);
expect(projectsOf(next)[0]?.id).toBe(recreatedProjectId);
expect(projectsOf(next)[0]?.cwd).toBe("/tmp/project");
expect(projectsOf(next)[0]?.name).toBe("Project Recreated");
expect(next.projectIds).toEqual([recreatedProjectId]);
expect(next.projectById[originalProjectId]).toBeUndefined();
expect(next.projectById[recreatedProjectId]?.id).toBe(recreatedProjectId);
});
it("removes stale project index entries when thread.created recreates a thread under a new project", () => {
@@ -404,8 +505,10 @@ describe("incremental orchestration updates", () => {
projectId: originalProjectId,
});
const state: AppState = {
projects: [
{
...makeState(thread),
projectIds: [originalProjectId, recreatedProjectId],
projectById: {
[originalProjectId]: {
id: originalProjectId,
name: "Project 1",
cwd: "/tmp/project-1",
@@ -413,9 +516,11 @@ describe("incremental orchestration updates", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
scripts: [],
},
{
[recreatedProjectId]: {
id: recreatedProjectId,
name: "Project 2",
cwd: "/tmp/project-2",
@@ -423,15 +528,11 @@ describe("incremental orchestration updates", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
scripts: [],
},
],
threads: [thread],
sidebarThreadsById: {},
threadIdsByProjectId: {
[originalProjectId]: [threadId],
},
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
@@ -453,8 +554,8 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.projectId).toBe(recreatedProjectId);
expect(threadsOf(next)).toHaveLength(1);
expect(threadsOf(next)[0]?.projectId).toBe(recreatedProjectId);
expect(next.threadIdsByProjectId[originalProjectId]).toBeUndefined();
expect(next.threadIdsByProjectId[recreatedProjectId]).toEqual([threadId]);
});
@@ -477,7 +578,73 @@ describe("incremental orchestration updates", () => {
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
const state: AppState = {
...makeState(thread1),
threads: [thread1, thread2],
threadIds: [thread1.id, thread2.id],
threadShellById: {
...makeState(thread1).threadShellById,
[thread2.id]: {
id: thread2.id,
codexThreadId: thread2.codexThreadId,
projectId: thread2.projectId,
title: thread2.title,
modelSelection: thread2.modelSelection,
runtimeMode: thread2.runtimeMode,
interactionMode: thread2.interactionMode,
error: thread2.error,
createdAt: thread2.createdAt,
archivedAt: thread2.archivedAt,
updatedAt: thread2.updatedAt,
branch: thread2.branch,
worktreePath: thread2.worktreePath,
},
},
threadSessionById: {
...makeState(thread1).threadSessionById,
[thread2.id]: thread2.session,
},
threadTurnStateById: {
...makeState(thread1).threadTurnStateById,
[thread2.id]: {
latestTurn: thread2.latestTurn,
},
},
messageIdsByThreadId: {
...makeState(thread1).messageIdsByThreadId,
[thread2.id]: [],
},
messageByThreadId: {
...makeState(thread1).messageByThreadId,
[thread2.id]: {},
},
activityIdsByThreadId: {
...makeState(thread1).activityIdsByThreadId,
[thread2.id]: [],
},
activityByThreadId: {
...makeState(thread1).activityByThreadId,
[thread2.id]: {},
},
proposedPlanIdsByThreadId: {
...makeState(thread1).proposedPlanIdsByThreadId,
[thread2.id]: [],
},
proposedPlanByThreadId: {
...makeState(thread1).proposedPlanByThreadId,
[thread2.id]: {},
},
turnDiffIdsByThreadId: {
...makeState(thread1).turnDiffIdsByThreadId,
[thread2.id]: [],
},
turnDiffSummaryByThreadId: {
...makeState(thread1).turnDiffSummaryByThreadId,
[thread2.id]: {},
},
sidebarThreadSummaryById: {
...makeState(thread1).sidebarThreadSummaryById,
},
threadIdsByProjectId: {
[thread1.projectId]: [thread1.id, thread2.id],
},
};
const next = applyOrchestrationEvent(
@@ -494,9 +661,12 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
expect(next.threads[0]?.latestTurn?.state).toBe("running");
expect(next.threads[1]).toBe(thread2);
expect(threadsOf(next)[0]?.messages[0]?.text).toBe("hello world");
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("running");
expect(next.threadShellById[thread2.id]).toBe(state.threadShellById[thread2.id]);
expect(next.threadSessionById[thread2.id]).toBe(state.threadSessionById[thread2.id]);
expect(next.messageIdsByThreadId[thread2.id]).toBe(state.messageIdsByThreadId[thread2.id]);
expect(next.messageByThreadId[thread2.id]).toBe(state.messageByThreadId[thread2.id]);
});
it("applies replay batches in sequence and updates session state", () => {
@@ -545,9 +715,9 @@ describe("incremental orchestration updates", () => {
),
]);
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
expect(threadsOf(next)[0]?.session?.status).toBe("running");
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("completed");
expect(threadsOf(next)[0]?.messages).toHaveLength(1);
});
it("does not regress latestTurn when an older turn diff completes late", () => {
@@ -578,8 +748,8 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
expect(threadsOf(next)[0]?.turnDiffSummaries).toHaveLength(1);
expect(threadsOf(next)[0]?.latestTurn).toEqual(threadsOf(state)[0]?.latestTurn);
});
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
@@ -622,10 +792,10 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
expect(threadsOf(next)[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
expect(threadsOf(next)[0]?.latestTurn?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
});
@@ -731,15 +901,15 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
expect(threadsOf(next)[0]?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant-1",
]);
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
expect(threadsOf(next)[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(threadsOf(next)[0]?.activities.map((activity) => activity.id)).toEqual([
EventId.makeUnsafe("activity-1"),
]);
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
expect(threadsOf(next)[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
TurnId.makeUnsafe("turn-1"),
]);
});
@@ -789,7 +959,7 @@ describe("incremental orchestration updates", () => {
}),
);
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
expect(threadsOf(reverted)[0]?.pendingSourceProposedPlan).toBeUndefined();
const next = applyOrchestrationEvent(
reverted,
@@ -807,10 +977,10 @@ describe("incremental orchestration updates", () => {
}),
);
expect(next.threads[0]?.latestTurn).toMatchObject({
expect(threadsOf(next)[0]?.latestTurn).toMatchObject({
turnId: TurnId.makeUnsafe("turn-3"),
state: "running",
});
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
expect(threadsOf(next)[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
});
});
+654 -264
View File
File diff suppressed because it is too large. Load diff
+138 -18
View File
@@ -1,26 +1,146 @@
import { type ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { type MessageId, type ProjectId, type ThreadId, type TurnId } from "@t3tools/contracts";
import { type AppState } from "./store";
import {
selectProjectById,
selectSidebarThreadSummaryById,
selectThreadById,
useStore,
} from "./store";
import { type Project, type SidebarThreadSummary, type Thread } from "./types";
type ChatMessage,
type Project,
type ProposedPlan,
type SidebarThreadSummary,
type Thread,
type ThreadSession,
type ThreadTurnState,
type TurnDiffSummary,
} from "./types";
export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined {
const selector = useMemo(() => selectProjectById(projectId), [projectId]);
return useStore(selector);
const EMPTY_MESSAGES: ChatMessage[] = [];
const EMPTY_ACTIVITIES: Thread["activities"] = [];
const EMPTY_PROPOSED_PLANS: ProposedPlan[] = [];
const EMPTY_TURN_DIFF_SUMMARIES: TurnDiffSummary[] = [];
function collectByIds<TKey extends string, TValue>(
ids: readonly TKey[] | undefined,
byId: Record<TKey, TValue> | undefined,
): TValue[] {
if (!ids || ids.length === 0 || !byId) {
return [];
}
return ids.flatMap((id) => {
const value = byId[id];
return value ? [value] : [];
});
}
export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined {
const selector = useMemo(() => selectThreadById(threadId), [threadId]);
return useStore(selector);
export function createProjectSelector(
projectId: ProjectId | null | undefined,
): (state: AppState) => Project | undefined {
return (state) => (projectId ? state.projectById[projectId] : undefined);
}
export function useSidebarThreadSummaryById(
export function createSidebarThreadSummarySelector(
threadId: ThreadId | null | undefined,
): SidebarThreadSummary | undefined {
const selector = useMemo(() => selectSidebarThreadSummaryById(threadId), [threadId]);
return useStore(selector);
): (state: AppState) => SidebarThreadSummary | undefined {
return (state) => (threadId ? state.sidebarThreadSummaryById[threadId] : undefined);
}
export function createThreadSelector(
threadId: ThreadId | null | undefined,
): (state: AppState) => Thread | undefined {
let previousShell: AppState["threadShellById"][ThreadId] | undefined;
let previousSession: ThreadSession | null | undefined;
let previousTurnState: ThreadTurnState | undefined;
let previousMessageIds: MessageId[] | undefined;
let previousMessagesById: AppState["messageByThreadId"][ThreadId] | undefined;
let previousActivityIds: string[] | undefined;
let previousActivitiesById: AppState["activityByThreadId"][ThreadId] | undefined;
let previousProposedPlanIds: string[] | undefined;
let previousProposedPlansById: AppState["proposedPlanByThreadId"][ThreadId] | undefined;
let previousTurnDiffIds: TurnId[] | undefined;
let previousTurnDiffsById: AppState["turnDiffSummaryByThreadId"][ThreadId] | undefined;
let previousThread: Thread | undefined;
return (state) => {
if (!threadId) {
return undefined;
}
const shell = state.threadShellById[threadId];
if (!shell) {
return undefined;
}
const session = state.threadSessionById[threadId] ?? null;
const turnState = state.threadTurnStateById[threadId];
const messageIds = state.messageIdsByThreadId[threadId];
const messageById = state.messageByThreadId[threadId];
const activityIds = state.activityIdsByThreadId[threadId];
const activityById = state.activityByThreadId[threadId];
const proposedPlanIds = state.proposedPlanIdsByThreadId[threadId];
const proposedPlanById = state.proposedPlanByThreadId[threadId];
const turnDiffIds = state.turnDiffIdsByThreadId[threadId];
const turnDiffById = state.turnDiffSummaryByThreadId[threadId];
if (
previousThread &&
previousShell === shell &&
previousSession === session &&
previousTurnState === turnState &&
previousMessageIds === messageIds &&
previousMessagesById === messageById &&
previousActivityIds === activityIds &&
previousActivitiesById === activityById &&
previousProposedPlanIds === proposedPlanIds &&
previousProposedPlansById === proposedPlanById &&
previousTurnDiffIds === turnDiffIds &&
previousTurnDiffsById === turnDiffById
) {
return previousThread;
}
const nextThread: Thread = {
...shell,
session,
latestTurn: turnState?.latestTurn ?? null,
pendingSourceProposedPlan: turnState?.pendingSourceProposedPlan,
messages: collectByIds(messageIds, messageById) as Thread["messages"] extends ChatMessage[]
? ChatMessage[]
: never,
activities: collectByIds(activityIds, activityById) as Thread["activities"] extends Array<
infer _
>
? Thread["activities"]
: never,
proposedPlans: collectByIds(
proposedPlanIds,
proposedPlanById,
) as Thread["proposedPlans"] extends ProposedPlan[] ? ProposedPlan[] : never,
turnDiffSummaries: collectByIds(
turnDiffIds,
turnDiffById,
) as Thread["turnDiffSummaries"] extends TurnDiffSummary[] ? TurnDiffSummary[] : never,
};
previousShell = shell;
previousSession = session;
previousTurnState = turnState;
previousMessageIds = messageIds;
previousMessagesById = messageById;
previousActivityIds = activityIds;
previousActivitiesById = activityById;
previousProposedPlanIds = proposedPlanIds;
previousProposedPlansById = proposedPlanById;
previousTurnDiffIds = turnDiffIds;
previousTurnDiffsById = turnDiffById;
previousThread = {
...nextThread,
messages: nextThread.messages.length === 0 ? EMPTY_MESSAGES : nextThread.messages,
activities: nextThread.activities.length === 0 ? EMPTY_ACTIVITIES : nextThread.activities,
proposedPlans:
nextThread.proposedPlans.length === 0 ? EMPTY_PROPOSED_PLANS : nextThread.proposedPlans,
turnDiffSummaries:
nextThread.turnDiffSummaries.length === 0
? EMPTY_TURN_DIFF_SUMMARIES
: nextThread.turnDiffSummaries,
};
return previousThread;
};
}
+21
View File
@@ -111,6 +111,27 @@ export interface Thread {
activities: OrchestrationThreadActivity[];
}
export interface ThreadShell {
id: ThreadId;
codexThreadId: string | null;
projectId: ProjectId;
title: string;
modelSelection: ModelSelection;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
error: string | null;
createdAt: string;
archivedAt: string | null;
updatedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
}
export interface ThreadTurnState {
latestTurn: OrchestrationLatestTurn | null;
pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"];
}
export interface SidebarThreadSummary {
id: ThreadId;
projectId: ProjectId;