Prepare datamodel for multi-environment (#1765)

Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-09 02:05:20 +00:00
1 parent 72b7f90c50
commit b96308fc5a
121 files changed
+10195 -4958

No files matched your search

+38 -16
View File
@@ -1,11 +1,13 @@
import type { ThreadId } from "@t3tools/contracts";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { FolderIcon, GitForkIcon } from "lucide-react";
import { useCallback } from "react";
import { useCallback, useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { readEnvironmentApi } from "../environmentApi";
import { newCommandId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import {
EnvMode,
resolveDraftEnvModeAfterBranchChange,
@@ -20,7 +22,9 @@ const envModeItems = [
] as const;
interface BranchToolbarProps {
environmentId: EnvironmentId;
threadId: ThreadId;
draftId?: DraftId;
onEnvModeChange: (mode: EnvMode) => void;
envLocked: boolean;
onCheckoutPullRequestRequest?: (reference: string) => void;
@@ -28,21 +32,34 @@ interface BranchToolbarProps {
}
export default function BranchToolbar({
environmentId,
threadId,
draftId,
onEnvModeChange,
envLocked,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarProps) {
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 activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = useStore((store) =>
activeProjectId ? store.projectById[activeProjectId] : undefined,
const threadRef = useMemo(
() => scopeThreadRef(environmentId, threadId),
[environmentId, threadId],
);
const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
const serverThread = useStore(serverThreadSelector);
const serverSession = serverThread?.session ?? null;
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const activeProjectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
: draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const activeProjectSelector = useMemo(
() => createProjectSelectorByRef(activeProjectRef),
[activeProjectRef],
);
const activeProject = useStore(activeProjectSelector);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
@@ -56,8 +73,8 @@ export default function BranchToolbar({
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
if (!activeThreadId || !activeProject) return;
const api = readEnvironmentApi(environmentId);
// 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 (serverSession && worktreePath !== activeWorktreePath && api) {
@@ -88,20 +105,24 @@ export default function BranchToolbar({
currentWorktreePath: activeWorktreePath,
effectiveEnvMode,
});
setDraftThreadContext(threadId, {
setDraftThreadContext(draftId ?? threadRef, {
branch,
worktreePath,
envMode: nextDraftEnvMode,
projectRef: scopeProjectRef(environmentId, activeProject.id),
});
},
[
activeThreadId,
activeProject,
serverSession,
activeWorktreePath,
hasServerThread,
setThreadBranchAction,
setDraftThreadContext,
threadId,
draftId,
threadRef,
environmentId,
effectiveEnvMode,
],
);
@@ -156,6 +177,7 @@ export default function BranchToolbar({
)}
<BranchToolbarBranchSelector
environmentId={environmentId}
activeProjectCwd={activeProject.cwd}
activeThreadBranch={activeThreadBranch}
activeWorktreePath={activeWorktreePath}
@@ -1,4 +1,4 @@
import type { GitBranch } from "@t3tools/contracts";
import type { EnvironmentId, GitBranch } from "@t3tools/contracts";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
@@ -16,7 +16,7 @@ import {
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { readEnvironmentApi } from "../environmentApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
deriveLocalBranchNameFromRemoteRef,
@@ -39,6 +39,7 @@ import {
import { toastManager } from "./ui/toast";
interface BranchToolbarBranchSelectorProps {
environmentId: EnvironmentId;
activeProjectCwd: string;
activeThreadBranch: string | null;
activeWorktreePath: string | null;
@@ -70,6 +71,7 @@ function getBranchTriggerLabel(input: {
}
export function BranchToolbarBranchSelector({
environmentId,
activeProjectCwd,
activeThreadBranch,
activeWorktreePath,
@@ -85,16 +87,16 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useGitStatus(branchCwd);
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
useEffect(() => {
if (!branchCwd) return;
void queryClient.prefetchInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({ cwd: branchCwd, query: "" }),
gitBranchSearchInfiniteQueryOptions({ environmentId, cwd: branchCwd, query: "" }),
);
}, [branchCwd, queryClient]);
}, [branchCwd, environmentId, queryClient]);
const {
data: branchesSearchData,
@@ -104,6 +106,7 @@ export function BranchToolbarBranchSelector({
isPending: isBranchesSearchPending,
} = useInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({
environmentId,
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
}),
@@ -184,13 +187,13 @@ export function BranchToolbarBranchSelector({
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.branches(branchCwd) })
.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) })
.catch(() => undefined);
});
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || isBranchActionPending) return;
// In new-worktree mode, selecting a branch sets the base branch.
@@ -248,7 +251,7 @@ export function BranchToolbarBranchSelector({
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
@@ -302,10 +305,10 @@ export function BranchToolbarBranchSelector({
return;
}
void queryClient.invalidateQueries({
queryKey: gitQueryKeys.branches(branchCwd),
queryKey: gitQueryKeys.branches(environmentId, branchCwd),
});
},
[branchCwd, queryClient],
[branchCwd, environmentId, queryClient],
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
+2 -2
View File
@@ -22,7 +22,7 @@ import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
import { readLocalApi } from "../localApi";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
@@ -253,7 +253,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
const api = readLocalApi();
if (api) {
void openInPreferredEditor(api, targetPath);
} else {
+330 -229
View File
@@ -4,6 +4,7 @@ import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
EnvironmentId,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
@@ -12,11 +13,16 @@ import {
type ServerLifecycleWelcomePayload,
type ThreadId,
type TurnId,
type UserInputQuestion,
WS_METHODS,
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -24,19 +30,20 @@ import { page } from "vitest/browser";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
removeInlineTerminalContextPlaceholder,
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { __resetNativeApiForTests } from "../nativeApi";
import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { useStore } from "../store";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
@@ -49,8 +56,13 @@ vi.mock("../lib/gitStatusState", () => ({
}));
const THREAD_ID = "thread-browser-test" as ThreadId;
const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_ID = "project-1" as ProjectId;
const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID);
const THREAD_KEY = scopedThreadKey(THREAD_REF);
const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`;
const PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
@@ -129,6 +141,13 @@ function isoAt(offsetSeconds: number): string {
function createBaseServerConfig(): ServerConfig {
return {
environment: {
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -314,6 +333,13 @@ function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
snapshot,
serverConfig: createBaseServerConfig(),
welcome: {
environment: {
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
projectName: "Project",
bootstrapProjectId: PROJECT_ID,
@@ -396,6 +422,33 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest
};
}
function createThreadSessionSetEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
return {
sequence,
eventId: EventId.makeUnsafe(`event-thread-session-set-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: NOW_ISO,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.session-set",
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: `turn-${threadId}` as TurnId,
lastError: null,
updatedAt: NOW_ISO,
},
},
};
}
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event);
}
@@ -419,25 +472,72 @@ async function waitForWsClient(): Promise<void> {
);
}
function threadRefFor(threadId: ThreadId) {
return scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
}
function threadKeyFor(threadId: ThreadId): string {
return scopedThreadKey(threadRefFor(threadId));
}
function composerDraftFor(target: string) {
const { draftsByThreadKey } = useComposerDraftStore.getState();
return draftsByThreadKey[target] ?? draftsByThreadKey[threadKeyFor(target as ThreadId)];
}
function draftIdFromPath(pathname: string) {
const segments = pathname.split("/");
const draftId = segments[segments.length - 1];
if (!draftId) {
throw new Error(`Expected thread path, received "${pathname}".`);
}
return DraftId.makeUnsafe(draftId);
}
function draftThreadIdFor(draftId: ReturnType<typeof draftIdFromPath>): ThreadId {
const draftSession = useComposerDraftStore.getState().getDraftSession(draftId);
if (!draftSession) {
throw new Error(`Expected draft session for "${draftId}".`);
}
return draftSession.threadId;
}
function serverThreadPath(threadId: ThreadId): string {
return `/${LOCAL_ENVIRONMENT_ID}/${threadId}`;
}
async function waitForAppBootstrap(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
expect(useStore.getState().bootstrapComplete).toBe(true);
expect(selectBootstrapCompleteForActiveEnvironment(useStore.getState())).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
async function materializePromotedDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await waitForWsClient();
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
sendOrchestrationDomainEvent(
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
);
}
async function startPromotedServerThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
sendOrchestrationDomainEvent(
createThreadSessionSetEvent(threadId, fixture.snapshot.snapshotSequence + 1),
);
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await materializePromotedDraftThreadViaDomainEvent(threadId);
await startPromotedServerThreadViaDomainEvent(threadId);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
expect(useComposerDraftStore.getState().draftThreadsByThreadKey[threadKeyFor(threadId)]).toBe(
undefined,
);
},
{ timeout: 8_000, interval: 16 },
);
@@ -468,9 +568,12 @@ function withProjectScripts(
function setDraftThreadWithoutWorktree(): void {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -479,8 +582,8 @@ function setDraftThreadWithoutWorktree(): void {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
}
@@ -542,51 +645,12 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
};
}
function createSnapshotWithPendingUserInput(options?: {
questions?: ReadonlyArray<UserInputQuestion>;
}): OrchestrationReadModel {
function createSnapshotWithPendingUserInput(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-pending-input-target" as MessageId,
targetText: "question thread",
});
const questions =
options?.questions ??
([
{
id: "scope",
header: "Scope",
question: "What should this change cover?",
options: [
{
label: "Tight",
description: "Touch only the footer layout logic.",
},
{
label: "Broad",
description: "Also adjust the related composer controls.",
},
],
multiSelect: false,
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Conservative",
description: "Favor reliability and low-risk changes.",
},
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
multiSelect: false,
},
] satisfies ReadonlyArray<UserInputQuestion>);
return {
...snapshot,
threads: snapshot.threads.map((thread) =>
@@ -601,7 +665,38 @@ function createSnapshotWithPendingUserInput(options?: {
summary: "User input requested",
payload: {
requestId: "req-browser-user-input",
questions,
questions: [
{
id: "scope",
header: "Scope",
question: "What should this change cover?",
options: [
{
label: "Tight",
description: "Touch only the footer layout logic.",
},
{
label: "Broad",
description: "Also adjust the related composer controls.",
},
],
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Conservative",
description: "Favor reliability and low-risk changes.",
},
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
},
],
},
turnId: null,
sequence: 1,
@@ -1057,7 +1152,7 @@ async function mountChatView(options: {
const router = getRouter(
createMemoryHistory({
initialEntries: [`/${THREAD_ID}`],
initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`],
}),
);
@@ -1162,42 +1257,32 @@ describe("ChatView timeline estimator parity (full app)", () => {
return [];
},
});
await __resetNativeApiForTests();
await __resetLocalApiForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
wsRequests.length = 0;
customWsRpcResolver = null;
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
stickyActiveProvider: null,
});
useStore.setState({
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: false,
activeEnvironmentId: null,
environmentStateById: {},
});
useUiStateStore.setState({
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
});
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalStateByThreadKey: {},
terminalLaunchContextByThreadKey: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
@@ -1241,6 +1326,35 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
);
it("re-expands the bootstrap project using its scoped key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_KEY]: false,
},
projectOrder: [PROJECT_KEY],
threadLastVisitedAtById: {},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-bootstrap-project-expand" as MessageId,
targetText: "bootstrap project expand",
}),
});
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
const userText = "x".repeat(3_200);
const targetMessageId = "msg-user-target-resize" as MessageId;
@@ -1438,8 +1552,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
useTerminalStateStore.setState({
terminalStateByThreadId: {
[THREAD_ID]: {
terminalStateByThreadKey: {
[THREAD_KEY]: {
terminalOpen: true,
terminalHeight: 280,
terminalIds: ["default"],
@@ -1449,8 +1563,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
activeTerminalGroupId: "group-default",
},
},
terminalLaunchContextByThreadId: {
[THREAD_ID]: {
terminalLaunchContextByThreadKey: {
[THREAD_KEY]: {
cwd: "/repo/project",
worktreePath: null,
},
@@ -1696,9 +1810,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("runs project scripts from local draft threads at the project cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1707,8 +1824,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1772,9 +1889,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1783,8 +1903,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1835,9 +1955,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("lets the server own setup after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1846,8 +1969,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1957,12 +2080,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalStateByThreadKey: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1971,8 +2097,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1998,7 +2124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
@@ -2057,12 +2183,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("shows the send state once bootstrap dispatch is in flight", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalStateByThreadKey: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -2071,8 +2200,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -2101,7 +2230,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
@@ -2193,7 +2322,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const removedLabel = "Terminal 1 lines 1-2";
const addedLabel = "Terminal 2 lines 9-10";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-removed",
terminalLabel: "Terminal 1",
@@ -2220,21 +2349,21 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const store = useComposerDraftStore.getState();
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
const currentPrompt = store.draftsByThreadKey[THREAD_KEY]?.prompt ?? "";
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
store.setPrompt(THREAD_ID, nextPrompt.prompt);
store.removeTerminalContext(THREAD_ID, "ctx-removed");
store.setPrompt(THREAD_REF, nextPrompt.prompt);
store.removeTerminalContext(THREAD_REF, "ctx-removed");
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]).toBeUndefined();
expect(document.body.textContent).not.toContain(removedLabel);
},
{ timeout: 8_000, interval: 16 },
);
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-added",
terminalLabel: "Terminal 2",
@@ -2246,7 +2375,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
() => {
const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
const draft = useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY];
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
expect(document.body.textContent).toContain(addedLabel);
expect(document.body.textContent).not.toContain(removedLabel);
@@ -2261,7 +2390,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("disables send when the composer only contains an expired terminal pill", async () => {
const expiredLabel = "Terminal 1 line 4";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-expired-only",
terminalLabel: "Terminal 1",
@@ -2297,7 +2426,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("warns when sending text while omitting expired terminal pills", async () => {
const expiredLabel = "Terminal 1 line 4";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-expired-send-warning",
terminalLabel: "Terminal 1",
@@ -2308,7 +2437,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
useComposerDraftStore
.getState()
.setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
.setPrompt(THREAD_REF, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -2448,7 +2577,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
it("canonicalizes promoted draft threads to the server thread route", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
@@ -2470,21 +2599,34 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
const newThreadId = draftThreadIdFor(newDraftId);
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the steady-state promotion path: the server emits
// `thread.created`, the client materializes the thread incrementally,
// and the draft is cleared by live batch effects.
await promoteDraftThreadViaDomainEvent(newThreadId);
// `thread.created` should only mark the draft as promoting; it should
// not navigate away until the server thread has actual runtime state.
await materializePromotedDraftThreadViaDomainEvent(newThreadId);
expect(mounted.router.state.location.pathname).toBe(newThreadPath);
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
// The route should still be on the new thread — not redirected away.
// Once the server thread starts, the route should canonicalize.
await startPromotedServerThreadViaDomainEvent(newThreadId);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadKey[newDraftId]).toBe(
undefined,
);
},
{ timeout: 8_000, interval: 16 },
);
// The route should switch to the canonical server thread path.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after server thread promotion clears the draft.",
(path) => path === serverThreadPath(newThreadId),
"Promoted drafts should canonicalize to the server thread route.",
);
// The empty thread view and composer should still be visible.
@@ -2497,6 +2639,48 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("canonicalizes stale promoted draft routes to the server thread route", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-hydration-race-test" as MessageId,
targetText: "draft hydration race test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newDraftId = draftIdFromPath(newThreadPath);
const newThreadId = draftThreadIdFor(newDraftId);
await promoteDraftThreadViaDomainEvent(newThreadId);
await mounted.router.navigate({
to: "/draft/$draftId",
params: { draftId: newDraftId },
});
await waitForURL(
mounted.router,
(path) => path === serverThreadPath(newThreadId),
"Stale promoted draft routes should canonicalize to the server thread path.",
);
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("snapshots sticky codex settings into a new draft thread", async () => {
useComposerDraftStore.setState({
stickyModelSelectionByProvider: {
@@ -2531,9 +2715,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
expect(composerDraftFor(newDraftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2584,9 +2768,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new sticky claude draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
expect(composerDraftFor(newDraftId)).toMatchObject({
modelSelectionByProvider: {
claudeAgent: {
provider: "claudeAgent",
@@ -2624,9 +2808,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toBeUndefined();
expect(composerDraftFor(newDraftId)).toBe(undefined);
} finally {
await mounted.cleanup();
}
@@ -2666,9 +2850,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a sticky draft thread UUID.",
);
const threadId = threadPath.slice(1) as ThreadId;
const draftId = draftIdFromPath(threadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
expect(composerDraftFor(draftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2681,7 +2865,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
activeProvider: "codex",
});
useComposerDraftStore.getState().setModelSelection(threadId, {
useComposerDraftStore.getState().setModelSelection(draftId, {
provider: "codex",
model: "gpt-5.4",
options: {
@@ -2697,7 +2881,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => path === threadPath,
"New-thread should reuse the existing project draft thread.",
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
expect(composerDraftFor(draftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2804,7 +2988,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a promoted draft thread UUID.",
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
const promotedDraftId = draftIdFromPath(promotedThreadPath);
const promotedThreadId = draftThreadIdFor(promotedDraftId);
await promoteDraftThreadViaDomainEvent(promotedThreadId);
@@ -2925,70 +3110,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("does not trigger numeric option shortcuts while the composer is focused", async () => {
it("submits pending user input after the final option selection resolves the draft answers", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotWithPendingUserInput(),
});
try {
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
const event = new KeyboardEvent("keydown", {
key: "2",
bubbles: true,
cancelable: true,
});
composerEditor.dispatchEvent(event);
await waitForLayout();
expect(event.defaultPrevented).toBe(false);
expect(document.body.textContent).toContain("What should this change cover?");
expect(document.body.textContent).not.toContain(
"How aggressive should the imaginary plan be?",
);
await waitForButtonByText("Next question");
} finally {
await mounted.cleanup();
}
});
it("submits multi-select questionnaire answers as arrays", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
snapshot: createSnapshotWithPendingUserInput({
questions: [
{
id: "scope",
header: "Scope",
question: "Which areas should this change cover?",
options: [
{
label: "Server",
description: "Touch server orchestration.",
},
{
label: "Web",
description: "Touch the browser UI.",
},
],
multiSelect: true,
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
multiSelect: false,
},
],
}),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
@@ -3000,37 +3125,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const serverOption = await waitForButtonContainingText("Server");
serverOption.click();
await waitForLayout();
const firstOption = await waitForButtonContainingText("Tight");
firstOption.click();
expect(document.body.textContent).toContain("Which areas should this change cover?");
const webOption = await waitForButtonContainingText("Web");
webOption.click();
await waitForLayout();
expect(document.body.textContent).toContain("Which areas should this change cover?");
const nextButton = await waitForButtonByText("Next question");
expect(nextButton.disabled).toBe(false);
nextButton.click();
await vi.waitFor(
() => {
expect(document.body.textContent).toContain(
"How aggressive should the imaginary plan be?",
);
},
{ timeout: 8_000, interval: 16 },
);
const balancedOption = await waitForButtonContainingText("Balanced");
balancedOption.click();
const submitButton = await waitForButtonByText("Submit answers");
expect(submitButton.disabled).toBe(false);
submitButton.click();
const finalOption = await waitForButtonContainingText("Conservative");
finalOption.click();
await vi.waitFor(
() => {
@@ -3042,6 +3141,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
| {
_tag: string;
type?: string;
requestId?: string;
answers?: Record<string, unknown>;
}
| undefined;
@@ -3049,9 +3149,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "thread.user-input.respond",
requestId: "req-browser-user-input",
answers: {
scope: ["Server", "Web"],
risk: "Balanced",
scope: "Tight",
risk: "Conservative",
},
});
},
+57 -7
View File
@@ -1,6 +1,7 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { EnvironmentId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { type EnvironmentState, useStore } from "../store";
import { type Thread } from "../types";
import {
@@ -10,9 +11,12 @@ import {
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
shouldWriteThreadErrorToCurrentServerThread,
waitForStartedServerThread,
} from "./ChatView.logic";
const localEnvironmentId = EnvironmentId.makeUnsafe("environment-local");
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
const state = deriveComposerSendState({
@@ -170,6 +174,36 @@ describe("reconcileMountedTerminalThreadIds", () => {
});
});
describe("shouldWriteThreadErrorToCurrentServerThread", () => {
it("routes errors to the active server thread when route and target match", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const routeThreadRef = scopeThreadRef(localEnvironmentId, threadId);
expect(
shouldWriteThreadErrorToCurrentServerThread({
serverThread: {
environmentId: localEnvironmentId,
id: threadId,
},
routeThreadRef,
targetThreadId: threadId,
}),
).toBe(true);
});
it("does not route draft-thread errors into server-backed state", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
expect(
shouldWriteThreadErrorToCurrentServerThread({
serverThread: undefined,
routeThreadRef: scopeThreadRef(localEnvironmentId, threadId),
targetThreadId: threadId,
}),
).toBe(false);
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
@@ -181,6 +215,7 @@ const makeThread = (input?: {
} | null;
}): Thread => ({
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
environmentId: localEnvironmentId,
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
@@ -208,11 +243,12 @@ const makeThread = (input?: {
function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>) {
const projectId = ProjectId.makeUnsafe("project-1");
useStore.setState({
const environmentState: EnvironmentState = {
projectIds: [projectId],
projectById: {
[projectId]: {
id: projectId,
environmentId: localEnvironmentId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
@@ -233,6 +269,7 @@ function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>)
thread.id,
{
id: thread.id,
environmentId: thread.environmentId,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
@@ -301,6 +338,12 @@ function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>)
),
sidebarThreadSummaryById: {},
bootstrapComplete: true,
};
useStore.setState({
activeEnvironmentId: localEnvironmentId,
environmentStateById: {
[localEnvironmentId]: environmentState,
},
});
}
@@ -326,14 +369,16 @@ describe("waitForStartedServerThread", () => {
}),
]);
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
await expect(
waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId)),
).resolves.toBe(true);
});
it("waits for the thread to start via subscription updates", async () => {
const threadId = ThreadId.makeUnsafe("thread-wait");
setStoreThreads([makeThread({ id: threadId })]);
const promise = waitForStartedServerThread(threadId, 500);
const promise = waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500);
setStoreThreads([
makeThread({
@@ -376,7 +421,9 @@ describe("waitForStartedServerThread", () => {
return originalSubscribe(listener);
});
await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true);
await expect(
waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500),
).resolves.toBe(true);
});
it("returns false after the timeout when the thread never starts", async () => {
@@ -384,7 +431,7 @@ describe("waitForStartedServerThread", () => {
const threadId = ThreadId.makeUnsafe("thread-timeout");
setStoreThreads([makeThread({ id: threadId })]);
const promise = waitForStartedServerThread(threadId, 500);
const promise = waitForStartedServerThread(scopeThreadRef(localEnvironmentId, threadId), 500);
await vi.advanceTimersByTimeAsync(500);
@@ -414,6 +461,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
it("does not clear local dispatch before server state changes", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
environmentId: localEnvironmentId,
codexThreadId: null,
projectId,
title: "Thread",
@@ -450,6 +498,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
it("clears local dispatch when a new turn is already settled", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
environmentId: localEnvironmentId,
codexThreadId: null,
projectId,
title: "Thread",
@@ -495,6 +544,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
it("clears local dispatch when the session changes without an observed running phase", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
environmentId: localEnvironmentId,
codexThreadId: null,
projectId,
title: "Thread",
+36 -9
View File
@@ -1,9 +1,16 @@
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
import {
type EnvironmentId,
ProjectId,
type ModelSelection,
type ScopedThreadRef,
type ThreadId,
type TurnId,
} from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { selectThreadById, useStore } from "../store";
import { selectThreadByRef, useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -24,6 +31,7 @@ export function buildLocalDraftThread(
): Thread {
return {
id: threadId,
environmentId: draftThread.environmentId,
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
@@ -44,13 +52,32 @@ export function buildLocalDraftThread(
};
}
export function shouldWriteThreadErrorToCurrentServerThread(input: {
serverThread:
| {
environmentId: EnvironmentId;
id: ThreadId;
}
| null
| undefined;
routeThreadRef: ScopedThreadRef;
targetThreadId: ThreadId;
}): boolean {
return Boolean(
input.serverThread &&
input.targetThreadId === input.routeThreadRef.threadId &&
input.serverThread.environmentId === input.routeThreadRef.environmentId &&
input.serverThread.id === input.targetThreadId,
);
}
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<ThreadId>;
openThreadIds: ReadonlyArray<ThreadId>;
activeThreadId: ThreadId | null;
currentThreadIds: ReadonlyArray<string>;
openThreadIds: ReadonlyArray<string>;
activeThreadId: string | null;
activeThreadTerminalOpen: boolean;
maxHiddenThreadCount?: number;
}): ThreadId[] {
}): string[] {
const openThreadIdSet = new Set(input.openThreadIds);
const hiddenThreadIds = input.currentThreadIds.filter(
(threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
@@ -199,10 +226,10 @@ export function threadHasStarted(thread: Thread | null | undefined): boolean {
}
export async function waitForStartedServerThread(
threadId: ThreadId,
threadRef: ScopedThreadRef,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => selectThreadById(threadId)(useStore.getState());
const getThread = () => selectThreadByRef(useStore.getState(), threadRef);
const thread = getThread();
if (threadHasStarted(thread)) {
@@ -225,7 +252,7 @@ export async function waitForStartedServerThread(
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(selectThreadById(threadId)(state))) {
if (!threadHasStarted(selectThreadByRef(state, threadRef))) {
return;
}
finish(true);
File diff suppressed because it is too large. Load diff
+26 -15
View File
@@ -2,7 +2,8 @@ import { parsePatchFiles } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime";
import type { TurnId } from "@t3tools/contracts";
import {
ChevronLeftIcon,
ChevronRightIcon,
@@ -22,15 +23,16 @@ import { openInPreferredEditor } from "../editorPreferences";
import { useGitStatus } from "~/lib/gitStatusState";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { readLocalApi } from "../localApi";
import { resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useStore } from "../store";
import { createThreadSelector } from "../storeSelectors";
import { selectProjectByRef, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
@@ -175,22 +177,30 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const previousDiffOpenRef = useRef(false);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const routeThreadId = useParams({
const routeThreadRef = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
select: (params) => resolveThreadRouteRef(params),
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const diffOpen = diffSearch.diff === "1";
const activeThreadId = routeThreadId;
const activeThreadId = routeThreadRef?.threadId ?? null;
const activeThread = useStore(
useMemo(() => createThreadSelector(activeThreadId), [activeThreadId]),
useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore((store) =>
activeProjectId ? store.projectById[activeProjectId] : undefined,
activeThread && activeProjectId
? selectProjectByRef(store, {
environmentId: activeThread.environmentId,
projectId: activeProjectId,
})
: undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitStatusQuery = useGitStatus(activeCwd ?? null);
const gitStatusQuery = useGitStatus({
environmentId: activeThread?.environmentId ?? null,
cwd: activeCwd ?? null,
});
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -263,6 +273,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
}, [orderedTurnDiffSummaries, selectedTurn]);
const activeCheckpointDiffQuery = useQuery(
checkpointDiffQueryOptions({
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
@@ -322,7 +333,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const openDiffFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
const api = readLocalApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void openInPreferredEditor(api, targetPath).catch((error) => {
@@ -335,8 +346,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1", diffTurnId: turnId };
@@ -346,8 +357,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const selectWholeConversation = () => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1" };
@@ -1,3 +1,4 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -5,10 +6,24 @@ import { render } from "vitest-browser-react";
const THREAD_A = ThreadId.makeUnsafe("thread-a");
const THREAD_B = ThreadId.makeUnsafe("thread-b");
const ENVIRONMENT_ID = "environment-local" as never;
const GIT_CWD = "/repo/project";
const BRANCH_NAME = "feature/toast-scope";
function createDeferredPromise<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((nextResolve, nextReject) => {
resolve = nextResolve;
reject = nextReject;
});
return { promise, resolve, reject };
}
const {
activeRunStackedActionDeferredRef,
invalidateGitQueriesSpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
@@ -18,9 +33,10 @@ const {
toastPromiseSpy,
toastUpdateSpy,
} = vi.hoisted(() => ({
activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
toastCloseSpy: vi.fn(),
@@ -28,12 +44,8 @@ const {
toastUpdateSpy: vi.fn(),
}));
vi.mock("@tanstack/react-query", async () => {
const actual =
await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
vi.mock("@tanstack/react-query", () => {
return {
...actual,
useIsMutating: vi.fn(() => 0),
useMutation: vi.fn((options: { __kind?: string }) => {
if (options.__kind === "run-stacked-action") {
@@ -56,27 +68,7 @@ vi.mock("@tanstack/react-query", async () => {
isPending: false,
};
}),
useQuery: vi.fn((options: { queryKey?: string[] }) => {
if (options.queryKey?.[0] === "git-branches") {
return {
data: {
isRepo: true,
hasOriginRemote: true,
branches: [
{
name: BRANCH_NAME,
current: true,
isDefault: false,
worktreePath: null,
},
],
},
error: null,
};
}
return { data: null, error: null };
}),
useQuery: vi.fn(() => ({ data: null, error: null })),
useQueryClient: vi.fn(() => ({})),
};
});
@@ -123,27 +115,44 @@ vi.mock("~/lib/gitStatusState", () => ({
})),
}));
vi.mock("~/lib/utils", async () => {
const actual = await vi.importActual<typeof import("~/lib/utils")>("~/lib/utils");
return {
...actual,
newCommandId: vi.fn(() => "command-1"),
randomUUID: vi.fn(() => "action-1"),
};
});
vi.mock("~/nativeApi", () => ({
readNativeApi: vi.fn(() => null),
vi.mock("~/localApi", () => ({
readLocalApi: vi.fn(() => null),
}));
vi.mock("~/store", () => ({
selectEnvironmentState: (
state: { environmentStateById: Record<string, unknown> },
environmentId: string | null,
) => {
if (!environmentId) {
throw new Error("Missing environment id");
}
const environmentState = state.environmentStateById[environmentId];
if (!environmentState) {
throw new Error(`Unknown environment: ${environmentId}`);
}
return environmentState;
},
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
threadShellById: {
[THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
[THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
environmentStateById: {
[ENVIRONMENT_ID]: {
threadShellById: {
[THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
[THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
},
},
}),
}));
@@ -168,7 +177,10 @@ function Harness() {
<button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
Switch thread
</button>
<GitActionsControl gitCwd={GIT_CWD} activeThreadId={activeThreadId} />
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, activeThreadId)}
/>
</>
);
}
@@ -177,6 +189,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
document.body.innerHTML = "";
});
@@ -231,6 +244,9 @@ describe("GitActionsControl thread-scoped progress toast", () => {
}),
);
} finally {
activeRunStackedActionDeferredRef.current.reject(new Error("test cleanup"));
await Promise.resolve();
vi.useRealTimers();
await screen.unmount();
host.remove();
}
@@ -248,9 +264,15 @@ describe("GitActionsControl thread-scoped progress toast", () => {
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<GitActionsControl gitCwd={GIT_CWD} activeThreadId={THREAD_A} />, {
container: host,
});
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, THREAD_A)}
/>,
{
container: host,
},
);
try {
window.dispatchEvent(new Event("focus"));
@@ -264,11 +286,15 @@ describe("GitActionsControl thread-scoped progress toast", () => {
await vi.advanceTimersByTimeAsync(1);
expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
expect(refreshGitStatusSpy).toHaveBeenCalledWith(GIT_CWD);
expect(refreshGitStatusSpy).toHaveBeenCalledWith({
environmentId: ENVIRONMENT_ID,
cwd: GIT_CWD,
});
} finally {
if (originalVisibilityState) {
Object.defineProperty(document, "visibilityState", originalVisibilityState);
}
vi.useRealTimers();
await screen.unmount();
host.remove();
}
+42 -20
View File
@@ -1,9 +1,9 @@
import { type ScopedThreadRef } from "@t3tools/contracts";
import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
@@ -49,12 +49,14 @@ import {
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { useStore } from "~/store";
import { createThreadSelectorByRef } from "~/storeSelectors";
interface GitActionsControlProps {
gitCwd: string | null;
activeThreadId: ThreadId | null;
activeThreadRef: ScopedThreadRef | null;
}
interface PendingDefaultBranchAction {
@@ -206,14 +208,18 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
return <InfoIcon className={iconClassName} />;
}
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
export default function GitActionsControl({ gitCwd, activeThreadRef }: GitActionsControlProps) {
const activeThreadId = activeThreadRef?.threadId ?? null;
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const activeServerThread = useStore((store) =>
activeThreadId ? store.threadShellById[activeThreadId] : undefined,
const activeServerThreadSelector = useMemo(
() => createThreadSelectorByRef(activeThreadRef),
[activeThreadRef],
);
const activeServerThread = useStore(activeServerThreadSelector);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
@@ -246,7 +252,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
}
const worktreePath = activeServerThread.worktreePath;
const api = readNativeApi();
const api = activeEnvironmentId ? readEnvironmentApi(activeEnvironmentId) : undefined;
if (api) {
void api.orchestration
.dispatchCommand({
@@ -261,7 +267,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
setThreadBranch(activeThreadId, branch, worktreePath);
},
[activeServerThread, activeThreadId, setThreadBranch],
[activeEnvironmentId, activeServerThread, activeThreadId, setThreadBranch],
);
const syncThreadBranchAfterGitAction = useCallback(
@@ -276,7 +282,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useGitStatus(gitCwd);
const { data: gitStatus = null, error: gitStatusError } = useGitStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
});
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
@@ -287,19 +296,27 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const allSelected = excludedFiles.size === 0;
const noneSelected = selectedFiles.length === 0;
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
const initMutation = useMutation(
gitInitMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }),
);
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({
environmentId: activeEnvironmentId,
cwd: gitCwd,
queryClient,
}),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const pullMutation = useMutation(
gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }),
);
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
useIsMutating({
mutationKey: gitMutationKeys.runStackedAction(activeEnvironmentId, gitCwd),
}) > 0;
const isPullRunning =
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
useEffect(() => {
@@ -372,7 +389,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
void refreshGitStatus(gitCwd).catch(() => undefined);
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
() => undefined,
);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
};
const handleVisibilityChange = () => {
@@ -391,10 +410,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [gitCwd]);
}, [activeEnvironmentId, gitCwd]);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
const api = readLocalApi();
if (!api) {
toastManager.add({
type: "error",
@@ -412,7 +431,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
return;
}
void api.shell.openExternal(prUrl).catch((err) => {
void api.shell.openExternal(prUrl).catch((err: unknown) => {
toastManager.add({
type: "error",
title: "Unable to open PR link",
@@ -601,7 +620,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
toastActionProps = {
children: toastCta.label,
onClick: () => {
const api = readNativeApi();
const api = readLocalApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(toastCta.url);
@@ -760,7 +779,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const openChangedFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
const api = readLocalApi();
if (!api || !gitCwd) {
toastManager.add({
type: "error",
@@ -836,7 +855,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<Menu
onOpenChange={(open) => {
if (open) {
void refreshGitStatus(gitCwd).catch(() => undefined);
void refreshGitStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
}).catch(() => undefined);
}
}}
>
@@ -2,6 +2,7 @@ import "../index.css";
import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
ORCHESTRATION_WS_METHODS,
type MessageId,
type OrchestrationReadModel,
@@ -18,7 +19,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { __resetNativeApiForTests } from "../nativeApi";
import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
@@ -34,6 +35,7 @@ vi.mock("../lib/gitStatusState", () => ({
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
const PROJECT_ID = "project-1" as ProjectId;
const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
const NOW_ISO = "2026-03-04T12:00:00.000Z";
interface TestFixture {
@@ -49,6 +51,13 @@ const wsLink = ws.link(/ws(s)?:\/\/.*/);
function createBaseServerConfig(): ServerConfig {
return {
environment: {
environmentId: LOCAL_ENVIRONMENT_ID,
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -155,6 +164,13 @@ function buildFixture(): TestFixture {
snapshot: createMinimalSnapshot(),
serverConfig: createBaseServerConfig(),
welcome: {
environment: {
environmentId: LOCAL_ENVIRONMENT_ID,
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
projectName: "Project",
bootstrapProjectId: PROJECT_ID,
@@ -286,7 +302,9 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
host.style.overflow = "hidden";
document.body.append(host);
const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
const router = getRouter(
createMemoryHistory({ initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`] }),
);
const screen = await render(
<AppAtomRegistryProvider>
@@ -347,32 +365,17 @@ describe("Keybindings update toast", () => {
return [];
},
});
await __resetNativeApiForTests();
await __resetLocalApiForTests();
localStorage.clear();
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
useStore.setState({
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: false,
activeEnvironmentId: null,
environmentStateById: {},
});
});
+6 -3
View File
@@ -1,4 +1,5 @@
import { memo, useState, useCallback } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
@@ -24,7 +25,7 @@ import {
stripDisplayedPlanMarkdown,
} from "../proposedPlan";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { readNativeApi } from "~/nativeApi";
import { readEnvironmentApi } from "~/environmentApi";
import { toastManager } from "./ui/toast";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
@@ -53,6 +54,7 @@ function stepStatusIcon(status: string): React.ReactNode {
interface PlanSidebarProps {
activePlan: ActivePlanState | null;
activeProposedPlan: LatestProposedPlanState | null;
environmentId: EnvironmentId;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
timestampFormat: TimestampFormat;
@@ -62,6 +64,7 @@ interface PlanSidebarProps {
const PlanSidebar = memo(function PlanSidebar({
activePlan,
activeProposedPlan,
environmentId,
markdownCwd,
workspaceRoot,
timestampFormat,
@@ -87,7 +90,7 @@ const PlanSidebar = memo(function PlanSidebar({
}, [planMarkdown]);
const handleSaveToWorkspace = useCallback(() => {
const api = readNativeApi();
const api = readEnvironmentApi(environmentId);
if (!api || !workspaceRoot || !planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
setIsSavingToWorkspace(true);
@@ -115,7 +118,7 @@ const PlanSidebar = memo(function PlanSidebar({
() => setIsSavingToWorkspace(false),
() => setIsSavingToWorkspace(false),
);
}, [planMarkdown, workspaceRoot]);
}, [environmentId, planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
@@ -1,4 +1,4 @@
import type { GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts";
import type { EnvironmentId, GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,6 +24,7 @@ import { Spinner } from "./ui/spinner";
interface PullRequestThreadDialogProps {
open: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
cwd: string | null;
initialReference: string | null;
@@ -33,6 +34,7 @@ interface PullRequestThreadDialogProps {
export function PullRequestThreadDialog({
open,
environmentId,
threadId,
cwd,
initialReference,
@@ -72,6 +74,7 @@ export function PullRequestThreadDialog({
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
const resolvePullRequestQuery = useQuery(
gitResolvePullRequestQueryOptions({
environmentId,
cwd,
reference: open ? parsedDebouncedReference : null,
}),
@@ -83,13 +86,14 @@ export function PullRequestThreadDialog({
const cached = queryClient.getQueryData<GitResolvePullRequestResult>([
"git",
"pull-request",
environmentId,
cwd,
parsedReference,
]);
return cached?.pullRequest ?? null;
}, [cwd, parsedReference, queryClient]);
}, [cwd, environmentId, parsedReference, queryClient]);
const preparePullRequestThreadMutation = useMutation(
gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }),
gitPreparePullRequestThreadMutationOptions({ environmentId, cwd, queryClient }),
);
const liveResolvedPullRequest =
@@ -20,7 +20,7 @@ import {
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -28,6 +28,8 @@ import {
type Thread,
} from "../types";
const localEnvironmentId = EnvironmentId.makeUnsafe("environment-local");
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
@@ -625,6 +627,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
const { defaultModelSelection, ...rest } = overrides;
return {
id: ProjectId.makeUnsafe("project-1"),
environmentId: localEnvironmentId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
@@ -642,6 +645,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: ThreadId.makeUnsafe("thread-1"),
environmentId: localEnvironmentId,
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,247 @@
import "../index.css";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const {
terminalConstructorSpy,
terminalDisposeSpy,
fitAddonFitSpy,
fitAddonLoadSpy,
environmentApiById,
readEnvironmentApiMock,
readLocalApiMock,
} = vi.hoisted(() => ({
terminalConstructorSpy: vi.fn(),
terminalDisposeSpy: vi.fn(),
fitAddonFitSpy: vi.fn(),
fitAddonLoadSpy: vi.fn(),
environmentApiById: new Map<string, { terminal: { open: ReturnType<typeof vi.fn> } }>(),
readEnvironmentApiMock: vi.fn((environmentId: string) => environmentApiById.get(environmentId)),
readLocalApiMock: vi.fn<
() =>
| {
contextMenu: { show: ReturnType<typeof vi.fn> };
shell: { openExternal: ReturnType<typeof vi.fn> };
}
| undefined
>(() => ({
contextMenu: { show: vi.fn(async () => null) },
shell: { openExternal: vi.fn(async () => undefined) },
})),
}));
vi.mock("@xterm/addon-fit", () => ({
FitAddon: class MockFitAddon {
fit = fitAddonFitSpy;
},
}));
vi.mock("@xterm/xterm", () => ({
Terminal: class MockTerminal {
cols = 80;
rows = 24;
options: { theme?: unknown } = {};
buffer = {
active: {
viewportY: 0,
baseY: 0,
getLine: vi.fn(() => null),
},
};
constructor(options: unknown) {
terminalConstructorSpy(options);
}
loadAddon(addon: unknown) {
fitAddonLoadSpy(addon);
}
open() {}
write() {}
clear() {}
clearSelection() {}
focus() {}
refresh() {}
scrollToBottom() {}
hasSelection() {
return false;
}
getSelection() {
return "";
}
getSelectionPosition() {
return null;
}
attachCustomKeyEventHandler() {
return true;
}
registerLinkProvider() {
return { dispose: vi.fn() };
}
onData() {
return { dispose: vi.fn() };
}
onSelectionChange() {
return { dispose: vi.fn() };
}
dispose() {
terminalDisposeSpy();
}
},
}));
vi.mock("~/environmentApi", () => ({
readEnvironmentApi: readEnvironmentApiMock,
}));
vi.mock("~/localApi", () => ({
readLocalApi: readLocalApiMock,
}));
import { TerminalViewport } from "./ThreadTerminalDrawer";
const THREAD_ID = ThreadId.makeUnsafe("thread-terminal-browser");
function createEnvironmentApi() {
return {
terminal: {
open: vi.fn(async () => ({
threadId: THREAD_ID,
terminalId: "default",
cwd: "/repo/project",
worktreePath: null,
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-04-07T00:00:00.000Z",
})),
write: vi.fn(async () => undefined),
resize: vi.fn(async () => undefined),
},
};
}
async function mountTerminalViewport(props: { threadRef: ReturnType<typeof scopeThreadRef> }) {
const host = document.createElement("div");
host.style.width = "800px";
host.style.height = "400px";
document.body.append(host);
const screen = await render(
<TerminalViewport
threadRef={props.threadRef}
threadId={THREAD_ID}
terminalId="default"
terminalLabel="Terminal"
cwd="/repo/project"
onSessionExited={() => undefined}
onAddTerminalContext={() => undefined}
focusRequestId={0}
autoFocus={false}
resizeEpoch={0}
drawerHeight={320}
/>,
{ container: host },
);
return {
rerender: async (nextProps: { threadRef: ReturnType<typeof scopeThreadRef> }) => {
await screen.rerender(
<TerminalViewport
threadRef={nextProps.threadRef}
threadId={THREAD_ID}
terminalId="default"
terminalLabel="Terminal"
cwd="/repo/project"
onSessionExited={() => undefined}
onAddTerminalContext={() => undefined}
focusRequestId={0}
autoFocus={false}
resizeEpoch={0}
drawerHeight={320}
/>,
);
},
cleanup: async () => {
await screen.unmount();
host.remove();
},
};
}
describe("TerminalViewport", () => {
afterEach(() => {
environmentApiById.clear();
readEnvironmentApiMock.mockClear();
readLocalApiMock.mockClear();
terminalConstructorSpy.mockClear();
terminalDisposeSpy.mockClear();
fitAddonFitSpy.mockClear();
fitAddonLoadSpy.mockClear();
});
it("does not create a terminal when APIs are unavailable", async () => {
readEnvironmentApiMock.mockReturnValueOnce(undefined);
readLocalApiMock.mockReturnValueOnce(undefined);
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
});
try {
await vi.waitFor(() => {
expect(terminalConstructorSpy).not.toHaveBeenCalled();
});
} finally {
await mounted.cleanup();
}
});
it("reopens the terminal when the scoped thread reference changes", async () => {
const environmentA = createEnvironmentApi();
const environmentB = createEnvironmentApi();
environmentApiById.set("environment-a", environmentA);
environmentApiById.set("environment-b", environmentB);
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
});
try {
await vi.waitFor(() => {
expect(environmentA.terminal.open).toHaveBeenCalledTimes(1);
});
await mounted.rerender({
threadRef: scopeThreadRef("environment-b" as never, THREAD_ID),
});
await vi.waitFor(() => {
expect(environmentB.terminal.open).toHaveBeenCalledTimes(1);
});
expect(terminalDisposeSpy).toHaveBeenCalledTimes(1);
} finally {
await mounted.cleanup();
}
});
});
@@ -1,6 +1,7 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import {
type ScopedThreadRef,
type TerminalEvent,
type TerminalSessionSnapshot,
type ThreadId,
@@ -31,7 +32,8 @@ import {
MAX_TERMINALS_PER_GROUP,
type ThreadTerminalGroup,
} from "../types";
import { readNativeApi } from "~/nativeApi";
import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
const MIN_DRAWER_HEIGHT = 180;
@@ -208,6 +210,7 @@ export function shouldHandleTerminalSelectionMouseUp(
}
interface TerminalViewportProps {
threadRef: ScopedThreadRef;
threadId: ThreadId;
terminalId: string;
terminalLabel: string;
@@ -222,7 +225,8 @@ interface TerminalViewportProps {
drawerHeight: number;
}
function TerminalViewport({
export function TerminalViewport({
threadRef,
threadId,
terminalId,
terminalLabel,
@@ -260,6 +264,9 @@ function TerminalViewport({
if (!mount) return;
let disposed = false;
const api = readEnvironmentApi(threadRef.environmentId);
const localApi = readLocalApi();
if (!api || !localApi) return;
const fitAddon = new FitAddon();
const terminal = new Terminal({
@@ -277,9 +284,6 @@ function TerminalViewport({
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const api = readNativeApi();
if (!api) return;
const clearSelectionAction = () => {
selectionActionRequestIdRef.current += 1;
if (selectionActionTimerRef.current !== null) {
@@ -340,7 +344,7 @@ function TerminalViewport({
const requestId = ++selectionActionRequestIdRef.current;
selectionActionOpenRef.current = true;
try {
const clicked = await api.contextMenu.show(
const clicked = await localApi.contextMenu.show(
[{ id: "add-to-chat", label: "Add to chat" }],
nextAction.position,
);
@@ -416,7 +420,7 @@ function TerminalViewport({
if (!latestTerminal) return;
if (match.kind === "url") {
void api.shell.openExternal(match.text).catch((error) => {
void localApi.shell.openExternal(match.text).catch((error: unknown) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open link",
@@ -426,7 +430,7 @@ function TerminalViewport({
}
const target = resolvePathLinkTarget(match.text, cwd);
void openInPreferredEditor(api, target).catch((error) => {
void openInPreferredEditor(localApi, target).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
@@ -573,12 +577,12 @@ function TerminalViewport({
const previousLastEntryId =
selectTerminalEventEntries(
previousState.terminalEventEntriesByKey,
threadId,
threadRef,
terminalId,
).at(-1)?.id ?? 0;
const nextEntries = selectTerminalEventEntries(
state.terminalEventEntriesByKey,
threadId,
threadRef,
terminalId,
);
const nextLastEntryId = nextEntries.at(-1)?.id ?? 0;
@@ -608,7 +612,7 @@ function TerminalViewport({
writeTerminalSnapshot(activeTerminal, snapshot);
const bufferedEntries = selectTerminalEventEntries(
useTerminalStateStore.getState().terminalEventEntriesByKey,
threadId,
threadRef,
terminalId,
);
const replayEntries = selectTerminalEventEntriesAfterSnapshot(
@@ -677,7 +681,7 @@ function TerminalViewport({
// autoFocus is intentionally omitted;
// it is only read at mount time and must not trigger terminal teardown/recreation.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cwd, runtimeEnv, terminalId, threadId]);
}, [cwd, runtimeEnv, terminalId, threadId, threadRef]);
useEffect(() => {
if (!autoFocus) return;
@@ -692,7 +696,7 @@ function TerminalViewport({
}, [autoFocus, focusRequestId]);
useEffect(() => {
const api = readNativeApi();
const api = readEnvironmentApi(threadRef.environmentId);
const terminal = terminalRef.current;
const fitAddon = fitAddonRef.current;
if (!api || !terminal || !fitAddon) return;
@@ -714,13 +718,14 @@ function TerminalViewport({
return () => {
window.cancelAnimationFrame(frame);
};
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
}, [drawerHeight, resizeEpoch, terminalId, threadId, threadRef]);
return (
<div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
);
}
interface ThreadTerminalDrawerProps {
threadRef: ScopedThreadRef;
threadId: ThreadId;
cwd: string;
worktreePath?: string | null;
@@ -773,6 +778,7 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
}
export default function ThreadTerminalDrawer({
threadRef,
threadId,
cwd,
worktreePath,
@@ -1098,6 +1104,7 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
@@ -1119,6 +1126,7 @@ export default function ThreadTerminalDrawer({
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
+10 -1
View File
@@ -1,9 +1,11 @@
import {
type EnvironmentId,
type EditorId,
type ProjectScript,
type ResolvedKeybindingsConfig,
type ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { memo } from "react";
import GitActionsControl from "../GitActionsControl";
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
@@ -15,6 +17,7 @@ import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
activeThreadId: ThreadId;
activeThreadTitle: string;
activeProjectName: string | undefined;
@@ -39,6 +42,7 @@ interface ChatHeaderProps {
}
export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeThreadId,
activeThreadTitle,
activeProjectName,
@@ -101,7 +105,12 @@ export const ChatHeader = memo(function ChatHeader({
openInCwd={openInCwd}
/>
)}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
{activeProjectName && (
<GitActionsControl
gitCwd={gitCwd}
activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
/>
)}
<Tooltip>
<TooltipTrigger
render={
@@ -1,4 +1,10 @@
import { DEFAULT_MODEL_BY_PROVIDER, ModelSelection, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_MODEL_BY_PROVIDER,
EnvironmentId,
ModelSelection,
ThreadId,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import "../../index.css";
import { page } from "vitest/browser";
@@ -9,35 +15,37 @@ import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
import { TraitsMenuContent } from "./TraitsPicker";
import { useComposerDraftStore } from "../../composerDraftStore";
const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) {
const threadId = ThreadId.makeUnsafe("thread-compact-menu");
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
const threadKey = scopedThreadKey(threadRef);
const provider = props?.modelSelection?.provider ?? "claudeAgent";
const draftsByThreadId = {} as ReturnType<
typeof useComposerDraftStore.getState
>["draftsByThreadId"];
const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];
draftsByThreadId[threadId] = {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
[provider]: {
provider,
model,
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
useComposerDraftStore.setState({
draftsByThreadKey: {
[threadKey]: {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
[provider]: {
provider,
model,
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
},
},
activeProvider: provider,
runtimeMode: null,
interactionMode: null,
},
},
activeProvider: provider,
runtimeMode: null,
interactionMode: null,
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
@@ -121,7 +129,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
<TraitsMenuContent
provider={provider}
models={models}
threadId={threadId}
threadRef={threadRef}
model={model}
prompt={props?.prompt ?? ""}
modelOptions={providerOptions}
@@ -150,9 +158,9 @@ describe("CompactComposerControlsMenu", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
@@ -1,5 +1,5 @@
import { type ApprovalRequestId } from "@t3tools/contracts";
import { memo, useCallback, useEffect, useRef } from "react";
import { memo, useEffect, useEffectEvent, useRef } from "react";
import { type PendingUserInput } from "../../session-logic";
import {
derivePendingUserInputProgress,
@@ -60,6 +60,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
const onAdvanceRef = useRef(onAdvance);
useEffect(() => {
onAdvanceRef.current = onAdvance;
}, [onAdvance]);
// Clear auto-advance timer on unmount
useEffect(() => {
@@ -70,22 +75,19 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
}, []);
const handleOptionSelection = useCallback(
(questionId: string, optionLabel: string) => {
onToggleOption(questionId, optionLabel);
if (activeQuestion?.multiSelect) {
return;
}
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvance();
}, 200);
},
[activeQuestion?.multiSelect, onAdvance, onToggleOption],
);
const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
onToggleOption(questionId, optionLabel);
if (activeQuestion?.multiSelect) {
return;
}
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvanceRef.current();
}, 200);
});
// Keyboard shortcut: number keys 1-9 select corresponding options when focus is
// outside editable fields. Multi-select prompts toggle options in place; single-
@@ -112,7 +114,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [activeQuestion, handleOptionSelection, isResponding]);
}, [activeQuestion, isResponding]);
if (!activeQuestion) {
return null;
@@ -42,6 +42,8 @@ beforeAll(() => {
});
});
const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
describe("MessagesTimeline", () => {
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
@@ -85,6 +87,7 @@ describe("MessagesTimeline", () => {
onRevertUserMessage={() => {}}
isRevertingCheckpoint={false}
onImageExpand={() => {}}
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
markdownCwd={undefined}
resolvedTheme="light"
timestampFormat="locale"
@@ -130,6 +133,7 @@ describe("MessagesTimeline", () => {
onRevertUserMessage={() => {}}
isRevertingCheckpoint={false}
onImageExpand={() => {}}
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
markdownCwd={undefined}
resolvedTheme="light"
timestampFormat="locale"
@@ -1,4 +1,4 @@
import { type MessageId, type TurnId } from "@t3tools/contracts";
import { type EnvironmentId, type MessageId, type TurnId } from "@t3tools/contracts";
import {
memo,
useCallback,
@@ -82,6 +82,7 @@ interface MessagesTimelineProps {
onRevertUserMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
activeThreadEnvironmentId: EnvironmentId;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
@@ -117,6 +118,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
isRevertingCheckpoint,
onImageExpand,
activeThreadEnvironmentId,
markdownCwd,
resolvedTheme,
timestampFormat,
@@ -531,6 +533,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div className="min-w-0 px-1 py-0.5">
<ProposedPlanCard
planMarkdown={row.proposedPlan.planMarkdown}
environmentId={activeThreadEnvironmentId}
cwd={markdownCwd}
workspaceRoot={workspaceRoot}
/>
@@ -19,6 +19,7 @@ const DEFAULT_VIEWPORT = {
height: 1_100,
};
const MARKDOWN_CWD = "/repo/project";
const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
interface RowMeasurement {
actualHeightPx: number;
@@ -31,7 +32,10 @@ interface RowMeasurement {
interface VirtualizationScenario {
name: string;
targetRowId: string;
props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
props: Omit<
ComponentProps<typeof MessagesTimeline>,
"scrollContainer" | "activeThreadEnvironmentId"
>;
maxEstimateDeltaPx: number;
}
@@ -48,7 +52,10 @@ interface VirtualizerSnapshot {
}
function MessagesTimelineBrowserHarness(
props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">,
props: Omit<
ComponentProps<typeof MessagesTimeline>,
"scrollContainer" | "activeThreadEnvironmentId"
>,
) {
const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>(
@@ -73,6 +80,7 @@ function MessagesTimelineBrowserHarness(
>
<MessagesTimeline
{...props}
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
scrollContainer={scrollContainer}
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={handleToggleWorkGroup}
@@ -143,7 +151,7 @@ function createBaseTimelineProps(input: {
completionDividerBeforeEntryId?: string | null;
turnDiffSummaryByAssistantMessageId?: Map<MessageId, TurnDiffSummary>;
onVirtualizerSnapshot?: ComponentProps<typeof MessagesTimeline>["onVirtualizerSnapshot"];
}): Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer"> {
}): Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer" | "activeThreadEnvironmentId"> {
return {
hasMessages: true,
isWorking: false,
@@ -481,7 +489,10 @@ async function waitForElement<T extends Element>(
async function measureTimelineRow(input: {
host: HTMLElement;
props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
props: Omit<
ComponentProps<typeof MessagesTimeline>,
"scrollContainer" | "activeThreadEnvironmentId"
>;
targetRowId: string;
}): Promise<RowMeasurement> {
const scrollContainer = await waitForElement(
@@ -550,7 +561,10 @@ async function measureTimelineRow(input: {
}
async function mountMessagesTimeline(input: {
props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
props: Omit<
ComponentProps<typeof MessagesTimeline>,
"scrollContainer" | "activeThreadEnvironmentId"
>;
viewport?: { width: number; height: number };
}) {
const viewport = input.viewport ?? DEFAULT_VIEWPORT;
@@ -576,7 +590,10 @@ async function mountMessagesTimeline(input: {
return {
host,
rerender: async (
nextProps: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">,
nextProps: Omit<
ComponentProps<typeof MessagesTimeline>,
"scrollContainer" | "activeThreadEnvironmentId"
>,
) => {
await screen.rerender(<MessagesTimelineBrowserHarness {...nextProps} />);
await waitForLayout();
@@ -18,7 +18,7 @@ import {
Zed,
} from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { readLocalApi } from "~/localApi";
const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
@@ -93,7 +93,7 @@ export const OpenInPicker = memo(function OpenInPicker({
const openInEditor = useCallback(
(editorId: EditorId | null) => {
const api = readNativeApi();
const api = readLocalApi();
if (!api || !openInCwd) return;
const editor = editorId ?? preferredEditor;
if (!editor) return;
@@ -110,7 +110,7 @@ export const OpenInPicker = memo(function OpenInPicker({
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
const api = readNativeApi();
const api = readLocalApi();
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !openInCwd) return;
if (!preferredEditor) return;
@@ -1,4 +1,5 @@
import { memo, useState, useId } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import {
buildCollapsedProposedPlanPreviewMarkdown,
buildProposedPlanMarkdownFilename,
@@ -24,15 +25,17 @@ import {
DialogTitle,
} from "../ui/dialog";
import { toastManager } from "../ui/toast";
import { readNativeApi } from "~/nativeApi";
import { readEnvironmentApi } from "~/environmentApi";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
export const ProposedPlanCard = memo(function ProposedPlanCard({
planMarkdown,
environmentId,
cwd,
workspaceRoot,
}: {
planMarkdown: string;
environmentId: EnvironmentId;
cwd: string | undefined;
workspaceRoot: string | undefined;
}) {
@@ -82,7 +85,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
};
const handleSaveToWorkspace = () => {
const api = readNativeApi();
const api = readEnvironmentApi(environmentId);
const relativePath = savePath.trim();
if (!api || !workspaceRoot) {
return;
@@ -6,10 +6,11 @@ import {
CodexModelOptions,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
ProjectId,
EnvironmentId,
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { page } from "vitest/browser";
import { useCallback } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -27,7 +28,13 @@ import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
// ── Claude TraitsPicker tests ─────────────────────────────────────────
const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
const CLAUDE_THREAD_ID = ThreadId.makeUnsafe("thread-claude-traits");
const CLAUDE_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CLAUDE_THREAD_ID);
const CLAUDE_THREAD_KEY = scopedThreadKey(CLAUDE_THREAD_REF);
const CODEX_THREAD_ID = ThreadId.makeUnsafe("thread-codex-traits");
const CODEX_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CODEX_THREAD_ID);
const CODEX_THREAD_KEY = scopedThreadKey(CODEX_THREAD_REF);
const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
{
provider: "codex",
@@ -120,10 +127,10 @@ function ClaudeTraitsPickerHarness(props: {
fallbackModelSelection: ModelSelection | null;
triggerVariant?: "ghost" | "outline";
}) {
const prompt = useComposerThreadDraft(CLAUDE_THREAD_ID).prompt;
const prompt = useComposerThreadDraft(CLAUDE_THREAD_REF).prompt;
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
const { modelOptions, selectedModel } = useEffectiveComposerModelState({
threadId: CLAUDE_THREAD_ID,
threadRef: CLAUDE_THREAD_REF,
providers: TEST_PROVIDERS,
selectedProvider: "claudeAgent",
threadModelSelection: props.fallbackModelSelection,
@@ -135,7 +142,7 @@ function ClaudeTraitsPickerHarness(props: {
});
const handlePromptChange = useCallback(
(nextPrompt: string) => {
setPrompt(CLAUDE_THREAD_ID, nextPrompt);
setPrompt(CLAUDE_THREAD_REF, nextPrompt);
},
[setPrompt],
);
@@ -144,7 +151,7 @@ function ClaudeTraitsPickerHarness(props: {
<TraitsPicker
provider="claudeAgent"
models={TEST_PROVIDERS[1]!.models}
threadId={CLAUDE_THREAD_ID}
threadRef={CLAUDE_THREAD_REF}
model={selectedModel ?? props.model}
prompt={prompt}
modelOptions={modelOptions?.claudeAgent}
@@ -168,8 +175,8 @@ async function mountClaudePicker(props?: {
}) {
const model = props?.model ?? "claude-opus-4-6";
const claudeOptions = !props?.skipDraftModelOptions ? props?.options : undefined;
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
[CLAUDE_THREAD_ID]: {
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[CLAUDE_THREAD_KEY]: {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
@@ -192,9 +199,9 @@ async function mountClaudePicker(props?: {
},
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
@@ -230,9 +237,9 @@ describe("TraitsPicker (Claude)", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
@@ -369,10 +376,9 @@ describe("TraitsPicker (Claude)", () => {
// ── Codex TraitsPicker tests ──────────────────────────────────────────
async function mountCodexPicker(props: { model?: string; options?: CodexModelOptions }) {
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex;
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
[threadId]: {
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[CODEX_THREAD_KEY]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
@@ -392,10 +398,10 @@ async function mountCodexPicker(props: { model?: string; options?: CodexModelOpt
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {
"environment-local:project-codex-traits": CODEX_THREAD_KEY,
},
});
const host = document.createElement("div");
@@ -404,7 +410,7 @@ async function mountCodexPicker(props: { model?: string; options?: CodexModelOpt
<TraitsPicker
provider="codex"
models={TEST_PROVIDERS[0]!.models}
threadId={threadId}
threadRef={CODEX_THREAD_REF}
model={props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex}
prompt=""
modelOptions={props.options}
@@ -429,9 +435,9 @@ describe("TraitsPicker (Codex)", () => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
+12 -5
View File
@@ -3,8 +3,8 @@ import {
type CodexModelOptions,
type ProviderKind,
type ProviderModelOptions,
type ScopedThreadRef,
type ServerProviderModel,
type ThreadId,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
@@ -28,18 +28,19 @@ import {
MenuSeparator as MenuDivider,
MenuTrigger,
} from "../ui/menu";
import { useComposerDraftStore } from "../../composerDraftStore";
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { cn } from "~/lib/utils";
type ProviderOptions = ProviderModelOptions[ProviderKind];
type TraitsPersistence =
| {
threadId: ThreadId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
onModelOptionsChange?: never;
}
| {
threadId?: undefined;
threadRef?: undefined;
onModelOptionsChange: (nextOptions: ProviderOptions | undefined) => void;
};
@@ -167,7 +168,13 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
persistence.onModelOptionsChange(nextOptions);
return;
}
setProviderModelOptions(persistence.threadId, provider, nextOptions, { persistSticky: true });
const threadTarget = persistence.threadRef ?? persistence.draftId;
if (!threadTarget) {
return;
}
setProviderModelOptions(threadTarget, provider, nextOptions, {
persistSticky: true,
});
},
[persistence, provider, setProviderModelOptions],
);
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import type { ServerProviderModel } from "@t3tools/contracts";
import { getComposerProviderState } from "./composerProviderRegistry";
import {
getComposerProviderState,
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
} from "./composerProviderRegistry";
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
{
@@ -417,3 +421,31 @@ describe("getComposerProviderState", () => {
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
});
});
describe("provider traits render guards", () => {
it("returns null for codex traits picker when no thread target is provided", () => {
const content = renderProviderTraitsPicker({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
modelOptions: undefined,
prompt: "",
onPromptChange: () => {},
});
expect(content).toBeNull();
});
it("returns null for claude traits menu content when no thread target is provided", () => {
const content = renderProviderTraitsMenuContent({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
modelOptions: undefined,
prompt: "",
onPromptChange: () => {},
});
expect(content).toBeNull();
});
});
@@ -1,11 +1,12 @@
import {
type ProviderKind,
type ProviderModelOptions,
type ScopedThreadRef,
type ServerProviderModel,
type ThreadId,
} from "@t3tools/contracts";
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
import type { ReactNode } from "react";
import type { DraftId } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
import {
@@ -33,7 +34,8 @@ export type ComposerProviderState = {
type ProviderRegistryEntry = {
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
renderTraitsMenuContent: (input: {
threadId: ThreadId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
@@ -41,7 +43,8 @@ type ProviderRegistryEntry = {
onPromptChange: (prompt: string) => void;
}) => ReactNode;
renderTraitsPicker: (input: {
threadId: ThreadId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
@@ -50,6 +53,13 @@ type ProviderRegistryEntry = {
}) => ReactNode;
};
function hasComposerTraitsTarget(input: {
threadRef: ScopedThreadRef | undefined;
draftId: DraftId | undefined;
}): boolean {
return input.threadRef !== undefined || input.draftId !== undefined;
}
function getProviderStateFromCapabilities(
input: ComposerProviderStateInput,
): ComposerProviderState {
@@ -94,66 +104,92 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
codex: {
getState: (input) => getProviderStateFromCapabilities(input),
renderTraitsMenuContent: ({
threadId,
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) => (
<TraitsMenuContent
provider="codex"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
<TraitsPicker
provider="codex"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsMenuContent
provider="codex"
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsPicker
provider="codex"
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
},
claudeAgent: {
getState: (input) => getProviderStateFromCapabilities(input),
renderTraitsMenuContent: ({
threadId,
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) => (
<TraitsMenuContent
provider="claudeAgent"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
<TraitsPicker
provider="claudeAgent"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsMenuContent
provider="claudeAgent"
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) =>
!hasComposerTraitsTarget({ threadRef, draftId }) ? null : (
<TraitsPicker
provider="claudeAgent"
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
model={model}
modelOptions={modelOptions}
prompt={prompt}
onPromptChange={onPromptChange}
/>
),
},
};
@@ -163,7 +199,8 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
export function renderProviderTraitsMenuContent(input: {
provider: ProviderKind;
threadId: ThreadId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
@@ -171,7 +208,8 @@ export function renderProviderTraitsMenuContent(input: {
onPromptChange: (prompt: string) => void;
}): ReactNode {
return composerProviderRegistry[input.provider].renderTraitsMenuContent({
threadId: input.threadId,
...(input.threadRef ? { threadRef: input.threadRef } : {}),
...(input.draftId ? { draftId: input.draftId } : {}),
model: input.model,
models: input.models,
modelOptions: input.modelOptions,
@@ -182,7 +220,8 @@ export function renderProviderTraitsMenuContent(input: {
export function renderProviderTraitsPicker(input: {
provider: ProviderKind;
threadId: ThreadId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
@@ -190,7 +229,8 @@ export function renderProviderTraitsPicker(input: {
onPromptChange: (prompt: string) => void;
}): ReactNode {
return composerProviderRegistry[input.provider].renderTraitsPicker({
threadId: input.threadId,
...(input.threadRef ? { threadRef: input.threadRef } : {}),
...(input.draftId ? { draftId: input.draftId } : {}),
model: input.model,
models: input.models,
modelOptions: input.modelOptions,
@@ -1,17 +1,29 @@
import "../../index.css";
import { DEFAULT_SERVER_SETTINGS, type NativeApi, type ServerConfig } from "@t3tools/contracts";
import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
type LocalApi,
type ServerConfig,
} from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { __resetNativeApiForTests } from "../../nativeApi";
import { __resetLocalApiForTests } from "../../localApi";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
import { GeneralSettingsPanel } from "./SettingsPanels";
function createBaseServerConfig(): ServerConfig {
return {
environment: {
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -32,14 +44,14 @@ function createBaseServerConfig(): ServerConfig {
describe("GeneralSettingsPanel observability", () => {
beforeEach(async () => {
resetServerStateForTests();
await __resetNativeApiForTests();
await __resetLocalApiForTests();
localStorage.clear();
document.body.innerHTML = "";
});
afterEach(async () => {
resetServerStateForTests();
await __resetNativeApiForTests();
await __resetLocalApiForTests();
document.body.innerHTML = "";
});
@@ -68,12 +80,12 @@ describe("GeneralSettingsPanel observability", () => {
});
it("opens the logs folder in the preferred editor", async () => {
const openInEditor = vi.fn<NativeApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
const openInEditor = vi.fn<LocalApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
window.nativeApi = {
shell: {
openInEditor,
},
} as unknown as NativeApi;
} as unknown as LocalApi;
setServerConfigSnapshot(createBaseServerConfig());
@@ -13,11 +13,12 @@ import { useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
PROVIDER_DISPLAY_NAMES,
type ScopedThreadRef,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { Equal } from "effect";
@@ -45,8 +46,12 @@ import {
getCustomModelOptionsByProvider,
resolveAppModelSelectionState,
} from "../../modelSelection";
import { ensureNativeApi, readNativeApi } from "../../nativeApi";
import { useStore } from "../../store";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import {
selectProjectsAcrossEnvironments,
selectThreadsAcrossEnvironments,
useStore,
} from "../../store";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
@@ -496,8 +501,8 @@ export function useSettingsRestore(onRestored?: () => void) {
const restoreDefaults = useCallback(async () => {
if (changedSettingLabels.length === 0) return;
const api = readNativeApi();
const confirmed = await (api ?? ensureNativeApi()).dialogs.confirm(
const api = readLocalApi();
const confirmed = await (api ?? ensureLocalApi()).dialogs.confirm(
["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join(
"\n",
),
@@ -554,7 +559,7 @@ export function GeneralSettingsPanel() {
if (refreshingRef.current) return;
refreshingRef.current = true;
setIsRefreshingProviders(true);
void ensureNativeApi()
void ensureLocalApi()
.server.refreshProviders()
.catch((error: unknown) => {
console.warn("Failed to refresh providers", error);
@@ -614,7 +619,7 @@ export function GeneralSettingsPanel() {
return;
}
void ensureNativeApi()
void ensureLocalApi()
.shell.openInEditor(path, editor)
.catch((error) => {
setOpenPathErrorByTarget((existing) => ({
@@ -1479,20 +1484,10 @@ export function GeneralSettingsPanel() {
}
export function ArchivedThreadsPanel() {
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 projects = useStore(selectProjectsAcrossEnvironments);
const threads = useStore(selectThreadsAcrossEnvironments);
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const archivedGroups = useMemo(() => {
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,
@@ -1505,11 +1500,11 @@ export function ArchivedThreadsPanel() {
}),
}))
.filter((group) => group.threads.length > 0);
}, [projectById, projectIds, threadIds, threadShellById]);
}, [projects, threads]);
const handleArchivedThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
const api = readLocalApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[
@@ -1521,7 +1516,7 @@ export function ArchivedThreadsPanel() {
if (clicked === "unarchive") {
try {
await unarchiveThread(threadId);
await unarchiveThread(threadRef);
} catch (error) {
toastManager.add({
type: "error",
@@ -1533,7 +1528,7 @@ export function ArchivedThreadsPanel() {
}
if (clicked === "delete") {
await confirmAndDeleteThread(threadId);
await confirmAndDeleteThread(threadRef);
}
},
[confirmAndDeleteThread, unarchiveThread],
@@ -1566,10 +1561,13 @@ export function ArchivedThreadsPanel() {
className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
void handleArchivedThreadContextMenu(
scopeThreadRef(thread.environmentId, thread.id),
{
x: event.clientX,
y: event.clientY,
},
);
}}
>
<div className="min-w-0 flex-1">
@@ -1586,13 +1584,16 @@ export function ArchivedThreadsPanel() {
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(thread.id).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to unarchive thread",
description: error instanceof Error ? error.message : "An error occurred.",
});
})
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id)).catch(
(error) => {
toastManager.add({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
});
},
)
}
>
<ArchiveX className="size-3.5" />