Compare commits

..
Author SHA1 Message Date
Julius Marminge a94819851d Track settled thread sends before clearing them
- add `requestSettled` state to pending sends
- clear sends only after the request has settled and state has caught up
- update ChatView to mark sends settled at the relevant points
2026-03-29 20:03:39 -07:00
Julius Marminge a2c1172551 Restore send phase handling in the store
- Move optimistic send state into shared store
- Keep connecting composer disabled without showing Stop generation
- Add coverage for the restored composer state
2026-03-29 19:59:47 -07:00
Julius Marminge 761e7359f9 Preserve send phase while resetting optimistic state
- Track the send-phase bridge phase alongside thread state
- Keep active thread phase stable during optimistic send resets
2026-03-29 19:32:19 -07:00
Julius Marminge 4c72c5f671 Stop resetting send phase from server snapshot
- Keep the optimistic send phase stable during turn start
- Remove redundant snapshot syncs that caused phase flicker
2026-03-29 19:28:59 -07:00
Julius Marminge 4790ea0129 Reset optimistic send phase per thread
- Track send phase state per active thread
- Clear stale optimistic sending state after failures and settles
- Keep work indicators aligned with the authoritative session phase
2026-03-29 19:25:32 -07:00
Julius Marminge f65ebd618e Merge branch 'main' into feature/fix-send-phase-reset 2026-03-29 18:37:59 -07:00
Julius Marminge 59f23d7bfd Show archive action on hover with confirm focus (#1561) 2026-03-29 18:36:53 -07:00
Naufal PutraandJulius Marminge 4a4795e5f0 Scroll active item into view in composer menu (#1557)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:33:47 +00:00
Efroim-PropelandJulius Marminge 5b58f74e9a fix(desktop): default confirm dialog selection to "No" (#1400)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-29 18:20:56 -07:00
Julius Marminge 6d51620f8b Avoid showing zero-second working timer
- Treat sub-second elapsed time as no timer
- Keep send-phase status text as "Working..." until time has accrued
2026-03-29 18:20:53 -07:00
Julius Marmingeandcodex 32dca3b76b [codex] debounce thread jump hint pills (#1526)
Co-authored-by: codex <[email protected]>
2026-03-29 18:19:37 -07:00
Abdulelah Hajjar 6358444900 fix(web): Fix duplicate highlight in composer slash command menu (#1445) 2026-03-29 18:14:59 -07:00
Alexander VostresandJulius Marminge 792ad4b5c1 Fix model settings getting stuck (#1538)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:13:16 +00:00
Julius Marminge 909fd5a571 Reset send start state after all send paths
- Clear `sendStartedAtRef` unconditionally when send work finishes
- Prevent stale send-phase state after success or failure
2026-03-29 18:03:30 -07:00
Craig d41781987c fix(web): preserve scroll when collapsing large changed-files trees (#1113) 2026-03-29 17:53:21 -07:00
shivamandEwan fc6507066e fix(windows): hover-effect-fix-in-the-branch-ui (#1559)
Co-authored-by: Ewan <[email protected]>
2026-03-29 17:53:03 -07:00
bf9c828aef Make provider model lists dynamic based on auth context (#1556)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-29 17:51:05 -07:00
shivam 7b676b76de fix: show empty project thread state in sidebar (#1546) 2026-03-29 11:47:51 -07:00
Julius Marminge d5f2333173 Show hidden thread status in sidebar (#1517) 2026-03-29 11:47:17 -07:00
Alexander Vostres 40e7dbdae9 Fix for broken Codex model selection for 'Text Generation Model' (#1543) 2026-03-29 11:27:20 -07:00
Julius Marminge 922f9b66e5 Fix send phase reset flicker
- Treat `connecting` as working in ChatView
- Sync orchestration snapshot before send transitions end
2026-03-29 10:55:53 -07:00
Julius Marminge 8332eb21d5 Reset send state with optimistic transition tracking
- Replace local send phase state with React transition/optimistic state
- Clear send timing reliably after send failures and thread creation
2026-03-29 10:30:25 -07:00
Cursor Agent c91e8b23e8 fix: prevent fallback effect from immediately resetting sendPhase on follow-up messages
The fallback effect that catches missed 'running' phase transitions was
incorrectly firing on follow-up messages. When beginSendPhase was called,
latestTurnSettled was still true from the previous completed turn, causing
an immediate resetSendPhase before the server could create the new turn.

Fix: record the turnId at the time beginSendPhase is called (via a ref),
and only allow the fallback reset when the latest turn differs from the
one recorded — meaning a new turn was actually created and has settled.

Applied via @cursor push command
2026-03-29 17:07:04 +00:00
Julius Marminge 9a9be39751 Reset stuck send phase after turns settle
- Keep the send timer alive while a send is active
- Fallback-reset sendPhase when a turn settles after a missed transition
2026-03-29 09:41:39 -07:00
66 changed files with 2729 additions and 1545 deletions

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
@@ -31,7 +31,6 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
workspaceState: "available",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
@@ -52,9 +51,6 @@ function makeSnapshot(input: {
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
effectiveCwd: input.worktreePath ?? input.workspaceRoot,
effectiveCwdSource: input.worktreePath ? "worktree" : "project",
effectiveCwdState: "available",
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
+25 -2
View File
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("keeps spark enabled for api key accounts", () => {
it("disables spark for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
});
});
});
@@ -343,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
+10 -94
View File
@@ -26,6 +26,15 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -96,23 +105,6 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -162,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
killCodexChildProcess(child);
}
export function normalizeCodexModelSlug(
@@ -402,19 +331,6 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
@@ -29,8 +29,9 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -84,8 +85,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptions(
modelSelection.model,
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
@@ -28,8 +28,9 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -156,8 +157,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptions(
modelSelection.model,
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
+1 -16
View File
@@ -1,10 +1,9 @@
import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Cause, Effect, Exit, FileSystem, Layer, PlatformError, Scope } from "effect";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
@@ -1284,20 +1283,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("fails cleanly when statusDetails is requested for a missing workspace", () =>
Effect.gen(function* () {
const missingCwd = path.join(os.tmpdir(), `git-missing-${crypto.randomUUID()}`);
const result = yield* Effect.exit((yield* GitCore).statusDetails(missingCwd));
expect(Exit.isFailure(result)).toBe(true);
if (Exit.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toBeInstanceOf(GitCommandError);
expect((error as GitCommandError).detail).toContain("Workspace folder is missing");
}
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+2 -20
View File
@@ -29,7 +29,6 @@ import {
} from "../Services/GitCore.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -519,13 +518,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const { worktreesDir } = yield* ServerConfig;
let execute: GitCoreShape["execute"];
let rawExecute: GitCoreShape["execute"];
if (options?.executeOverride) {
rawExecute = options.executeOverride;
execute = options.executeOverride;
} else {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
rawExecute = Effect.fnUntraced(function* (input) {
execute = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
@@ -615,22 +613,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
execute = Effect.fnUntraced(function* (input) {
yield* assertWorkspaceDirectory(input.cwd, input.operation).pipe(
Effect.mapError(
(error) =>
new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: error.message,
cause: error,
}),
),
);
return yield* rawExecute(input);
});
const executeGit = (
operation: string,
cwd: string,
@@ -25,10 +25,6 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import {
inspectWorkspacePathState,
resolveWorkspaceUnavailableReason,
} from "../../workspacePaths.ts";
type ReactorInput =
| {
@@ -158,12 +154,7 @@ const make = Effect.gen(function* () {
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly thread: {
readonly projectId: ProjectId;
readonly worktreePath: string | null;
readonly effectiveCwd: string | null;
readonly effectiveCwdState: string;
};
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
}): Effect.fn.Return<string | undefined> {
@@ -184,7 +175,7 @@ const make = Effect.gen(function* () {
onSome: (runtime) => runtime.cwd,
}));
if (input.thread.effectiveCwdState !== "available" || !cwd) {
if (!cwd) {
return undefined;
}
if (!isGitWorkspace(cwd)) {
@@ -592,20 +583,6 @@ const make = Effect.gen(function* () {
}).pipe(Effect.catch(() => Effect.void));
return;
}
const sessionWorkspaceState = yield* Effect.promise(() =>
inspectWorkspacePathState(sessionRuntime.value.cwd),
);
if (sessionWorkspaceState !== "available") {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
detail:
resolveWorkspaceUnavailableReason(sessionWorkspaceState) ??
"Workspace folder is unavailable.",
createdAt: now,
}).pipe(Effect.catch(() => Effect.void));
return;
}
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
@@ -1,7 +1,3 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
@@ -27,7 +23,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "projection-snapshot-"));
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
@@ -48,7 +43,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
VALUES (
'project-1',
'Project 1',
${workspaceRoot},
'/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}',
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
'2026-02-24T00:00:00.000Z',
@@ -238,8 +233,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot,
workspaceState: "available",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -271,9 +265,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: workspaceRoot,
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
@@ -18,7 +18,6 @@ import {
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
type WorkspaceAvailabilityState,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -43,7 +42,6 @@ import {
ProjectionSnapshotQuery,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
import { inspectWorkspacePathState } from "../../workspacePaths.ts";
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
@@ -137,12 +135,6 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
: toPersistenceSqlError(sqlOperation)(cause);
}
type EffectiveWorkspaceMetadata = {
readonly effectiveCwd: string | null;
readonly effectiveCwdSource: "project" | "worktree" | null;
readonly effectiveCwdState: WorkspaceAvailabilityState;
};
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -546,35 +538,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const workspaceRoots = new Set(projectRows.map((row) => row.workspaceRoot));
const worktreePaths = new Set(
threadRows.flatMap((row) => (row.worktreePath ? [row.worktreePath] : [])),
);
const workspaceStateEntries = yield* Effect.promise(() =>
Promise.all(
[...new Set([...workspaceRoots, ...worktreePaths])].map(async (workspacePath) => {
const workspaceState = await inspectWorkspacePathState(workspacePath);
return [workspacePath, workspaceState] as const;
}),
),
);
const workspaceStates = new Map(workspaceStateEntries);
const projectRowsById = new Map(projectRows.map((row) => [row.projectId, row] as const));
const projectWorkspaceStateById = new Map(
projectRows.map((row) => [
row.projectId,
workspaceStates.get(row.workspaceRoot) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
]),
);
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
workspaceState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -582,48 +549,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
deletedAt: row.deletedAt,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => {
const effectiveWorkspace: EffectiveWorkspaceMetadata =
row.worktreePath !== null
? {
effectiveCwd: row.worktreePath,
effectiveCwdSource: "worktree",
effectiveCwdState:
workspaceStates.get(row.worktreePath) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
}
: {
effectiveCwd: projectRowsById.get(row.projectId)?.workspaceRoot ?? null,
effectiveCwdSource: projectRowsById.has(row.projectId) ? "project" : null,
effectiveCwdState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
};
return {
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
effectiveCwd: effectiveWorkspace.effectiveCwd,
effectiveCwdSource: effectiveWorkspace.effectiveCwdSource,
effectiveCwdState: effectiveWorkspace.effectiveCwdState,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
};
});
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -45,8 +45,6 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
fs.mkdirSync("/tmp/provider-project", { recursive: true });
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -25,7 +25,6 @@ import {
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -255,12 +254,6 @@ const make = Effect.gen(function* () {
thread,
projects: readModel.projects,
});
if (effectiveCwd) {
yield* assertWorkspaceDirectory(
effectiveCwd,
"ProviderCommandReactor.ensureSessionForThread",
);
}
const resolveActiveSession = (threadId: ThreadId) =>
providerService
@@ -28,7 +28,6 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -42,7 +41,6 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -66,9 +64,6 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-a",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -92,9 +87,6 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-b",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -183,7 +183,6 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
workspaceState: "available" as const,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
createdAt: payload.createdAt,
+436 -174
View File
@@ -1,15 +1,15 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import {
buildServerProvider,
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -96,28 +96,9 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getClaudeModelCapabilities(model);
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -129,7 +110,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
@@ -144,7 +125,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
@@ -165,37 +146,286 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
// ── Dynamic model capability adjustment ─────────────────────────────
/** Subscription types where the 1M context window is included in the plan. */
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
"max",
"maxplan",
"max5",
"max20",
"enterprise",
"team",
]);
function toTitleCaseWords(value: string): string {
return value
.split(/[\s_-]+/g)
.filter(Boolean)
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
.join(" ");
}
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
switch (normalized) {
case "max":
case "maxplan":
case "max5":
case "max20":
return "Max";
case "enterprise":
return "Enterprise";
case "team":
return "Team";
case "pro":
return "Pro";
case "free":
return "Free";
default:
return toTitleCaseWords(subscriptionType!);
}
}
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
if (normalized === "apikey") return "apiKey";
return undefined;
}
function claudeAuthMetadata(input: {
readonly subscriptionType: string | undefined;
readonly authMethod: string | undefined;
}): { readonly type: string; readonly label: string } | undefined {
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
return {
type: "apiKey",
label: "Claude API Key",
};
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
};
}
return undefined;
}
/**
* Adjust the built-in model list based on the user's detected subscription.
*
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
* - Other tiers (Pro, free, unknown): 200k context stays the default;
* 1M remains available as a manual option so users can still enable it.
*/
export function adjustModelsForSubscription(
baseModels: ReadonlyArray<ServerProviderModel>,
subscriptionType: string | undefined,
): ReadonlyArray<ServerProviderModel> {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
return baseModels;
}
// Flip 1M to be the default for premium users
return baseModels.map((model) => {
const caps = model.capabilities;
if (!caps || caps.contextWindowOptions.length === 0) return model;
return {
...model,
capabilities: {
...caps,
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
opt.value === "1m"
? { value: opt.value, label: opt.label, isDefault: true as const }
: { value: opt.value, label: opt.label },
),
},
};
});
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
*
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
prompt: ".",
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: [],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return { subscriptionType: init.account?.subscriptionType };
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (!abort.signal.aborted) abort.abort();
}),
),
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
};
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
@@ -208,144 +438,81 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Claude is disabled in T3 Code settings.",
},
});
}
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
@@ -354,13 +521,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
status: "error",
auth: { status: "unknown" },
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
},
);
}
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
@@ -368,7 +621,16 @@ export const ClaudeProviderLive = Layer.effect(
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkClaudeProviderStatus().pipe(
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) =>
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
});
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
+242 -202
View File
@@ -1,16 +1,25 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -29,6 +38,13 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount";
import { probeCodexAccount } from "../codexAppServer";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
@@ -152,25 +168,9 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
);
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const caps = getCodexModelCapabilities(model);
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
@@ -196,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
@@ -217,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
auth: { status: "unknown" },
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
@@ -290,6 +290,21 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.orElseSucceed(() => false),
);
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
const probeCodexCapabilities = (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) =>
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
@@ -306,179 +321,88 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Codex is disabled in T3 Code settings.",
},
});
}
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
@@ -487,13 +411,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
},
);
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
auth: { status: "unknown" },
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const account = resolveAccount
? yield* resolveAccount({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
})
: undefined;
const resolvedModels = adjustCodexModelsForAccount(models, account);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const authType = codexAuthSubType(account);
const authLabel = codexAuthSubLabel(account);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
export const CodexProviderLive = Layer.effect(
CodexProvider,
@@ -502,8 +529,21 @@ export const CodexProviderLive = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: string) => {
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
return probeCodexCapabilities({
binaryPath,
...(homePath ? { homePath } : {}),
});
},
});
const checkProvider = checkCodexProviderStatus().pipe(
const checkProvider = checkCodexProviderStatus((input) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -173,7 +173,133 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "pro" as const,
sparkEnabled: true,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "pro");
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
true,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "plus" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "plus");
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "team" as const,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.auth.type, "team");
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for codex api key auth", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "apiKey" as const,
planType: null,
sparkEnabled: false,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "OpenAI API Key");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -235,7 +361,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
} finally {
process.env.PATH = previousPath;
}
@@ -249,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
@@ -264,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
@@ -287,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -313,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -338,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
@@ -366,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "ready",
enabled: true,
installed: true,
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -376,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "warning",
enabled: true,
installed: true,
authStatus: "unknown",
auth: { status: "unknown" },
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -494,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
@@ -537,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
const status = yield* checkCodexProviderStatus();
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -558,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
@@ -568,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
assert.strictEqual(parsed.auth.status, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -578,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
assert.strictEqual(parsed.auth.status, "unknown");
});
});
@@ -715,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -733,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "maxplan");
assert.strictEqual(status.auth.label, "Claude Max Subscription");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns an api key label for claude api key auth", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "Claude API Key");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
@@ -771,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
@@ -799,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(status.auth.status, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -819,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
@@ -844,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
@@ -854,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
@@ -864,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
assert.strictEqual(parsed.auth.status, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -874,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
assert.strictEqual(parsed.auth.status, "unknown");
});
});
},
@@ -20,7 +20,7 @@ import {
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Cause, Effect, Fiber, Layer, Option, PubSub, Ref, Schema, Stream } from "effect";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -44,7 +44,6 @@ import {
} from "../../persistence/Layers/Sqlite.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { clearWorkspacePathStateCache } from "../../workspacePaths.ts";
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
@@ -231,16 +230,6 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
for (const workspaceRoot of [
"/tmp/project",
"/tmp/project-claude",
"/tmp/project-send-turn",
"/tmp/project-claude-send-turn",
"/tmp/project-claude-start",
]) {
fs.mkdirSync(workspaceRoot, { recursive: true });
}
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
@@ -692,46 +681,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("fails recovery cleanly when the persisted workspace has been deleted", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "provider-missing-cwd-"));
const initial = yield* provider.startSession(asThreadId("thread-missing-cwd"), {
provider: "codex",
threadId: asThreadId("thread-missing-cwd"),
cwd: workspaceRoot,
runtimeMode: "full-access",
});
fs.rmSync(workspaceRoot, { recursive: true, force: true });
clearWorkspacePathStateCache(workspaceRoot);
yield* routing.codex.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
const exit = yield* Effect.exit(
provider.sendTurn({
threadId: initial.threadId,
input: "resume",
attachments: [],
}),
);
assert.equal(routing.codex.startSession.mock.calls.length, 0);
assert.equal(routing.codex.sendTurn.mock.calls.length, 0);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.equal(Schema.is(ProviderValidationError)(error), true);
assert.equal(
(error as ProviderValidationError).message.includes("Workspace folder is missing"),
true,
);
}
}),
);
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -34,7 +34,6 @@ import {
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
@@ -229,21 +228,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
if (persistedCwd) {
yield* assertWorkspaceDirectory(
persistedCwd,
"ProviderService.recoverSessionForThread",
).pipe(
Effect.mapError((error) =>
toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}'. ${error.message}`,
error,
),
),
);
}
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
@@ -331,13 +315,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
if (input.cwd) {
yield* assertWorkspaceDirectory(input.cwd, "ProviderService.startSession").pipe(
Effect.mapError((error) =>
toValidationError("ProviderService.startSession", error.message, error),
),
);
}
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
+123
View File
@@ -0,0 +1,123 @@
import type { ServerProviderModel } from "@t3tools/contracts";
export type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
export interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: false,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
if (account?.type === "apiKey") {
return "apiKey";
}
if (account?.type !== "chatgpt") {
return undefined;
}
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
}
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
switch (codexAuthSubType(account)) {
case "apiKey":
return "OpenAI API Key";
case "chatgpt":
return "ChatGPT Subscription";
case "free":
return "ChatGPT Free Subscription";
case "go":
return "ChatGPT Go Subscription";
case "plus":
return "ChatGPT Plus Subscription";
case "pro":
return "ChatGPT Pro Subscription";
case "team":
return "ChatGPT Team Subscription";
case "business":
return "ChatGPT Business Subscription";
case "enterprise":
return "ChatGPT Enterprise Subscription";
case "edu":
return "ChatGPT Edu Subscription";
default:
return undefined;
}
}
export function adjustCodexModelsForAccount(
baseModels: ReadonlyArray<ServerProviderModel>,
account: CodexAccountSnapshot | undefined,
): ReadonlyArray<ServerProviderModel> {
if (account?.sparkEnabled !== false) {
return baseModels;
}
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
+154
View File
@@ -0,0 +1,154 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
interface JsonRpcProbeResponse {
readonly id?: unknown;
readonly result?: unknown;
readonly error?: {
readonly message?: unknown;
};
}
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
return typeof response.error?.message === "string" ? response.error.message : undefined;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill();
}
export async function probeCodexAccount(input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly signal?: AbortSignal;
}): Promise<CodexAccountSnapshot> {
return await new Promise((resolve, reject) => {
const child = spawn(input.binaryPath, ["app-server"], {
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
let completed = false;
const cleanup = () => {
output.removeAllListeners();
output.close();
child.removeAllListeners();
if (!child.killed) {
killCodexChildProcess(child);
}
};
const finish = (callback: () => void) => {
if (completed) return;
completed = true;
cleanup();
callback();
};
const fail = (error: unknown) =>
finish(() =>
reject(
error instanceof Error
? error
: new Error(`Codex account probe failed: ${String(error)}.`),
),
);
if (input.signal?.aborted) {
fail(new Error("Codex account probe aborted."));
return;
}
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
const writeMessage = (message: unknown) => {
if (!child.stdin.writable) {
fail(new Error("Cannot write to codex app-server stdin."));
return;
}
child.stdin.write(`${JSON.stringify(message)}\n`);
};
output.on("line", (line) => {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
fail(new Error("Received invalid JSON from codex app-server during account probe."));
return;
}
if (!parsed || typeof parsed !== "object") {
return;
}
const response = parsed as JsonRpcProbeResponse;
if (response.id === 1) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`initialize failed: ${errorMessage}`));
return;
}
writeMessage({ method: "initialized" });
writeMessage({ id: 2, method: "account/read", params: {} });
return;
}
if (response.id === 2) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`account/read failed: ${errorMessage}`));
return;
}
finish(() => resolve(readCodexAccountSnapshot(response.result)));
}
});
child.once("error", fail);
child.once("exit", (code, signal) => {
if (completed) return;
fail(
new Error(
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
),
);
});
writeMessage({
id: 1,
method: "initialize",
params: buildCodexInitializeParams(),
});
});
}
+3 -3
View File
@@ -1,6 +1,6 @@
import type {
ServerProvider,
ServerProviderAuthStatus,
ServerProviderAuth,
ServerProviderModel,
ServerProviderState,
} from "@t3tools/contracts";
@@ -21,7 +21,7 @@ export interface ProviderProbeResult {
readonly installed: boolean;
readonly version: string | null;
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly auth: ServerProviderAuth;
readonly message?: string;
}
@@ -137,7 +137,7 @@ export function buildServerProvider(input: {
installed: input.probe.installed,
version: input.probe.version,
status: input.enabled ? input.probe.status : "disabled",
authStatus: input.probe.authStatus,
auth: input.probe.auth,
checkedAt: input.checkedAt,
...(input.probe.message ? { message: input.probe.message } : {}),
models: input.models,
+37
View File
@@ -104,6 +104,43 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
// Start with Claude text generation selection
yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "high",
},
},
});
// Switch to Codex — the stale Claude "effort" in options must not
// cause the update to lose the selected model.
const next = yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
},
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "high",
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims provider path settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
+14 -4
View File
@@ -27,6 +27,7 @@ import {
FileSystem,
Layer,
Path,
Equal,
PubSub,
Ref,
Schema,
@@ -130,9 +131,12 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings
};
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
return Equal.equals(current, defaults) ? undefined : current;
}
if (
@@ -146,9 +150,15 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
if (ATOMIC_SETTINGS_KEYS.has(key)) {
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
next[key] = currentRecord[key];
}
} else {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
}
}
+11 -8
View File
@@ -27,7 +27,6 @@ import {
TerminalSessionState,
TerminalStartInput,
} from "../Services/Manager";
import { inspectWorkspacePathState, WorkspacePathError } from "../../workspacePaths.ts";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
@@ -1243,13 +1242,17 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private async assertValidCwd(cwd: string): Promise<void> {
const state = await inspectWorkspacePathState(cwd);
if (state !== "available") {
throw new WorkspacePathError({
operation: "TerminalManager.assertValidCwd",
path: cwd,
state,
});
let stats: fs.Stats;
try {
stats = await fs.promises.stat(cwd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
}
throw error;
}
if (!stats.isDirectory()) {
throw new Error(`Terminal cwd is not a directory: ${cwd}`);
}
}
-100
View File
@@ -1,100 +0,0 @@
import fs from "node:fs/promises";
import { type WorkspaceAvailabilityState } from "@t3tools/contracts";
import { Effect, Schema } from "effect";
const WORKSPACE_PATH_CACHE_TTL_MS = 1_000;
type CachedWorkspacePathState = {
readonly expiresAt: number;
readonly state: WorkspaceAvailabilityState;
};
const workspacePathStateCache = new Map<string, CachedWorkspacePathState>();
export class WorkspacePathError extends Schema.TaggedErrorClass<WorkspacePathError>()(
"WorkspacePathError",
{
operation: Schema.String,
path: Schema.String,
state: Schema.Literals(["missing", "not_directory", "inaccessible"]),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
switch (this.state) {
case "missing":
return `Workspace folder is missing: ${this.path}`;
case "not_directory":
return `Workspace path is not a folder: ${this.path}`;
case "inaccessible":
default:
return `Workspace folder is inaccessible: ${this.path}`;
}
}
}
export function clearWorkspacePathStateCache(path?: string): void {
if (path) {
workspacePathStateCache.delete(path);
return;
}
workspacePathStateCache.clear();
}
export async function inspectWorkspacePathState(path: string): Promise<WorkspaceAvailabilityState> {
const cached = workspacePathStateCache.get(path);
const now = Date.now();
if (cached && cached.expiresAt > now) {
return cached.state;
}
let state: WorkspaceAvailabilityState;
try {
const stat = await fs.stat(path);
state = stat.isDirectory() ? "available" : "not_directory";
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
state = code === "ENOENT" ? "missing" : "inaccessible";
}
workspacePathStateCache.set(path, {
expiresAt: now + WORKSPACE_PATH_CACHE_TTL_MS,
state,
});
return state;
}
export const getWorkspacePathState = (path: string) =>
Effect.promise(() => inspectWorkspacePathState(path));
export const assertWorkspaceDirectory = (path: string, operation: string) =>
getWorkspacePathState(path).pipe(
Effect.flatMap((state) =>
state === "available"
? Effect.succeed(path)
: Effect.fail(
new WorkspacePathError({
operation,
path,
state,
}),
),
),
);
export function resolveWorkspaceUnavailableReason(
state: WorkspaceAvailabilityState,
): string | null {
switch (state) {
case "missing":
return "Workspace folder is missing.";
case "not_directory":
return "Workspace path is not a folder.";
case "inaccessible":
return "Workspace folder is inaccessible.";
case "available":
default:
return null;
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
+1 -34
View File
@@ -79,7 +79,6 @@ import { expandHomePath } from "./os-jank.ts";
import { makeServerPushBus } from "./wsServer/pushBus.ts";
import { makeServerReadiness } from "./wsServer/readiness.ts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
import { assertWorkspaceDirectory, WorkspacePathError } from "./workspacePaths.ts";
/**
* ServerShape - Service API for server lifecycle control.
@@ -234,22 +233,6 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
message: Schema.String,
}) {}
function formatOperationalError(cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
if (
Schema.is(RouteRequestError)(error) ||
Schema.is(WorkspacePathError)(error) ||
(typeof error === "object" &&
error !== null &&
"message" in error &&
typeof error.message === "string" &&
error.message.trim().length > 0)
) {
return (error as { message: string }).message;
}
return Cause.pretty(cause);
}
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
@@ -785,7 +768,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.projects.searchEntries");
return yield* Effect.tryPromise({
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
@@ -797,7 +779,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsWriteFile: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.projects.writeFile");
const target = yield* resolveWorkspaceWritePath({
workspaceRoot: body.cwd,
relativePath: body.relativePath,
@@ -826,25 +807,21 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.shellOpenInEditor: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.shell.openInEditor");
return yield* openInEditor(body);
}
case WS_METHODS.gitStatus: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.status");
return yield* gitManager.status(body);
}
case WS_METHODS.gitPull: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.pull");
return yield* git.pullCurrentBranch(body.cwd);
}
case WS_METHODS.gitRunStackedAction: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.runStackedAction");
return yield* gitManager.runStackedAction(body, {
actionId: body.actionId,
progressReporter: {
@@ -856,55 +833,46 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitResolvePullRequest: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.resolvePullRequest");
return yield* gitManager.resolvePullRequest(body);
}
case WS_METHODS.gitPreparePullRequestThread: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.preparePullRequestThread");
return yield* gitManager.preparePullRequestThread(body);
}
case WS_METHODS.gitListBranches: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.listBranches");
return yield* git.listBranches(body);
}
case WS_METHODS.gitCreateWorktree: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.createWorktree");
return yield* git.createWorktree(body);
}
case WS_METHODS.gitRemoveWorktree: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.removeWorktree");
return yield* git.removeWorktree(body);
}
case WS_METHODS.gitCreateBranch: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.createBranch");
return yield* git.createBranch(body);
}
case WS_METHODS.gitCheckout: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.checkout");
return yield* Effect.scoped(git.checkoutBranch(body));
}
case WS_METHODS.gitInit: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.git.init");
return yield* git.initRepo(body);
}
case WS_METHODS.terminalOpen: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.terminal.open");
return yield* terminalManager.open(body);
}
@@ -925,7 +893,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.terminalRestart: {
const body = stripRequestTag(request.body);
yield* assertWorkspaceDirectory(body.cwd, "ws.terminal.restart");
return yield* terminalManager.restart(body);
}
@@ -1006,7 +973,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
error: { message: formatOperationalError(result.cause) },
error: { message: Cause.pretty(result.cause) },
});
}
+1 -8
View File
@@ -13,7 +13,6 @@ import {
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import { isProjectWorkspaceAvailable, isThreadWorkspaceAvailable } from "../workspaceAvailability";
const envModeItems = [
{ value: "local", label: "Local" },
@@ -47,13 +46,7 @@ export default function BranchToolbar({
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = serverThread
? isThreadWorkspaceAvailable(serverThread)
? serverThread.effectiveCwd
: null
: activeProject && isProjectWorkspaceAvailable(activeProject)
? activeProject.cwd
: null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode = resolveEffectiveEnvMode({
activeWorktreePath,
@@ -397,7 +397,6 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
style={style}
onClick={() => selectBranch(branch)}
>
+125 -8
View File
@@ -117,7 +117,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: NOW_ISO,
models: [],
},
@@ -232,7 +232,6 @@ function createSnapshotForTargetUser(options: {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -256,9 +255,6 @@ function createSnapshotForTargetUser(options: {
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -317,9 +313,6 @@ function addThreadToSnapshot(
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -1048,6 +1041,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
);
it("shows an explicit empty state for projects without threads in the sidebar", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
});
try {
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd for draft threads without a worktree path", async () => {
setDraftThreadWithoutWorktree();
@@ -1767,6 +1773,117 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("restores the connecting composer state without showing the stop button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-connecting-state" as MessageId,
targetText: "connecting state target",
sessionStatus: "starting",
}),
});
try {
const connectingButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Connecting"]'),
"Unable to find connecting send button.",
);
expect(connectingButton.disabled).toBe(true);
expect(
document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
).toBeNull();
const composerEditor = await waitForElement(
() => document.querySelector<HTMLElement>('[contenteditable="false"]'),
"Unable to find disabled composer editor.",
);
expect(composerEditor).toBeTruthy();
} finally {
await mounted.cleanup();
}
});
it("hides the archive action when the pointer leaves a thread row", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-hover-test" as MessageId,
targetText: "archive hover target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
const archiveButton = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
"Unable to find archive button.",
);
const archiveAction = archiveButton.parentElement;
expect(
archiveAction,
"Archive button should render inside a visibility wrapper.",
).not.toBeNull();
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
await threadRow.hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("1");
},
{ timeout: 4_000, interval: 16 },
);
await page.getByTestId("composer-editor").hover();
await vi.waitFor(
() => {
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
},
{ timeout: 4_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("shows the confirm archive action after clicking the archive button", async () => {
localStorage.setItem(
"t3code:client-settings:v1",
JSON.stringify({
...DEFAULT_CLIENT_SETTINGS,
confirmThreadArchive: true,
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-archive-confirm-test" as MessageId,
targetText: "archive confirm target",
}),
});
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
await threadRow.hover();
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
await expect.element(archiveButton).toBeInTheDocument();
await archiveButton.click();
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
await expect.element(confirmButton).toBeInTheDocument();
await expect.element(confirmButton).toBeVisible();
} finally {
localStorage.removeItem("t3code:client-settings:v1");
await mounted.cleanup();
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -19,7 +19,6 @@ export function buildLocalDraftThread(
draftThread: DraftThreadState,
fallbackModelSelection: ModelSelection,
error: string | null,
projectCwd: string | null,
): Thread {
return {
id: threadId,
@@ -38,9 +37,6 @@ export function buildLocalDraftThread(
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
effectiveCwd: draftThread.worktreePath ?? projectCwd,
effectiveCwdSource: draftThread.worktreePath ? "worktree" : projectCwd ? "project" : null,
effectiveCwdState: "available",
turnDiffSummaries: [],
activities: [],
proposedPlans: [],
@@ -79,8 +75,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
+153 -293
View File
@@ -107,6 +107,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
@@ -174,15 +175,8 @@ import {
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
SendPhase,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import {
isProjectWorkspaceAvailable,
isThreadWorkspaceAvailable,
workspaceUnavailableReason,
} from "../workspaceAvailability";
import { useThreadActions } from "../hooks/useThreadActions";
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -251,14 +245,19 @@ interface PendingPullRequestSetupRequest {
}
export default function ChatView({ threadId }: ChatViewProps) {
const beginThreadSend = useStore((store) => store.beginThreadSend);
const clearThreadSend = useStore((store) => store.clearThreadSend);
const markThreadSendSettled = useStore((store) => store.markThreadSendSettled);
const moveThreadSend = useStore((store) => store.moveThreadSend);
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
const pendingThreadSend = useStore((store) => store.pendingThreadSendById[threadId] ?? null);
const setThreadSendPhase = useStore((store) => store.setThreadSendPhase);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const settings = useSettings();
const { confirmAndDeleteThread } = useThreadActions();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
);
@@ -331,14 +330,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
optimisticUserMessagesRef.current = optimisticUserMessages;
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
@@ -486,16 +481,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
localDraftError,
fallbackDraftProject?.cwd ?? null,
)
: undefined,
[
draftThread,
fallbackDraftProject?.defaultModelSelection,
fallbackDraftProject?.cwd,
localDraftError,
threadId,
],
[draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId],
);
const activeThread = serverThread ?? localDraftThread;
const runtimeMode =
@@ -514,16 +502,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
const projectWorkspaceAvailable = activeProject
? isProjectWorkspaceAvailable(activeProject)
: false;
const threadWorkspaceAvailable = activeThread ? isThreadWorkspaceAvailable(activeThread) : false;
const missingProjectWorkspace = activeProject !== undefined && !projectWorkspaceAvailable;
const missingWorktreeWorkspace =
activeThread?.effectiveCwdSource === "worktree" &&
activeThread.effectiveCwd !== null &&
!threadWorkspaceAvailable &&
projectWorkspaceAvailable;
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -687,14 +665,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const activeSendStartedAt = pendingThreadSend?.startedAt ?? null;
const isSendBusy = pendingThreadSend !== null;
const isPreparingWorktree =
pendingThreadSend?.phase === "preparing-worktree" && createWorktreeMutation.isPending;
const isConnecting = phase === "connecting";
const showConnectingState = isConnecting && !isSendBusy;
const isWorking = phase === "running" || isSendBusy || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
sendStartedAt,
activeSendStartedAt,
);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
@@ -1032,7 +1014,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
latestTurnSettled,
timelineEntries,
]);
const gitCwd = threadWorkspaceAvailable ? (activeThread?.effectiveCwd ?? null) : null;
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
worktreePath: activeThread?.worktreePath ?? null,
})
: null;
const composerTriggerKind = composerTrigger?.kind ?? null;
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
const isPathTrigger = composerTriggerKind === "path";
@@ -1042,7 +1029,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd, threadWorkspaceAvailable));
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const modelOptionsByProvider = useMemo(
@@ -1080,7 +1067,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
projectSearchEntriesQueryOptions({
cwd: gitCwd,
query: effectivePathQuery,
enabled: isPathTrigger && threadWorkspaceAvailable,
enabled: isPathTrigger,
limit: 80,
}),
);
@@ -1156,9 +1143,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
null,
[composerHighlightedItemId, composerMenuItems],
);
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
@@ -1178,7 +1162,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: activeThreadWorktreePath,
});
}, [activeProjectCwd, activeThreadWorktreePath]);
const isGitRepo = threadWorkspaceAvailable && (branchesQuery.data?.isRepo ?? true);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -1263,50 +1248,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[setStoreThreadError, threads],
);
const relinkProjectWorkspace = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeProject) return;
const nextWorkspaceRoot = await api.dialogs.pickFolder();
if (!nextWorkspaceRoot) {
return;
}
await api.orchestration.dispatchCommand({
type: "project.meta.update",
commandId: newCommandId(),
projectId: activeProject.id,
workspaceRoot: nextWorkspaceRoot,
});
}, [activeProject]);
const useProjectRootForThread = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeThread) return;
if (activeThread.session && activeThread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: activeThread.id,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
branch: null,
worktreePath: null,
});
}, [activeThread]);
const removeActiveProject = useCallback(async () => {
const api = readNativeApi();
if (!api || !activeProject) return;
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: newCommandId(),
projectId: activeProject.id,
});
}, [activeProject]);
const focusComposer = useCallback(() => {
composerEditorRef.current?.focusAtEnd();
@@ -2041,6 +1982,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts]);
useEffect(() => {
optimisticUserMessagesRef.current = optimisticUserMessages;
}, [optimisticUserMessages]);
useEffect(() => {
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
}, [activeComposerMenuItem, composerMenuItems, composerMenuOpen]);
useEffect(() => {
if (!activeThread?.id) return;
if (activeThread.messages.length === 0) {
@@ -2081,8 +2032,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
setSendPhase("idle");
setSendStartedAt(null);
sendInFlightRef.current = false;
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
@@ -2213,45 +2163,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
: "local";
useEffect(() => {
if (phase !== "running") return;
if (phase !== "running" && !isSendBusy) return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [phase]);
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
setSendStartedAt((current) => current ?? new Date().toISOString());
setSendPhase(nextPhase);
}, []);
const resetSendPhase = useCallback(() => {
setSendPhase("idle");
setSendStartedAt(null);
}, []);
useEffect(() => {
if (sendPhase === "idle") {
return;
}
if (
phase === "running" ||
activePendingApproval !== null ||
activePendingUserInput !== null ||
activeThread?.error
) {
resetSendPhase();
}
}, [
activePendingApproval,
activePendingUserInput,
activeThread?.error,
phase,
resetSendPhase,
sendPhase,
]);
}, [isSendBusy, phase]);
useEffect(() => {
if (!activeThreadId) return;
@@ -2471,7 +2390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy || isConnecting) {
if (phase === "running" || isSendBusy) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -2504,13 +2423,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
setIsRevertingCheckpoint(false);
},
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
);
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (!api || !activeThread || isSendBusy || sendInFlightRef.current) return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -2589,8 +2508,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
const sendStartedAt = new Date().toISOString();
sendInFlightRef.current = true;
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
beginThreadSend(
threadIdForSend,
baseBranchForWorktree ? "preparing-worktree" : "sending-turn",
sendStartedAt,
);
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2661,10 +2585,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
await (async () => {
try {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginSendPhase("preparing-worktree");
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2739,10 +2662,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
let shouldRunSetupScript = false;
if (isServerThread) {
shouldRunSetupScript = true;
} else {
if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
} else if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
if (shouldRunSetupScript) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
@@ -2776,7 +2697,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginSendPhase("sending-turn");
if (baseBranchForWorktree) {
setThreadSendPhase(threadIdForSend, "sending-turn");
}
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2795,7 +2718,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
})().catch(async (err: unknown) => {
markThreadSendSettled(threadIdForSend);
} catch (err: unknown) {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
@@ -2830,11 +2754,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadIdForSend,
err instanceof Error ? err.message : "Failed to send message.",
);
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetSendPhase();
clearThreadSend(threadIdForSend);
}
sendInFlightRef.current = false;
};
const onInterrupt = async () => {
@@ -3004,14 +2926,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
interactionMode: "default" | "plan";
}) => {
const api = readNativeApi();
if (
!api ||
!activeThread ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
if (!api || !activeThread || !isServerThread || isSendBusy || sendInFlightRef.current) {
return;
}
@@ -3032,7 +2947,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginSendPhase("sending-turn");
beginThreadSend(threadIdForSend, "sending-turn", new Date().toISOString());
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -3084,6 +2999,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
: {}),
createdAt: messageCreatedAt,
});
markThreadSendSettled(threadIdForSend);
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
@@ -3091,34 +3007,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
}
sendInFlightRef.current = false;
} catch (err) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
clearThreadSend(threadIdForSend);
setThreadError(
threadIdForSend,
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetSendPhase();
}
sendInFlightRef.current = false;
},
[
activeThread,
activeProposedPlan,
beginSendPhase,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
setComposerDraftInteractionMode,
setThreadError,
selectedModel,
@@ -3134,7 +3049,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
!activeProposedPlan ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return;
@@ -3155,14 +3069,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginSendPhase("sending-turn");
const finish = () => {
sendInFlightRef.current = false;
resetSendPhase();
};
beginThreadSend(activeThread.id, "sending-turn", createdAt);
await api.orchestration
.dispatchCommand({
try {
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: nextThreadId,
@@ -3174,72 +3084,75 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
createdAt,
})
.then(() => {
return api.orchestration.dispatchCommand({
type: "thread.turn.start",
});
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
moveThreadSend(activeThread.id, nextThreadId);
markThreadSendSettled(nextThreadId);
const snapshot = await api.orchestration.getSnapshot();
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
await navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
} catch (err) {
clearThreadSend(activeThread.id);
clearThreadSend(nextThreadId);
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: nextThreadId,
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
})
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
})
.catch(async (err) => {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
})
.then(finish, finish);
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
}
sendInFlightRef.current = false;
}, [
activeProject,
activeProposedPlan,
activeThread,
beginSendPhase,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
moveThreadSend,
syncServerReadModel,
selectedModel,
]);
@@ -3630,18 +3543,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
}
const headerWorkspaceUnavailableReason = missingProjectWorkspace
? workspaceUnavailableReason({
state: activeProject?.workspaceState ?? "available",
kind: "project",
})
: missingWorktreeWorkspace
? workspaceUnavailableReason({
state: activeThread.effectiveCwdState,
kind: "worktree",
})
: null;
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
{/* Top bar */}
@@ -3656,15 +3557,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
isGitRepo={isGitRepo}
workspaceUnavailableReason={headerWorkspaceUnavailableReason}
openInCwd={gitCwd}
activeProjectScripts={projectWorkspaceAvailable ? activeProject?.scripts : undefined}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined && threadWorkspaceAvailable}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalState.terminalOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
@@ -3687,52 +3587,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
error={activeThread.error}
onDismiss={() => setThreadError(activeThread.id, null)}
/>
{missingProjectWorkspace && activeProject && (
<div className="border-b border-amber-200/70 bg-amber-50 px-3 py-3 text-amber-950 sm:px-5 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100">
<div className="flex flex-wrap items-center gap-3">
<div className="flex-1 text-sm">
<div className="font-medium">Project folder is missing</div>
<div className="text-xs text-amber-900/80 dark:text-amber-200/80">
{workspaceUnavailableReason({
state: activeProject.workspaceState,
kind: "project",
})}
</div>
</div>
<Button size="sm" variant="outline" onClick={() => void relinkProjectWorkspace()}>
Relink project
</Button>
<Button size="sm" variant="outline" onClick={() => void removeActiveProject()}>
Remove project
</Button>
</div>
</div>
)}
{missingWorktreeWorkspace && activeThread && (
<div className="border-b border-amber-200/70 bg-amber-50 px-3 py-3 text-amber-950 sm:px-5 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100">
<div className="flex flex-wrap items-center gap-3">
<div className="flex-1 text-sm">
<div className="font-medium">Worktree is missing</div>
<div className="text-xs text-amber-900/80 dark:text-amber-200/80">
{workspaceUnavailableReason({
state: activeThread.effectiveCwdState,
kind: "worktree",
})}
</div>
</div>
<Button size="sm" variant="outline" onClick={() => void useProjectRootForThread()}>
Use project root
</Button>
<Button
size="sm"
variant="outline"
onClick={() => void confirmAndDeleteThread(activeThread.id)}
>
Delete thread
</Button>
</div>
</div>
)}
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 min-w-0 flex-1">
{/* Chat column */}
@@ -3776,9 +3630,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={
projectWorkspaceAvailable ? (activeProject?.cwd ?? undefined) : undefined
}
workspaceRoot={activeProject?.cwd ?? undefined}
/>
</div>
@@ -3968,7 +3820,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={isConnecting || isComposerApprovalState}
disabled={showConnectingState || isComposerApprovalState}
/>
</div>
@@ -4193,9 +4045,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-full px-4 sm:h-8"
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || showConnectingState}
>
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Refine"}
</Button>
) : (
<div className="flex items-center">
@@ -4203,9 +4059,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || showConnectingState}
>
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Implement"}
</Button>
<Menu>
<MenuTrigger
@@ -4215,7 +4075,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
variant="default"
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
aria-label="Implementation actions"
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || showConnectingState}
/>
}
>
@@ -4223,7 +4083,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || showConnectingState}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -4237,19 +4097,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={
isSendBusy || isConnecting || !composerSendState.hasSendableContent
isSendBusy ||
showConnectingState ||
!composerSendState.hasSendableContent
}
aria-label={
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
isPreparingWorktree
? "Preparing worktree"
: showConnectingState
? "Connecting"
: isSendBusy
? "Sending"
: "Send message"
}
>
{isConnecting || isSendBusy ? (
{showConnectingState || isSendBusy ? (
<svg
width="14"
height="14"
@@ -4330,9 +4192,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={
projectWorkspaceAvailable ? (activeProject?.cwd ?? undefined) : undefined
}
workspaceRoot={activeProject?.cwd ?? undefined}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
@@ -4348,14 +4208,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* end horizontal flex container */}
{(() => {
if (!terminalState.terminalOpen || !activeProject || !threadWorkspaceAvailable || !gitCwd) {
if (!terminalState.terminalOpen || !activeProject) {
return null;
}
return (
<ThreadTerminalDrawer
key={activeThread.id}
threadId={activeThread.id}
cwd={gitCwd}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: NOW_ISO,
models: [],
},
@@ -76,7 +76,6 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -100,9 +99,6 @@ function createMinimalSnapshot(): OrchestrationReadModel {
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
effectiveCwd: "/repo/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
+90 -5
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
createThreadJumpHintVisibilityController,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -15,6 +16,7 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import {
@@ -52,6 +54,68 @@ describe("hasUnseenCompletion", () => {
});
});
describe("createThreadJumpHintVisibilityController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delays showing jump hints until the configured delay elapses", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
expect(visibilityChanges).toEqual([]);
vi.advanceTimersByTime(1);
expect(visibilityChanges).toEqual([true]);
});
it("hides immediately when the modifiers are released", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
controller.sync(false);
expect(visibilityChanges).toEqual([true, false]);
});
it("cancels a pending reveal when the modifier is released early", () => {
const visibilityChanges: boolean[] = [];
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
visibilityChanges.push(visible);
},
});
controller.sync(true);
vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
controller.sync(false);
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
expect(visibilityChanges).toEqual([]);
});
});
describe("shouldClearThreadSelectionOnMouseDown", () => {
it("preserves selection for thread items", () => {
const child = {
@@ -171,6 +235,27 @@ describe("getVisibleSidebarThreadIds", () => {
ThreadId.makeUnsafe("thread-6"),
]);
});
it("skips threads from collapsed projects whose thread panels are not shown", () => {
expect(
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
});
});
describe("isContextMenuPointerDown", () => {
@@ -429,6 +514,9 @@ describe("getVisibleThreadsForProject", () => {
ThreadId.makeUnsafe("thread-6"),
ThreadId.makeUnsafe("thread-8"),
]);
expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-7"),
]);
});
it("returns all threads when the list is expanded", () => {
@@ -449,6 +537,7 @@ describe("getVisibleThreadsForProject", () => {
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
expect(result.hiddenThreads).toEqual([]);
});
});
@@ -458,7 +547,6 @@ function makeProject(overrides: Partial<Project> = {}): Project {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -495,9 +583,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
turnDiffSummaries: [],
activities: [],
...overrides,
+96 -1
View File
@@ -1,3 +1,4 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
@@ -8,6 +9,7 @@ import {
} from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
@@ -46,6 +48,91 @@ type ThreadStatusInput = Pick<
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export interface ThreadJumpHintVisibilityController {
sync: (shouldShow: boolean) => void;
dispose: () => void;
}
export function createThreadJumpHintVisibilityController(input: {
delayMs: number;
onVisibilityChange: (visible: boolean) => void;
setTimeoutFn?: typeof globalThis.setTimeout;
clearTimeoutFn?: typeof globalThis.clearTimeout;
}): ThreadJumpHintVisibilityController {
const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
let isVisible = false;
let timeoutId: NodeJS.Timeout | null = null;
const clearPendingShow = () => {
if (timeoutId === null) {
return;
}
clearTimeoutFn(timeoutId);
timeoutId = null;
};
return {
sync: (shouldShow) => {
if (!shouldShow) {
clearPendingShow();
if (isVisible) {
isVisible = false;
input.onVisibilityChange(false);
}
return;
}
if (isVisible || timeoutId !== null) {
return;
}
timeoutId = setTimeoutFn(() => {
timeoutId = null;
isVisible = true;
input.onVisibilityChange(true);
}, input.delayMs);
},
dispose: () => {
clearPendingShow();
},
};
}
export function useThreadJumpHintVisibility(): {
showThreadJumpHints: boolean;
updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
} {
const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
React.useEffect(() => {
const controller = createThreadJumpHintVisibilityController({
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
onVisibilityChange: (visible) => {
setShowThreadJumpHints(visible);
},
setTimeoutFn: window.setTimeout.bind(window),
clearTimeoutFn: window.clearTimeout.bind(window),
});
controllerRef.current = controller;
return () => {
controller.dispose();
controllerRef.current = null;
};
}, []);
const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
controllerRef.current?.sync(shouldShow);
}, []);
return {
showThreadJumpHints,
updateThreadJumpHintsVisibility,
};
}
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
@@ -71,13 +158,16 @@ export function resolveSidebarNewThreadEnvMode(input: {
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
);
}
@@ -244,6 +334,7 @@ export function getVisibleThreadsForProject(input: {
previewLimit: number;
}): {
hasHiddenThreads: boolean;
hiddenThreads: Thread[];
visibleThreads: Thread[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
@@ -252,6 +343,7 @@ export function getVisibleThreadsForProject(input: {
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
hiddenThreads: [],
visibleThreads: [...threads],
};
}
@@ -260,6 +352,7 @@ export function getVisibleThreadsForProject(input: {
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -268,6 +361,7 @@ export function getVisibleThreadsForProject(input: {
if (!activeThread) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -276,6 +370,7 @@ export function getVisibleThreadsForProject(input: {
return {
hasHiddenThreads: true,
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
+194 -123
View File
@@ -69,6 +69,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useThreadActions } from "../hooks/useThreadActions";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
@@ -116,11 +117,11 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
useThreadJumpHintVisibility,
} from "./Sidebar.logic";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { isProjectWorkspaceAvailable, isThreadWorkspaceAvailable } from "../workspaceAvailability";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -152,6 +153,44 @@ interface PrStatusIndicator {
type ThreadPr = GitStatusResult["pr"];
function ThreadStatusLabel({
status,
compact = false,
}: {
status: NonNullable<ReturnType<typeof resolveThreadStatusPill>>;
compact?: boolean;
}) {
if (compact) {
return (
<span
title={status.label}
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="sr-only">{status.label}</span>
</span>
);
}
return (
<span
title={status.label}
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
</span>
);
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
@@ -357,14 +396,14 @@ export default function Sidebar() {
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [hoveredThreadId, setHoveredThreadId] = useState<ThreadId | null>(null);
const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState<ThreadId | null>(null);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
const [showThreadJumpHints, setShowThreadJumpHints] = useState(false);
const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<ThreadId, HTMLButtonElement>());
const dragInProgressRef = useRef(false);
const suppressProjectClickAfterDragRef = useRef(false);
const suppressProjectClickForContextMenuRef = useRef(false);
@@ -401,16 +440,15 @@ export default function Sidebar() {
threads.map((thread) => ({
threadId: thread.id,
branch: thread.branch,
cwd: thread.effectiveCwd,
enabled: isThreadWorkspaceAvailable(thread),
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
})),
[threads],
[projectCwdById, threads],
);
const threadGitStatusCwds = useMemo(
() => [
...new Set(
threadGitTargets
.filter((target) => target.enabled && target.branch !== null)
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
@@ -419,7 +457,7 @@ export default function Sidebar() {
);
const threadGitStatusQueries = useQueries({
queries: threadGitStatusCwds.map((cwd) => ({
...gitStatusQueryOptions(cwd, true),
...gitStatusQueryOptions(cwd),
staleTime: 30_000,
refetchInterval: 60_000,
})),
@@ -1025,14 +1063,18 @@ export default function Sidebar() {
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) =>
const threadStatuses = new Map(
projectThreads.map((thread) => [
thread.id,
resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
}),
),
]),
);
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const activeThreadId = routeThreadId ?? undefined;
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
@@ -1041,25 +1083,35 @@ export default function Sidebar() {
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const { hasHiddenThreads, visibleThreads: visibleProjectThreads } =
getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const {
hasHiddenThreads,
hiddenThreads,
visibleThreads: visibleProjectThreads,
} = getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const hiddenThreadStatus = resolveProjectStatusIndicator(
hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
);
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = pinnedCollapsedThread
? [pinnedCollapsedThread]
: visibleProjectThreads;
const showEmptyThreadState = project.expanded && projectThreads.length === 0;
return {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
};
@@ -1072,23 +1124,22 @@ export default function Sidebar() {
visibleThreads,
],
);
const visibleSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const threadJumpCommandById = useMemo(() => {
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
let visibleThreadIndex = 0;
for (const renderedProject of renderedProjects) {
for (const thread of renderedProject.renderedThreads) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(thread.id, jumpCommand);
visibleThreadIndex += 1;
for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(threadId, jumpCommand);
}
return mapping;
}, [renderedProjects]);
}, [visibleSidebarThreadIds]);
const threadJumpThreadIds = useMemo(
() => [...threadJumpCommandById.keys()],
[threadJumpCommandById],
@@ -1103,10 +1154,7 @@ export default function Sidebar() {
}
return mapping;
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
const orderedSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const orderedSidebarThreadIds = visibleSidebarThreadIds;
useEffect(() => {
const getShortcutContext = () => ({
@@ -1115,7 +1163,7 @@ export default function Sidebar() {
});
const onWindowKeyDown = (event: KeyboardEvent) => {
setShowThreadJumpHints(
updateThreadJumpHintsVisibility(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1163,7 +1211,7 @@ export default function Sidebar() {
};
const onWindowKeyUp = (event: KeyboardEvent) => {
setShowThreadJumpHints(
updateThreadJumpHintsVisibility(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1172,7 +1220,7 @@ export default function Sidebar() {
};
const onWindowBlur = () => {
setShowThreadJumpHints(false);
updateThreadJumpHintsVisibility(false);
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1192,6 +1240,7 @@ export default function Sidebar() {
routeTerminalOpen,
routeThreadId,
threadJumpThreadIds,
updateThreadJumpHintsVisibility,
]);
function renderProjectItem(
@@ -1200,54 +1249,63 @@ export default function Sidebar() {
) {
const {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
} = renderedProject;
const projectWorkspaceAvailable = isProjectWorkspaceAvailable(project);
const renderThreadRow = (thread: (typeof projectThreads)[number]) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const threadWorkspaceAvailable = isThreadWorkspaceAvailable(thread);
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
const threadStatus = threadStatuses.get(thread.id) ?? null;
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
);
const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseEnter={() => {
setHoveredThreadId(thread.id);
}}
onMouseLeave={() => {
setHoveredThreadId((current) => (current === thread.id ? null : current));
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
}}
onBlurCapture={(event) => {
const currentTarget = event.currentTarget;
requestAnimationFrame(() => {
if (currentTarget.contains(document.activeElement)) {
return;
}
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
});
}}
>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
data-testid={`thread-row-${thread.id}`}
className={`${resolveThreadRowClassName({
isActive,
isSelected,
})} relative ${threadWorkspaceAvailable ? "" : "opacity-60"}`}
})} relative isolate`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
@@ -1258,7 +1316,6 @@ export default function Sidebar() {
}}
onContextMenu={(event) => {
event.preventDefault();
setHoveredThreadId((current) => (current === thread.id ? null : current));
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
@@ -1295,18 +1352,7 @@ export default function Sidebar() {
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
@@ -1356,10 +1402,18 @@ export default function Sidebar() {
</span>
)}
<div className="flex min-w-12 justify-end">
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
{isConfirmingArchive ? (
<button
ref={(element) => {
if (element) {
confirmArchiveButtonRefs.current.set(thread.id, element);
} else {
confirmArchiveButtonRefs.current.delete(thread.id);
}
}}
type="button"
data-thread-selection-safe
data-testid={`thread-archive-confirm-${thread.id}`}
aria-label={`Confirm archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
onPointerDown={(event) => {
@@ -1371,80 +1425,84 @@ export default function Sidebar() {
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
setHoveredThreadId((current) => (current === thread.id ? null : current));
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : hoveredThreadId === thread.id && !isThreadRunning ? (
) : !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
});
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
) : (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setHoveredThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
</div>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : (
<>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</>
)}
) : null}
<span className={threadMetaClassName}>
{showThreadJumpHints && jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</span>
</div>
</div>
</SidebarMenuSubButton>
@@ -1460,7 +1518,7 @@ export default function Sidebar() {
size="sm"
className={`gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground ${
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
} ${projectWorkspaceAvailable ? "" : "opacity-60"}`}
}`}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}
onPointerDownCapture={handleProjectTitlePointerDownCapture}
@@ -1539,6 +1597,16 @@ export default function Sidebar() {
ref={attachThreadListAutoAnimateRef}
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
>
{shouldShowThreadPanel && showEmptyThreadState ? (
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
<div
data-thread-selection-safe
className="flex h-6 w-full translate-x-0 items-center px-2 text-left text-[10px] text-muted-foreground/60"
>
<span>No threads yet</span>
</div>
</SidebarMenuSubItem>
) : null}
{shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))}
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
@@ -1552,7 +1620,10 @@ export default function Sidebar() {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
<span className="flex min-w-0 flex-1 items-center gap-2">
{hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />}
<span>Show more</span>
</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
@@ -50,6 +50,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
<div key={`dir:${node.path}`}>
<button
type="button"
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
+7 -16
View File
@@ -19,7 +19,6 @@ interface ChatHeaderProps {
activeThreadTitle: string;
activeProjectName: string | undefined;
isGitRepo: boolean;
workspaceUnavailableReason?: string | null;
openInCwd: string | null;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
@@ -44,7 +43,6 @@ export const ChatHeader = memo(function ChatHeader({
activeThreadTitle,
activeProjectName,
isGitRepo,
workspaceUnavailableReason,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -78,16 +76,11 @@ export const ChatHeader = memo(function ChatHeader({
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
{activeProjectName &&
(workspaceUnavailableReason ? (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
Workspace Missing
</Badge>
) : !isGitRepo ? (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
</Badge>
) : null)}
{activeProjectName && !isGitRepo && (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
</Badge>
)}
</div>
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
{activeProjectScripts && (
@@ -127,8 +120,7 @@ export const ChatHeader = memo(function ChatHeader({
/>
<TooltipPopup side="bottom">
{!terminalAvailable
? (workspaceUnavailableReason ??
"Terminal is unavailable until this thread has an active project.")
? "Terminal is unavailable until this thread has an active project."
: terminalToggleShortcutLabel
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
@@ -152,8 +144,7 @@ export const ChatHeader = memo(function ChatHeader({
/>
<TooltipPopup side="bottom">
{!isGitRepo
? (workspaceUnavailableReason ??
"Diff panel is unavailable because this project is not a git repository.")
? "Diff panel is unavailable because this project is not a git repository."
: diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
@@ -1,5 +1,5 @@
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
import { memo } from "react";
import { memo, useLayoutEffect, useRef } from "react";
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
import { BotIcon } from "lucide-react";
import { cn } from "~/lib/utils";
@@ -41,8 +41,19 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
const listRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (!props.activeItemId || !listRef.current) return;
const el = listRef.current.querySelector<HTMLElement>(
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
);
el?.scrollIntoView({ block: "nearest" });
}, [props.activeItemId]);
return (
<Command
autoHighlight={false}
mode="none"
onItemHighlighted={(highlightedValue) => {
props.onHighlightedItemChange(
@@ -50,7 +61,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
<div
ref={listRef}
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<CommandList className="max-h-64">
{props.items.map((item) => (
<ComposerCommandMenuItem
@@ -58,6 +72,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
@@ -80,15 +95,20 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
item: ComposerCommandItem;
resolvedTheme: "light" | "dark";
isActive: boolean;
onHighlight: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
return (
<CommandItem
value={props.item.id}
data-composer-item-id={props.item.id}
className={cn(
"cursor-pointer select-none gap-2",
props.isActive && "bg-accent text-accent-foreground",
"cursor-pointer select-none gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
props.isActive && "bg-accent! text-accent-foreground!",
)}
onMouseMove={() => {
if (!props.isActive) props.onHighlight(props.item.id);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -264,9 +264,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
rowVirtualizer.measure();
}, [rowVirtualizer, timelineWidthPx]);
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const itemIntersectsViewport =
item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
if (itemIntersectsViewport) {
return false;
}
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
@@ -483,6 +488,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
@@ -543,9 +549,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
<span>
{row.createdAt
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
: "Working..."}
{(() => {
const elapsed = row.createdAt ? formatWorkingTimer(row.createdAt, nowIso) : null;
return elapsed ? `Working for ${elapsed}` : "Working...";
})()}
</span>
</div>
</div>
@@ -637,6 +644,9 @@ function formatWorkingTimer(startIso: string, endIso: string): string | null {
}
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
if (elapsedSeconds < 1) {
return null;
}
if (elapsedSeconds < 60) {
return `${elapsedSeconds}s`;
}
@@ -22,7 +22,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models: [
{
@@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "1.0.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models: [
{
@@ -110,6 +110,19 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
},
];
function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {
return {
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: new Date().toISOString(),
models,
};
}
async function mountPicker(props: {
provider: ProviderKind;
model: string;
@@ -241,6 +254,93 @@ describe("ProviderModelPicker", () => {
}
});
it("only shows codex spark when the server reports it for the account", async () => {
const providersWithoutSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const providersWithSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "GPT-5.3 Codex Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]),
TEST_PROVIDERS[1]!,
];
const hidden = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithoutSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("GPT-5.3 Codex");
expect(text).not.toContain("GPT-5.3 Codex Spark");
});
} finally {
await hidden.cleanup();
}
const visible = await mountPicker({
provider: "claudeAgent",
model: "claude-opus-4-6",
lockedProvider: null,
providers: providersWithSpark,
});
try {
await page.getByRole("button").click();
await page.getByRole("menuitem", { name: "Codex" }).hover();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark");
});
} finally {
await visible.cleanup();
}
});
it("dispatches the canonical slug when a model is selected", async () => {
const mounted = await mountPicker({
provider: "claudeAgent",
@@ -35,7 +35,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -61,7 +61,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -71,6 +71,41 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
describe("getComposerProviderState", () => {
it("returns codex defaults when no codex draft options exist", () => {
const state = getComposerProviderState({
@@ -156,6 +191,7 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: false,
},
});
});
@@ -268,7 +304,116 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
fastMode: false,
},
});
});
it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => {
// Regression: normalizeClaudeModelOptionsWithCapabilities used to strip
// fastMode: false, which meant deepMerge could never clear a previous true.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: false,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => {
// Regression: thinking: true (the default) used to be stripped, which
// meant deepMerge could never clear a previous thinking: false.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
thinking: true,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default context window explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toMatchObject({
effort: "high",
contextWindow: "200k",
});
});
it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => {
// Regression: the default contextWindow must survive normalization so
// deepMerge can clear an older non-default 1m selection.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k");
});
it("omits contextWindow when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "1m",
},
},
});
expect(state.modelOptionsForDispatch).toBeUndefined();
});
it("omits fastMode when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: true,
},
},
});
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
});
});
@@ -6,12 +6,12 @@ import {
} from "@t3tools/contracts";
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
import type { ReactNode } from "react";
import { getProviderModelCapabilities } from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
import {
getProviderModelCapabilities,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
} from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
} from "@t3tools/shared/model";
export type ComposerProviderStateInput = {
provider: ProviderKind;
@@ -146,13 +146,14 @@ function getProviderSummary(provider: ServerProvider | undefined) {
detail: provider.message ?? "CLI not detected on PATH.",
};
}
if (provider.authStatus === "authenticated") {
if (provider.auth.status === "authenticated") {
const authLabel = provider.auth.label ?? provider.auth.type;
return {
headline: "Authenticated",
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
detail: provider.message ?? null,
};
}
if (provider.authStatus === "unauthenticated") {
if (provider.auth.status === "unauthenticated") {
return {
headline: "Not authenticated",
detail: provider.message ?? null,
+1 -1
View File
@@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti
return (
<AutocompletePrimitive.Item
className={cn(
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
className,
)}
data-slot="autocomplete-item"
+1 -1
View File
@@ -195,7 +195,7 @@ function ComboboxItem({
return (
<ComboboxPrimitive.Item
className={cn(
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
data-slot="combobox-item"
+1 -5
View File
@@ -14,7 +14,6 @@ import { useTerminalStateStore } from "../terminalStateStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
import { isProjectWorkspaceAvailable } from "../workspaceAvailability";
export function useThreadActions() {
const threads = useStore((store) => store.threads);
@@ -83,10 +82,7 @@ export function useThreadActions() {
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree =
orphanedWorktreePath !== null &&
threadProject !== undefined &&
isProjectWorkspaceAvailable(threadProject);
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
+9 -10
View File
@@ -26,7 +26,7 @@ export function invalidateGitQueries(queryClient: QueryClient) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function gitStatusQueryOptions(cwd: string | null, enabled = true) {
export function gitStatusQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.status(cwd),
queryFn: async () => {
@@ -34,15 +34,15 @@ export function gitStatusQueryOptions(cwd: string | null, enabled = true) {
if (!cwd) throw new Error("Git status is unavailable.");
return api.git.status({ cwd });
},
enabled: enabled && cwd !== null,
enabled: cwd !== null,
staleTime: GIT_STATUS_STALE_TIME_MS,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
});
}
export function gitBranchesQueryOptions(cwd: string | null, enabled = true) {
export function gitBranchesQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.branches(cwd),
queryFn: async () => {
@@ -50,10 +50,10 @@ export function gitBranchesQueryOptions(cwd: string | null, enabled = true) {
if (!cwd) throw new Error("Git branches are unavailable.");
return api.git.listBranches({ cwd });
},
enabled: enabled && cwd !== null,
enabled: cwd !== null,
staleTime: GIT_BRANCHES_STALE_TIME_MS,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
});
}
@@ -61,7 +61,6 @@ export function gitBranchesQueryOptions(cwd: string | null, enabled = true) {
export function gitResolvePullRequestQueryOptions(input: {
cwd: string | null;
reference: string | null;
enabled?: boolean;
}) {
return queryOptions({
queryKey: ["git", "pull-request", input.cwd, input.reference] as const,
@@ -72,7 +71,7 @@ export function gitResolvePullRequestQueryOptions(input: {
}
return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
},
enabled: (input.enabled ?? true) && input.cwd !== null && input.reference !== null,
enabled: input.cwd !== null && input.reference !== null,
staleTime: 30_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
-2
View File
@@ -39,7 +39,5 @@ export function projectSearchEntriesQueryOptions(input: {
enabled: (input.enabled ?? true) && input.cwd !== null && input.query.length > 0,
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
}
+1 -36
View File
@@ -1,13 +1,11 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import { normalizeModelSlug } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -69,36 +67,3 @@ export function getDefaultServerModel(
DEFAULT_MODEL_BY_PROVIDER[provider]
);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
-15
View File
@@ -26,7 +26,6 @@ import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { gitQueryKeys } from "../lib/gitReactQuery";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -172,10 +171,6 @@ function EventRouter() {
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
await Promise.all([
queryClient.invalidateQueries({ queryKey: gitQueryKeys.all }),
queryClient.invalidateQueries({ queryKey: projectQueryKeys.all }),
]);
if (pending) {
pending = false;
await flushSnapshotSync();
@@ -266,14 +261,6 @@ function EventRouter() {
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
})().catch(() => undefined);
});
const handleWorkspaceRefresh = () => {
if (document.visibilityState === "hidden") {
return;
}
void syncSnapshot();
};
window.addEventListener("focus", handleWorkspaceRefresh);
document.addEventListener("visibilitychange", handleWorkspaceRefresh);
// onServerConfigUpdated replays the latest cached value synchronously
// during subscribe. Skip the toast for that replay so effect re-runs
// don't produce duplicate toasts.
@@ -336,8 +323,6 @@ function EventRouter() {
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
window.removeEventListener("focus", handleWorkspaceRefresh);
document.removeEventListener("visibilitychange", handleWorkspaceRefresh);
unsubServerConfigUpdated();
unsubProvidersUpdated();
};
+158 -15
View File
@@ -7,7 +7,16 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
import {
beginThreadSend,
clearThreadSend,
markThreadUnread,
markThreadSendSettled,
reorderProjects,
setThreadSendPhase,
syncServerReadModel,
type AppState,
} from "./store";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -33,21 +42,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
...overrides,
};
}
function makeState(thread: Thread): AppState {
return {
pendingThreadSendById: {},
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -74,9 +80,6 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
interactionMode: DEFAULT_INTERACTION_MODE,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
@@ -100,7 +103,6 @@ function makeReadModel(thread: OrchestrationReadModel["threads"][number]): Orche
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -122,7 +124,6 @@ function makeReadModelProject(
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -180,12 +181,12 @@ describe("store pure functions", () => {
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const state: AppState = {
pendingThreadSendById: {},
projects: [
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -197,7 +198,6 @@ describe("store pure functions", () => {
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -209,7 +209,6 @@ describe("store pure functions", () => {
id: project3,
name: "Project 3",
cwd: "/tmp/project-3",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -304,12 +303,12 @@ describe("store read model sync", () => {
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState: AppState = {
pendingThreadSendById: {},
projects: [
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -321,7 +320,6 @@ describe("store read model sync", () => {
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
@@ -360,4 +358,149 @@ describe("store read model sync", () => {
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
});
it("keeps pending sends until the server catches up to the send", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:00:59.000Z",
startedAt: "2026-02-27T00:01:01.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
});
});
it("does not clear pending sends when the turn appears before the request settles", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
});
});
it("clears pending sends once the server session starts running", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
session: {
threadId,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:01:02.000Z",
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
});
it("clears settled pending sends once the turn has caught up", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = markThreadSendSettled(
beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
),
threadId,
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
});
});
describe("store pending thread send helpers", () => {
it("updates and clears pending thread send state", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const startedState = beginThreadSend(
makeState(makeThread()),
threadId,
"preparing-worktree",
"2026-02-27T00:01:00.000Z",
);
const sendingState = setThreadSendPhase(startedState, threadId, "sending-turn");
const settledState = markThreadSendSettled(sendingState, threadId);
const clearedState = clearThreadSend(settledState, threadId);
expect(startedState.pendingThreadSendById[threadId]?.phase).toBe("preparing-worktree");
expect(startedState.pendingThreadSendById[threadId]?.requestSettled).toBe(false);
expect(sendingState.pendingThreadSendById[threadId]?.phase).toBe("sending-turn");
expect(settledState.pendingThreadSendById[threadId]?.requestSettled).toBe(true);
expect(clearedState.pendingThreadSendById[threadId]).toBeUndefined();
});
});
+196 -5
View File
@@ -7,12 +7,19 @@ import {
} from "@t3tools/contracts";
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
import { create } from "zustand";
import { type ChatMessage, type Project, type Thread } from "./types";
import {
type ChatMessage,
type PendingThreadSend,
type PendingThreadSendPhase,
type Project,
type Thread,
} from "./types";
import { Debouncer } from "@tanstack/react-pacer";
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
pendingThreadSendById: Record<ThreadId, PendingThreadSend | undefined>;
projects: Project[];
threads: Thread[];
threadsHydrated: boolean;
@@ -32,6 +39,7 @@ const LEGACY_PERSISTED_STATE_KEYS = [
] as const;
const initialState: AppState = {
pendingThreadSendById: {},
projects: [],
threads: [],
threadsHydrated: false,
@@ -111,6 +119,71 @@ function updateThread(
return changed ? next : threads;
}
function hasLatestTurnCaughtUpToPendingSend(
latestTurnRequestedAt: string | null,
pendingSendStartedAt: string,
): boolean {
if (latestTurnRequestedAt === null) {
return false;
}
const latestTurnRequestedAtMs = Date.parse(latestTurnRequestedAt);
const pendingSendStartedAtMs = Date.parse(pendingSendStartedAt);
if (Number.isNaN(latestTurnRequestedAtMs) || Number.isNaN(pendingSendStartedAtMs)) {
return false;
}
return latestTurnRequestedAtMs >= pendingSendStartedAtMs;
}
function reconcilePendingThreadSends(
pendingThreadSendById: AppState["pendingThreadSendById"],
readModel: OrchestrationReadModel,
): AppState["pendingThreadSendById"] {
const readModelThreadById = new Map(
readModel.threads.map((thread) => [thread.id, thread] as const),
);
let changed = false;
const nextPendingThreadSendById: AppState["pendingThreadSendById"] = {};
for (const [threadId, pendingSend] of Object.entries(pendingThreadSendById) as Array<
[ThreadId, PendingThreadSend | undefined]
>) {
if (!pendingSend) {
continue;
}
const thread = readModelThreadById.get(threadId);
if (!thread) {
nextPendingThreadSendById[threadId] = pendingSend;
continue;
}
const authoritativeSendStarted = thread.session?.status === "running";
const authoritativeSendFailed = thread.session?.lastError != null;
const latestTurnCaughtUp = hasLatestTurnCaughtUpToPendingSend(
thread.latestTurn?.requestedAt ?? null,
pendingSend.startedAt,
);
if (
authoritativeSendStarted ||
authoritativeSendFailed ||
(pendingSend.requestSettled && latestTurnCaughtUp)
) {
changed = true;
continue;
}
nextPendingThreadSendById[threadId] = pendingSend;
}
if (
!changed &&
Object.keys(nextPendingThreadSendById).length === Object.keys(pendingThreadSendById).length
) {
return pendingThreadSendById;
}
return nextPendingThreadSendById;
}
function mapProjectsFromReadModel(
incoming: OrchestrationReadModel["projects"],
previous: Project[],
@@ -132,7 +205,6 @@ function mapProjectsFromReadModel(
id: project.id,
name: project.title,
cwd: project.workspaceRoot,
workspaceState: project.workspaceState,
defaultModelSelection:
existing?.defaultModelSelection ??
(project.defaultModelSelection
@@ -306,9 +378,6 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
effectiveCwd: thread.effectiveCwd,
effectiveCwdSource: thread.effectiveCwdSource,
effectiveCwdState: thread.effectiveCwdState,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
@@ -323,12 +392,121 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
});
return {
...state,
pendingThreadSendById: reconcilePendingThreadSends(state.pendingThreadSendById, readModel),
projects,
threads,
threadsHydrated: true,
};
}
export function beginThreadSend(
state: AppState,
threadId: ThreadId,
phase: PendingThreadSendPhase,
startedAt: string,
): AppState {
const existing = state.pendingThreadSendById[threadId];
if (
existing?.phase === phase &&
existing.startedAt === startedAt &&
existing.requestSettled === false
) {
return state;
}
return {
...state,
pendingThreadSendById: {
...state.pendingThreadSendById,
[threadId]: { phase, startedAt, requestSettled: false },
},
};
}
export function setThreadSendPhase(
state: AppState,
threadId: ThreadId,
phase: PendingThreadSendPhase,
): AppState {
const existing = state.pendingThreadSendById[threadId];
if (!existing || existing.phase === phase) {
return state;
}
return {
...state,
pendingThreadSendById: {
...state.pendingThreadSendById,
[threadId]: {
...existing,
phase,
},
},
};
}
export function markThreadSendSettled(state: AppState, threadId: ThreadId): AppState {
const existing = state.pendingThreadSendById[threadId];
if (!existing) {
return state;
}
const thread = state.threads.find((candidate) => candidate.id === threadId) ?? null;
const authoritativeSendStarted = thread?.session?.orchestrationStatus === "running";
const authoritativeSendFailed = thread?.session?.lastError != null;
const latestTurnCaughtUp = hasLatestTurnCaughtUpToPendingSend(
thread?.latestTurn?.requestedAt ?? null,
existing.startedAt,
);
if (authoritativeSendStarted || authoritativeSendFailed || latestTurnCaughtUp) {
return clearThreadSend(state, threadId);
}
if (existing.requestSettled) {
return state;
}
return {
...state,
pendingThreadSendById: {
...state.pendingThreadSendById,
[threadId]: {
...existing,
requestSettled: true,
},
},
};
}
export function clearThreadSend(state: AppState, threadId: ThreadId): AppState {
if (!(threadId in state.pendingThreadSendById)) {
return state;
}
const pendingThreadSendById = { ...state.pendingThreadSendById };
delete pendingThreadSendById[threadId];
return {
...state,
pendingThreadSendById,
};
}
export function moveThreadSend(
state: AppState,
fromThreadId: ThreadId,
toThreadId: ThreadId,
): AppState {
if (fromThreadId === toThreadId) {
return state;
}
const pendingSend = state.pendingThreadSendById[fromThreadId];
if (!pendingSend) {
return state;
}
const pendingThreadSendById = { ...state.pendingThreadSendById };
delete pendingThreadSendById[fromThreadId];
pendingThreadSendById[toThreadId] = pendingSend;
return {
...state,
pendingThreadSendById,
};
}
export function markThreadVisited(
state: AppState,
threadId: ThreadId,
@@ -429,6 +607,10 @@ export function setThreadBranch(
// ── Zustand store ────────────────────────────────────────────────────
interface AppStore extends AppState {
beginThreadSend: (threadId: ThreadId, phase: PendingThreadSendPhase, startedAt: string) => void;
clearThreadSend: (threadId: ThreadId) => void;
markThreadSendSettled: (threadId: ThreadId) => void;
moveThreadSend: (fromThreadId: ThreadId, toThreadId: ThreadId) => void;
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId) => void;
@@ -436,11 +618,18 @@ interface AppStore extends AppState {
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadSendPhase: (threadId: ThreadId, phase: PendingThreadSendPhase) => void;
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
}
export const useStore = create<AppStore>((set) => ({
...readPersistedState(),
beginThreadSend: (threadId, phase, startedAt) =>
set((state) => beginThreadSend(state, threadId, phase, startedAt)),
clearThreadSend: (threadId) => set((state) => clearThreadSend(state, threadId)),
markThreadSendSettled: (threadId) => set((state) => markThreadSendSettled(state, threadId)),
moveThreadSend: (fromThreadId, toThreadId) =>
set((state) => moveThreadSend(state, fromThreadId, toThreadId)),
syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
@@ -451,6 +640,8 @@ export const useStore = create<AppStore>((set) => ({
reorderProjects: (draggedProjectId, targetProjectId) =>
set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
setThreadSendPhase: (threadId, phase) =>
set((state) => setThreadSendPhase(state, threadId, phase)),
setThreadBranch: (threadId, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
}));
+7 -6
View File
@@ -13,11 +13,10 @@ import type {
CheckpointRef,
ProviderInteractionMode,
RuntimeMode,
WorkspaceAvailabilityState,
ThreadEffectiveCwdSource,
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type PendingThreadSendPhase = "preparing-worktree" | "sending-turn";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_INTERACTION_MODE: ProviderInteractionMode = "default";
@@ -83,7 +82,6 @@ export interface Project {
id: ProjectId;
name: string;
cwd: string;
workspaceState: WorkspaceAvailabilityState;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
@@ -110,9 +108,6 @@ export interface Thread {
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
effectiveCwd: string | null;
effectiveCwdSource: ThreadEffectiveCwdSource | null;
effectiveCwdState: WorkspaceAvailabilityState;
turnDiffSummaries: TurnDiffSummary[];
activities: OrchestrationThreadActivity[];
}
@@ -126,3 +121,9 @@ export interface ThreadSession {
lastError?: string;
orchestrationStatus: OrchestrationSessionStatus;
}
export interface PendingThreadSend {
phase: PendingThreadSendPhase;
startedAt: string;
requestSettled: boolean;
}
-35
View File
@@ -1,35 +0,0 @@
import type { Project, Thread } from "./types";
export function isWorkspaceStateAvailable(
state: Project["workspaceState"] | Thread["effectiveCwdState"],
): boolean {
return state === "available";
}
export function isProjectWorkspaceAvailable(project: Pick<Project, "workspaceState">): boolean {
return isWorkspaceStateAvailable(project.workspaceState);
}
export function isThreadWorkspaceAvailable(thread: Pick<Thread, "effectiveCwdState">): boolean {
return isWorkspaceStateAvailable(thread.effectiveCwdState);
}
export function workspaceUnavailableReason(input: {
state: Project["workspaceState"] | Thread["effectiveCwdState"];
kind: "project" | "worktree";
}): string | null {
if (input.state === "available") {
return null;
}
const subject = input.kind === "project" ? "Project folder" : "Worktree";
switch (input.state) {
case "missing":
return `${subject} is missing.`;
case "not_directory":
return `${subject} path is not a folder.`;
case "inaccessible":
default:
return `${subject} is inaccessible.`;
}
}
-3
View File
@@ -27,9 +27,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
latestTurn: null,
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project",
effectiveCwdSource: "project",
effectiveCwdState: "available",
...overrides,
};
}
+1 -1
View File
@@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
-21
View File
@@ -141,24 +141,10 @@ export const ProjectScript = Schema.Struct({
});
export type ProjectScript = typeof ProjectScript.Type;
export const WorkspaceAvailabilityState = Schema.Literals([
"available",
"missing",
"not_directory",
"inaccessible",
]);
export type WorkspaceAvailabilityState = typeof WorkspaceAvailabilityState.Type;
export const ThreadEffectiveCwdSource = Schema.Literals(["project", "worktree"]);
export type ThreadEffectiveCwdSource = typeof ThreadEffectiveCwdSource.Type;
export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
workspaceState: WorkspaceAvailabilityState.pipe(
Schema.withDecodingDefault(() => "available" as const),
),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -295,13 +281,6 @@ export const OrchestrationThread = Schema.Struct({
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
effectiveCwd: Schema.NullOr(TrimmedNonEmptyString).pipe(Schema.withDecodingDefault(() => null)),
effectiveCwdSource: Schema.NullOr(ThreadEffectiveCwdSource).pipe(
Schema.withDecodingDefault(() => null),
),
effectiveCwdState: WorkspaceAvailabilityState.pipe(
Schema.withDecodingDefault(() => "available" as const),
),
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
+8 -1
View File
@@ -35,6 +35,13 @@ export const ServerProviderAuthStatus = Schema.Literals([
]);
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
export const ServerProviderAuth = Schema.Struct({
status: ServerProviderAuthStatus,
type: Schema.optional(TrimmedNonEmptyString),
label: Schema.optional(TrimmedNonEmptyString),
});
export type ServerProviderAuth = typeof ServerProviderAuth.Type;
export const ServerProviderModel = Schema.Struct({
slug: TrimmedNonEmptyString,
name: TrimmedNonEmptyString,
@@ -49,7 +56,7 @@ export const ServerProvider = Schema.Struct({
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
status: ServerProviderState,
authStatus: ServerProviderAuthStatus,
auth: ServerProviderAuth,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
models: Schema.Array(ServerProviderModel),
-8
View File
@@ -1,8 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
describe("DEFAULT_CLIENT_SETTINGS", () => {
it("includes archive confirmation with a false default", () => {
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
});
});
+1
View File
@@ -112,6 +112,7 @@ const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
});
const ModelSelectionPatch = Schema.Union([
+56
View File
@@ -8,6 +8,8 @@ import {
hasContextWindowOption,
hasEffortLevel,
isClaudeUltrathinkPrompt,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
normalizeModelSlug,
resolveApiModelId,
resolveContextWindow,
@@ -226,3 +228,57 @@ describe("resolveApiModelId", () => {
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
});
});
describe("normalize*ModelOptionsWithCapabilities", () => {
it("preserves explicit false codex fast mode", () => {
expect(
normalizeCodexModelOptionsWithCapabilities(codexCaps, {
reasoningEffort: "high",
fastMode: false,
}),
).toEqual({
reasoningEffort: "high",
fastMode: false,
});
});
it("preserves the default Claude context window explicitly", () => {
expect(
normalizeClaudeModelOptionsWithCapabilities(
{
...claudeCaps,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
},
{
effort: "high",
contextWindow: "200k",
},
),
).toEqual({
effort: "high",
contextWindow: "200k",
});
});
it("omits unsupported Claude context window options", () => {
expect(
normalizeClaudeModelOptionsWithCapabilities(
{
...claudeCaps,
reasoningEffortLevels: [],
supportsThinkingToggle: true,
contextWindowOptions: [],
},
{
thinking: true,
contextWindow: "1m",
},
),
).toEqual({
thinking: true,
});
});
});
+34
View File
@@ -2,6 +2,8 @@ import {
DEFAULT_MODEL_BY_PROVIDER,
MODEL_SLUG_ALIASES_BY_PROVIDER,
type ClaudeCodeEffort,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ModelSelection,
type ProviderKind,
@@ -83,6 +85,38 @@ export function resolveContextWindow(
return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastMode !== undefined ? { fastMode } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined;
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking !== undefined ? { thinking } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
return typeof text === "string" && /\bultrathink\b/i.test(text);
}