Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c3b02fdf | ||
|
|
0cdb35e73b | ||
|
|
935e7c6cea | ||
|
|
439e8bcd42 | ||
|
|
7fa5304e87 | ||
|
|
d358a66439 | ||
|
|
d7257df2ae | ||
|
|
2ade03788b | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 |
No files matched your search
@@ -2,18 +2,42 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
You can also just install the desktop app. It's cooler.
|
||||
### Desktop app
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Some notes
|
||||
|
||||
|
||||
@@ -24,8 +24,7 @@
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
@@ -20,8 +20,10 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolveReady(ready);
|
||||
};
|
||||
|
||||
socket.once("connect", () => {
|
||||
finish(true);
|
||||
});
|
||||
socket.once("timeout", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.once("error", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.setTimeout(connectTimeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
let tcpReady = false;
|
||||
for (const host of tcpHosts) {
|
||||
tcpReady = await tcpPortIsReady({
|
||||
host,
|
||||
port: tcpPort,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
if (tcpReady) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingFiles,
|
||||
tcpReady,
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForResources({
|
||||
baseDir,
|
||||
files = [],
|
||||
intervalMs = 100,
|
||||
timeoutMs = 120_000,
|
||||
tcpHost,
|
||||
tcpPort,
|
||||
connectTimeoutMs = 500,
|
||||
}) {
|
||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
||||
|
||||
while (true) {
|
||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
||||
baseDir,
|
||||
files,
|
||||
tcpPort,
|
||||
tcpHosts,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
|
||||
if (pendingFiles.length === 0 && tcpReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
const pendingResources = [];
|
||||
if (!tcpReady) {
|
||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
||||
}
|
||||
for (const filePath of pendingFiles) {
|
||||
pendingResources.push(`file:${filePath}`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -68,6 +68,7 @@ import {
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -317,6 +318,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
|
||||
@@ -29,7 +29,6 @@
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -138,6 +138,13 @@ function buildLargeText(lineCount = 20_000): string {
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string): string[] {
|
||||
return input
|
||||
.split("\0")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
it.layer(TestLayer)("git integration", (it) => {
|
||||
@@ -181,6 +188,55 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("workspace helpers", () => {
|
||||
it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/virtual/repo";
|
||||
const relativePaths = Array.from({ length: 340 }, (_, index) => {
|
||||
const prefix = index % 3 === 0 ? "ignored" : "kept";
|
||||
return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`;
|
||||
});
|
||||
const expectedPaths = relativePaths.filter(
|
||||
(relativePath) => !relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "unexpected git command in chunking test",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const chunkPaths = splitNullSeparatedPaths(input.stdin ?? "");
|
||||
seenChunks.push(chunkPaths);
|
||||
const ignoredPaths = chunkPaths.filter((relativePath) =>
|
||||
relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
return Effect.succeed({
|
||||
code: ignoredPaths.length > 0 ? 0 : 1,
|
||||
stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.filterIgnoredPaths(cwd, relativePaths);
|
||||
|
||||
expect(seenChunks.length).toBeGreaterThan(1);
|
||||
expect(seenChunks.flat()).toEqual(relativePaths);
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
@@ -457,12 +513,18 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
}),
|
||||
vi.waitFor(
|
||||
async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
},
|
||||
{
|
||||
timeout: 10_000,
|
||||
interval: 100,
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -541,7 +603,13 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
@@ -594,7 +662,13 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
|
||||
waitForReleasePromise.then(() => ({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from "../Services/GitCore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { limitChunkToByteLimit } from "../../process/outputBuffer";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
@@ -37,6 +38,8 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
|
||||
const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
@@ -55,6 +58,7 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
stdin?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
@@ -96,6 +100,47 @@ function parseNumstatEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function parsePorcelainPath(line: string): string | null {
|
||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
||||
const simple = line.slice(2).trim();
|
||||
@@ -445,7 +490,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
maxOutputBytes: number,
|
||||
truncateOutputAtMaxBytes: boolean,
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
@@ -476,8 +521,8 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
if (truncateOutputAtMaxBytes && truncated) {
|
||||
return;
|
||||
}
|
||||
const nextBytes = bytes + chunk.byteLength;
|
||||
if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) {
|
||||
const limitedChunk = limitChunkToByteLimit(chunk, bytes, maxOutputBytes);
|
||||
if (!truncateOutputAtMaxBytes && limitedChunk.overflow) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
@@ -486,12 +531,9 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
});
|
||||
}
|
||||
|
||||
const chunkToDecode =
|
||||
truncateOutputAtMaxBytes && nextBytes > maxOutputBytes
|
||||
? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))
|
||||
: chunk;
|
||||
bytes += chunkToDecode.byteLength;
|
||||
truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes;
|
||||
const chunkToDecode = truncateOutputAtMaxBytes ? limitedChunk.chunk : chunk;
|
||||
bytes = truncateOutputAtMaxBytes ? limitedChunk.nextBytes : bytes + chunk.byteLength;
|
||||
truncated = truncateOutputAtMaxBytes && limitedChunk.truncated;
|
||||
|
||||
const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
|
||||
text += decoded;
|
||||
@@ -507,7 +549,10 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
text += remainder;
|
||||
lineBuffer += remainder;
|
||||
yield* emitCompleteLines(true);
|
||||
return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text;
|
||||
return {
|
||||
text,
|
||||
truncated,
|
||||
};
|
||||
});
|
||||
|
||||
export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
@@ -571,13 +616,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
input.stdin === undefined
|
||||
? Effect.void
|
||||
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
|
||||
yield* trace2Monitor.flush;
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
const trimmedStderr = stderr.text.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
@@ -589,7 +639,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* runGitCommand().pipe(
|
||||
@@ -618,11 +674,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
|
||||
): Effect.Effect<ExecuteGitResult, GitCommandError> =>
|
||||
execute({
|
||||
operation,
|
||||
cwd,
|
||||
args,
|
||||
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
@@ -679,7 +736,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<string, GitCommandError> =>
|
||||
executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout));
|
||||
executeGit(operation, cwd, args, options).pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
|
||||
),
|
||||
);
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
@@ -1416,6 +1477,86 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) =>
|
||||
executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"));
|
||||
|
||||
const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) =>
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.code === 0
|
||||
? Effect.succeed({
|
||||
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
})
|
||||
: Effect.fail(
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) =>
|
||||
Effect.gen(function* () {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0 && result.code !== 1) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
});
|
||||
|
||||
const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
@@ -1834,6 +1975,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
readConfigValue,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
filterIgnoredPaths,
|
||||
listBranches,
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
@@ -40,6 +41,8 @@ export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
@@ -93,6 +96,11 @@ export interface GitRangeContext {
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface GitListWorkspaceFilesResult {
|
||||
readonly paths: ReadonlyArray<string>;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
@@ -190,6 +198,26 @@ export interface GitCoreShape {
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Determine whether the provided cwd is inside a git work tree.
|
||||
*/
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List tracked and untracked workspace file paths relative to cwd.
|
||||
*/
|
||||
readonly listWorkspaceFiles: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove gitignored paths from a relative path list.
|
||||
*/
|
||||
readonly filterIgnoredPaths: (
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
|
||||
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CliConfig, t3Cli } from "./main";
|
||||
import { OpenLive } from "./open";
|
||||
import * as DesktopLauncher from "./process/Layers/DesktopLauncher";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
@@ -14,7 +14,7 @@ import { FetchHttpClient } from "effect/unstable/http";
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
Layer.provideMerge(ServerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(DesktopLauncher.layer),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
|
||||
@@ -13,7 +13,7 @@ import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
@@ -50,10 +50,12 @@ const testLayer = Layer.mergeAll(
|
||||
start: serverStart,
|
||||
stopSignal: Effect.void,
|
||||
} satisfies ServerShape),
|
||||
Layer.succeed(Open, {
|
||||
Layer.succeed(DesktopLauncher, {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
} satisfies DesktopLauncherShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import { DesktopLauncher } from "./process/Services/DesktopLauncher";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
@@ -336,7 +336,7 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
const desktopLauncher = yield* DesktopLauncher;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -366,7 +366,7 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
yield* desktopLauncher.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
import { FileSystem, Path, Effect } from "effect";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
Effect.gen(function* () {
|
||||
const antigravityLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "antigravity" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(antigravityLaunch, {
|
||||
command: "agy",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps file-manager editor to OS open commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
assertSuccess(result, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: `t3code-no-such-command-${Date.now()}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
it.effect("resolves win32 commands with PATHEXT", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it.effect("does not treat bare files without executable extension as available on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
it.effect("returns installed editors for command launches", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,274 +0,0 @@
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser and workspace
|
||||
* paths in a configured editor.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface OpenShape {
|
||||
/**
|
||||
* Open a URL target in the default browser.
|
||||
*/
|
||||
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
|
||||
|
||||
/**
|
||||
* Open a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
export const OpenLive = Layer.effect(Open, make);
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
@@ -261,7 +262,9 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
@@ -25,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -68,6 +68,7 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -226,7 +227,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects files created or deleted during this turn.
|
||||
clearWorkspaceIndexCache(input.cwd);
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
@@ -642,7 +643,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects the reverted filesystem state.
|
||||
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
|
||||
yield* workspaceEntries.invalidate(sessionRuntime.value.cwd);
|
||||
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
|
||||
@@ -0,0 +1,831 @@
|
||||
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
PlatformError,
|
||||
Scope,
|
||||
Sink,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
make as makeDesktopLauncher,
|
||||
type DetachedSpawnInput,
|
||||
type LaunchRuntimeOptions,
|
||||
} from "./DesktopLauncher";
|
||||
import { DesktopLauncher, DesktopLauncherSpawnError } from "../Services/DesktopLauncher";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
interface SpawnCall {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly detached?: boolean | undefined;
|
||||
readonly shell?: boolean | string | undefined;
|
||||
readonly stdin?: unknown;
|
||||
readonly stdout?: unknown;
|
||||
readonly stderr?: unknown;
|
||||
}
|
||||
|
||||
function decodePowerShellCommand(encoded: string): string {
|
||||
return Buffer.from(encoded, "base64").toString("utf16le");
|
||||
}
|
||||
|
||||
function platformSpawnError(message: string) {
|
||||
return PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: message,
|
||||
});
|
||||
}
|
||||
|
||||
function spawnerLayer(
|
||||
calls: Array<SpawnCall>,
|
||||
handler: (call: SpawnCall) => {
|
||||
readonly code?: number;
|
||||
readonly fail?: string;
|
||||
readonly awaitExit?: Deferred.Deferred<void>;
|
||||
readonly onKill?: () => void;
|
||||
} = () => ({
|
||||
code: 0,
|
||||
}),
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const standardCommand = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: {
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean | string;
|
||||
readonly stdin?: unknown;
|
||||
readonly stdout?: unknown;
|
||||
readonly stderr?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
const call: SpawnCall = {
|
||||
command: standardCommand.command,
|
||||
args: [...standardCommand.args],
|
||||
detached: standardCommand.options.detached,
|
||||
shell: standardCommand.options.shell,
|
||||
stdin: standardCommand.options.stdin,
|
||||
stdout: standardCommand.options.stdout,
|
||||
stderr: standardCommand.options.stderr,
|
||||
};
|
||||
calls.push(call);
|
||||
|
||||
const result = handler(call);
|
||||
if (result.fail) {
|
||||
return Effect.fail(platformSpawnError(result.fail));
|
||||
}
|
||||
|
||||
let exited = false;
|
||||
const exitCode = result.awaitExit
|
||||
? Deferred.await(result.awaitExit).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
exited = true;
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
|
||||
)
|
||||
: Effect.sync(() => {
|
||||
exited = true;
|
||||
return ChildProcessSpawner.ExitCode(result.code ?? 0);
|
||||
});
|
||||
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(calls.length),
|
||||
exitCode,
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () =>
|
||||
Effect.sync(() => {
|
||||
if (!exited) {
|
||||
result.onKill?.();
|
||||
}
|
||||
}),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode("")),
|
||||
stderr: Stream.make(encoder.encode("")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function spawnHarness(
|
||||
calls: Array<SpawnCall>,
|
||||
handler: (call: SpawnCall) => {
|
||||
readonly code?: number;
|
||||
readonly fail?: string;
|
||||
readonly awaitExit?: Deferred.Deferred<void>;
|
||||
readonly onKill?: () => void;
|
||||
} = () => ({
|
||||
code: 0,
|
||||
}),
|
||||
) {
|
||||
return {
|
||||
layer: spawnerLayer(calls, handler),
|
||||
spawnDetached: (
|
||||
input: DetachedSpawnInput,
|
||||
context: {
|
||||
readonly operation: string;
|
||||
readonly target?: string;
|
||||
readonly editor?: string;
|
||||
},
|
||||
) => {
|
||||
const call: SpawnCall = {
|
||||
command: input.command,
|
||||
args: [...input.args],
|
||||
detached: input.detached,
|
||||
shell: input.shell,
|
||||
stdin: input.stdin,
|
||||
stdout: input.stdout,
|
||||
stderr: input.stderr,
|
||||
};
|
||||
calls.push(call);
|
||||
|
||||
const result = handler(call);
|
||||
return result.fail
|
||||
? Effect.fail(
|
||||
new DesktopLauncherSpawnError({
|
||||
operation: context.operation,
|
||||
command: input.command,
|
||||
args: [...input.args],
|
||||
...(context.target !== undefined ? { target: context.target } : {}),
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
}),
|
||||
)
|
||||
: Effect.void;
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
const provideOpen = (
|
||||
options: LaunchRuntimeOptions,
|
||||
harness: {
|
||||
readonly layer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly spawnDetached: (
|
||||
input: DetachedSpawnInput,
|
||||
context: {
|
||||
readonly operation: string;
|
||||
readonly target?: string;
|
||||
readonly editor?: string;
|
||||
},
|
||||
) => Effect.Effect<void, DesktopLauncherSpawnError>;
|
||||
},
|
||||
) =>
|
||||
Layer.effect(
|
||||
DesktopLauncher,
|
||||
makeDesktopLauncher({ ...options, spawnDetached: harness.spawnDetached }),
|
||||
).pipe(Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, harness.layer)));
|
||||
|
||||
const runOpen = <A>(
|
||||
options: LaunchRuntimeOptions,
|
||||
harness: {
|
||||
readonly layer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly spawnDetached: (
|
||||
input: DetachedSpawnInput,
|
||||
context: {
|
||||
readonly operation: string;
|
||||
readonly target?: string;
|
||||
readonly editor?: string;
|
||||
},
|
||||
) => Effect.Effect<void, DesktopLauncherSpawnError>;
|
||||
},
|
||||
effect: Effect.Effect<A, never, DesktopLauncher>,
|
||||
) => effect.pipe(Effect.provide(provideOpen(options, harness)));
|
||||
|
||||
const readOpen = Effect.service(DesktopLauncher);
|
||||
|
||||
const writeExecutable = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(filePath, 0o755);
|
||||
});
|
||||
|
||||
it.effect("getAvailableEditors detects installed editors through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
|
||||
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
|
||||
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
|
||||
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const editors = yield* open.getAvailableEditors;
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(calls, []);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const editors = yield* open.getAvailableEditors;
|
||||
assert.equal(editors.includes("file-manager"), false);
|
||||
assert.deepEqual(calls, []);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses --goto for editors that support it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
|
||||
yield* writeExecutable(`${dir}/cursor`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace/src/open.ts:71:5",
|
||||
editor: "cursor",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/cursor`,
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor launches Windows batch shims through cmd.exe without shell mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
|
||||
yield* fs.writeFileString(`${dir}/code.cmd`, "@echo off\r\n");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "C:\\work\\100% real\\file.ts:12:4",
|
||||
editor: "vscode",
|
||||
});
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.command, "cmd.exe");
|
||||
assert.deepEqual(calls[0]?.args.slice(0, 4), ["/d", "/v:off", "/s", "/c"]);
|
||||
assert.equal(calls[0]?.args[4]?.toLowerCase().includes(`${dir}/code.cmd`.toLowerCase()), true);
|
||||
assert.equal(calls[0]?.args[4]?.includes('"--goto"'), true);
|
||||
assert.equal(calls[0]?.args[4]?.includes("100%% real"), true);
|
||||
assert.equal(calls[0]?.detached, true);
|
||||
assert.equal(calls[0]?.shell, false);
|
||||
assert.equal(calls[0]?.stdin, "ignore");
|
||||
assert.equal(calls[0]?.stdout, "ignore");
|
||||
assert.equal(calls[0]?.stderr, "ignore");
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor detached launches bypass the scoped child-process spawner", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
|
||||
yield* writeExecutable(`${dir}/zed`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const harness = spawnHarness(calls);
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
Scope.make("sequential"),
|
||||
(scope) =>
|
||||
Effect.gen(function* () {
|
||||
const runtimeServices = yield* Layer.build(
|
||||
provideOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
harness,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "zed",
|
||||
});
|
||||
}),
|
||||
(scope) => Scope.close(scope, Exit.void),
|
||||
);
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/zed`,
|
||||
args: ["/tmp/workspace"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
|
||||
yield* writeExecutable(`${dir}/open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "file-manager",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/open`,
|
||||
args: ["/tmp/workspace"],
|
||||
detached: undefined,
|
||||
shell: false,
|
||||
stdin: undefined,
|
||||
stdout: undefined,
|
||||
stderr: undefined,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser uses macOS open flags and app arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
|
||||
yield* writeExecutable(`${dir}/open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com", {
|
||||
wait: true,
|
||||
background: true,
|
||||
newInstance: true,
|
||||
app: {
|
||||
name: "google chrome",
|
||||
arguments: ["--profile-directory=Work"],
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/open`,
|
||||
args: [
|
||||
"--wait-apps",
|
||||
"--background",
|
||||
"--new",
|
||||
"-a",
|
||||
"google chrome",
|
||||
"https://example.com",
|
||||
"--args",
|
||||
"--profile-directory=Work",
|
||||
],
|
||||
detached: undefined,
|
||||
shell: false,
|
||||
stdin: undefined,
|
||||
stdout: undefined,
|
||||
stderr: undefined,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser uses PowerShell on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
|
||||
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com");
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
|
||||
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
|
||||
assert.equal(
|
||||
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
|
||||
"Start 'https://example.com'",
|
||||
);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser detaches direct app launches on win32 when not waiting", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-app-" });
|
||||
yield* fs.writeFileString(`${dir}/chrome.exe`, "MZ");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com", {
|
||||
app: {
|
||||
name: "chrome",
|
||||
arguments: ["--profile-directory=Work"],
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.command.toLowerCase(), `${dir}/chrome.exe`.toLowerCase());
|
||||
assert.deepEqual(calls[0]?.args, ["--profile-directory=Work", "https://example.com"]);
|
||||
assert.equal(calls[0]?.detached, true);
|
||||
assert.equal(calls[0]?.shell, false);
|
||||
assert.equal(calls[0]?.stdin, "ignore");
|
||||
assert.equal(calls[0]?.stdout, "ignore");
|
||||
assert.equal(calls[0]?.stderr, "ignore");
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser preserves non-zero exit errors for waited direct app launches", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-linux-app-wait-" });
|
||||
yield* writeExecutable(`${dir}/firefox`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnHarness(calls, () => ({ code: 23 })),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const error = yield* open
|
||||
.openBrowser("https://example.com", {
|
||||
wait: true,
|
||||
app: { name: "firefox" },
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "DesktopLauncherNonZeroExitError");
|
||||
if (error._tag !== "DesktopLauncherNonZeroExitError") {
|
||||
throw new Error(`Unexpected error tag: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.exitCode, 23);
|
||||
assert.equal(error.command, `${dir}/firefox`);
|
||||
assert.deepEqual(error.args, ["https://example.com"]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnHarness(calls, (call) =>
|
||||
call.command.includes("powershell")
|
||||
? { fail: "powershell unavailable" }
|
||||
: {
|
||||
code: 0,
|
||||
},
|
||||
),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com");
|
||||
|
||||
assert.equal(calls[0]?.command.includes("powershell"), true);
|
||||
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
|
||||
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser skips WSL PowerShell when process env marks a container", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-container-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const originalValues = new Map<string, string | undefined>();
|
||||
const setEnv = (key: string, value: string | undefined) => {
|
||||
if (!originalValues.has(key)) {
|
||||
originalValues.set(key, process.env[key]);
|
||||
}
|
||||
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
return;
|
||||
}
|
||||
|
||||
process.env[key] = value;
|
||||
};
|
||||
const restoreEnv = () => {
|
||||
for (const [key, value] of originalValues) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
setEnv("PATH", `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`);
|
||||
setEnv("WSL_DISTRO_NAME", "Ubuntu");
|
||||
setEnv("CONTAINER", "docker");
|
||||
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
isWsl: true,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com");
|
||||
} finally {
|
||||
restoreEnv();
|
||||
}
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/xdg-open`,
|
||||
args: ["https://example.com"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/home/julius/workspace",
|
||||
editor: "file-manager",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/xdg-open`,
|
||||
args: ["/home/julius/workspace"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor fails when the editor command is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: "" },
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const error = yield* open
|
||||
.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "cursor",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "DesktopLauncherCommandNotFoundError");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Desktop launcher command not found in openInEditor: cursor for editor cursor",
|
||||
);
|
||||
assert.deepEqual(calls, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("openBrowser rejects an empty target with a validation error", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: "" },
|
||||
},
|
||||
spawnHarness(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const error = yield* open.openBrowser(" ").pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "DesktopLauncherValidationError");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Desktop launcher validation failed in openBrowser: target must not be empty",
|
||||
);
|
||||
assert.deepEqual(calls, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("openBrowser reports exhausted fallback attempts when multiple launchers fail", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-fallback-errors-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnHarness(calls, () => ({ fail: "launcher unavailable" })),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const error = yield* open.openBrowser("https://example.com").pipe(Effect.flip);
|
||||
assert.equal(error._tag, "DesktopLauncherLaunchAttemptsExhaustedError");
|
||||
if (error._tag !== "DesktopLauncherLaunchAttemptsExhaustedError") {
|
||||
throw new Error(`Unexpected error tag: ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(
|
||||
error.attempts.map((attempt) => attempt.reason),
|
||||
["spawnFailed", "spawnFailed"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
error.attempts.map((attempt) => attempt.command.includes("powershell")),
|
||||
[true, false],
|
||||
);
|
||||
assert.deepEqual(
|
||||
calls.map((call) => call.command.includes("powershell")),
|
||||
[true, false],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
@@ -0,0 +1,879 @@
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser, workspace paths in
|
||||
* a configured editor, and generic external targets through the platform's
|
||||
* default opener.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import OS from "node:os";
|
||||
import { spawn as spawnNodeChildProcess } from "node:child_process";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { Array, Effect, FileSystem, Layer, Option, Path, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
isWindowsBatchShim,
|
||||
makeWindowsCmdSpawnArguments,
|
||||
resolveWindowsCommandShell,
|
||||
} from "../windowsCommand";
|
||||
import {
|
||||
DesktopLauncherCommandNotFoundError,
|
||||
DesktopLauncherDiscoveryError,
|
||||
DesktopLauncherLaunchAttemptsExhaustedError,
|
||||
DesktopLauncherNonZeroExitError,
|
||||
DesktopLauncherSpawnError,
|
||||
DesktopLauncherUnknownEditorError,
|
||||
DesktopLauncherValidationError,
|
||||
DesktopLauncher,
|
||||
type DesktopLauncherShape,
|
||||
type OpenApplicationInput,
|
||||
type OpenExternalInput,
|
||||
} from "../Services/DesktopLauncher";
|
||||
|
||||
export interface DetachedSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean;
|
||||
readonly stdin?: "ignore";
|
||||
readonly stdout?: "ignore";
|
||||
readonly stderr?: "ignore";
|
||||
}
|
||||
|
||||
type DesktopLauncherOperation =
|
||||
| "getAvailableEditors"
|
||||
| "openBrowser"
|
||||
| "openExternal"
|
||||
| "openInEditor";
|
||||
|
||||
interface LaunchContext {
|
||||
readonly operation: DesktopLauncherOperation;
|
||||
readonly target?: string;
|
||||
readonly editor?: EditorId;
|
||||
}
|
||||
|
||||
export interface LaunchRuntimeOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly isWsl?: boolean;
|
||||
readonly isInsideContainer?: boolean;
|
||||
readonly powerShellCommand?: string;
|
||||
readonly spawnDetached?: (
|
||||
input: DetachedSpawnInput,
|
||||
context: LaunchContext,
|
||||
) => Effect.Effect<void, DesktopLauncherSpawnError>;
|
||||
}
|
||||
|
||||
interface LaunchRuntime {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly isWsl: boolean;
|
||||
readonly isInsideContainer: boolean;
|
||||
readonly powerShellCandidates: ReadonlyArray<string>;
|
||||
readonly windowsPathExtensions: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface LaunchPlan {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly wait: boolean;
|
||||
readonly allowNonzeroExitCode: boolean;
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean;
|
||||
readonly stdio?: "ignore";
|
||||
}
|
||||
|
||||
interface ResolvedCommand {
|
||||
readonly path: string;
|
||||
readonly usesCmdWrapper: boolean;
|
||||
}
|
||||
|
||||
interface OpenApplicationCandidate {
|
||||
readonly name: string;
|
||||
readonly arguments: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface LaunchAttemptFailure {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly reason: "commandNotFound" | "spawnFailed" | "nonZeroExit";
|
||||
readonly detail: string;
|
||||
readonly exitCode?: number;
|
||||
}
|
||||
|
||||
type LaunchAttemptError =
|
||||
| DesktopLauncherCommandNotFoundError
|
||||
| DesktopLauncherNonZeroExitError
|
||||
| DesktopLauncherSpawnError;
|
||||
|
||||
type LaunchPlanError = LaunchAttemptError | DesktopLauncherLaunchAttemptsExhaustedError;
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
|
||||
const WSL_POWERSHELL_CANDIDATES = [
|
||||
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
|
||||
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
|
||||
"powershell.exe",
|
||||
"pwsh.exe",
|
||||
] as const;
|
||||
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
|
||||
return parsed.length > 0 ? Array.dedupe(parsed) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
runtime: LaunchRuntime,
|
||||
pathService: Path.Path,
|
||||
): ReadonlyArray<string> {
|
||||
if (runtime.platform !== "win32") return [command];
|
||||
const extension = pathService.extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.dedupe([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extensionName of runtime.windowsPathExtensions) {
|
||||
candidates.push(`${command}${extensionName}`);
|
||||
candidates.push(`${command}${extensionName.toLowerCase()}`);
|
||||
}
|
||||
return Array.dedupe(candidates);
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
|
||||
if (platform !== "linux") return false;
|
||||
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
|
||||
return true;
|
||||
}
|
||||
return OS.release().toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
function quotePowerShellValue(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function encodePowerShellCommand(command: string): string {
|
||||
return Buffer.from(command, "utf16le").toString("base64");
|
||||
}
|
||||
|
||||
function normalizeAppCandidates(
|
||||
app: OpenApplicationInput | ReadonlyArray<OpenApplicationInput> | undefined,
|
||||
): ReadonlyArray<OpenApplicationCandidate | undefined> {
|
||||
if (!app) return [undefined];
|
||||
|
||||
const apps = Array.ensure(app);
|
||||
const candidates: Array<OpenApplicationCandidate> = [];
|
||||
|
||||
for (const appDef of apps) {
|
||||
const names = Array.ensure(appDef.name);
|
||||
for (const name of names) {
|
||||
candidates.push({ name, arguments: appDef.arguments ?? [] });
|
||||
}
|
||||
}
|
||||
|
||||
return candidates.length > 0 ? candidates : [undefined];
|
||||
}
|
||||
|
||||
function isUriLikeTarget(target: string): boolean {
|
||||
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
|
||||
}
|
||||
|
||||
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: LaunchRuntime): boolean {
|
||||
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
|
||||
}
|
||||
|
||||
function makeLaunchPlan(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: {
|
||||
readonly wait: boolean;
|
||||
readonly allowNonzeroExitCode: boolean;
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean;
|
||||
readonly stdio?: "ignore";
|
||||
},
|
||||
): LaunchPlan {
|
||||
return {
|
||||
command,
|
||||
args,
|
||||
wait: options.wait,
|
||||
allowNonzeroExitCode: options.allowNonzeroExitCode,
|
||||
shell: options.shell ?? false,
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
|
||||
const args: string[] = [];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) args.push("--wait-apps");
|
||||
if (input.background) args.push("--background");
|
||||
if (input.newInstance) args.push("--new");
|
||||
args.push(input.target);
|
||||
|
||||
return makeLaunchPlan("open", args, {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeDarwinApplicationPlan(
|
||||
input: OpenExternalInput,
|
||||
app: OpenApplicationCandidate,
|
||||
): LaunchPlan {
|
||||
const args: string[] = [];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) args.push("--wait-apps");
|
||||
if (input.background) args.push("--background");
|
||||
if (input.newInstance) args.push("--new");
|
||||
args.push("-a", app.name);
|
||||
args.push(input.target);
|
||||
if (app.arguments.length > 0) {
|
||||
args.push("--args", ...app.arguments);
|
||||
}
|
||||
|
||||
return makeLaunchPlan("open", args, {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
|
||||
const encodedParts = ["Start"];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) encodedParts.push("-Wait");
|
||||
encodedParts.push(quotePowerShellValue(input.target));
|
||||
|
||||
return makeLaunchPlan(
|
||||
powerShellCommand,
|
||||
[
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
encodePowerShellCommand(encodedParts.join(" ")),
|
||||
],
|
||||
{
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
|
||||
const wait = input.wait ?? false;
|
||||
return makeLaunchPlan("xdg-open", [input.target], {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
detached: !wait,
|
||||
...(wait ? {} : { stdio: "ignore" as const }),
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
|
||||
return makeLaunchPlan("explorer", [input.target], {
|
||||
wait: false,
|
||||
allowNonzeroExitCode: false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectApplicationPlan(
|
||||
input: OpenExternalInput,
|
||||
app: OpenApplicationCandidate,
|
||||
): LaunchPlan {
|
||||
const wait = input.wait ?? false;
|
||||
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
detached: !wait,
|
||||
...(wait ? {} : { stdio: "ignore" as const }),
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function resolveExternalPlans(
|
||||
input: OpenExternalInput,
|
||||
runtime: LaunchRuntime,
|
||||
): ReadonlyArray<LaunchPlan> {
|
||||
const appCandidates = normalizeAppCandidates(input.app);
|
||||
const plans: LaunchPlan[] = [];
|
||||
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
|
||||
|
||||
for (const app of appCandidates) {
|
||||
if (app) {
|
||||
if (runtime.platform === "darwin") {
|
||||
plans.push(makeDarwinApplicationPlan(input, app));
|
||||
} else {
|
||||
plans.push(makeDirectApplicationPlan(input, app));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runtime.platform === "darwin") {
|
||||
plans.push(makeDarwinDefaultPlan(input));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
|
||||
for (const powerShellCommand of runtime.powerShellCandidates) {
|
||||
plans.push(makePowerShellPlan(input, powerShellCommand));
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.platform === "win32") {
|
||||
if (!(input.wait ?? false)) {
|
||||
plans.push(makeWindowsExplorerPlan(input));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
plans.push(makeLinuxDefaultPlan(input));
|
||||
}
|
||||
|
||||
return plans;
|
||||
}
|
||||
|
||||
function resolveSpawnInput(
|
||||
runtime: LaunchRuntime,
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
): DetachedSpawnInput {
|
||||
return {
|
||||
command: resolvedCommand.usesCmdWrapper
|
||||
? resolveWindowsCommandShell(runtime.env)
|
||||
: resolvedCommand.path,
|
||||
args: resolvedCommand.usesCmdWrapper
|
||||
? makeWindowsCmdSpawnArguments(resolvedCommand.path, plan.args)
|
||||
: [...plan.args],
|
||||
...(plan.detached !== undefined ? { detached: plan.detached } : {}),
|
||||
...(plan.shell !== undefined ? { shell: plan.shell } : {}),
|
||||
...(plan.stdio === "ignore"
|
||||
? {
|
||||
stdin: "ignore" as const,
|
||||
stdout: "ignore" as const,
|
||||
stderr: "ignore" as const,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeCommandNotFoundError(
|
||||
context: LaunchContext,
|
||||
command: string,
|
||||
): DesktopLauncherCommandNotFoundError {
|
||||
return new DesktopLauncherCommandNotFoundError({
|
||||
operation: context.operation,
|
||||
command,
|
||||
...(context.target !== undefined ? { target: context.target } : {}),
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSpawnError(
|
||||
context: LaunchContext,
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
cause?: unknown,
|
||||
): DesktopLauncherSpawnError {
|
||||
return new DesktopLauncherSpawnError({
|
||||
operation: context.operation,
|
||||
command,
|
||||
args: [...args],
|
||||
...(context.target !== undefined ? { target: context.target } : {}),
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function makeNonZeroExitError(
|
||||
context: LaunchContext,
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
exitCode: number,
|
||||
): DesktopLauncherNonZeroExitError {
|
||||
return new DesktopLauncherNonZeroExitError({
|
||||
operation: context.operation,
|
||||
command,
|
||||
args: [...args],
|
||||
exitCode,
|
||||
...(context.target !== undefined ? { target: context.target } : {}),
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function toLaunchAttemptFailure(error: LaunchAttemptError): LaunchAttemptFailure {
|
||||
switch (error._tag) {
|
||||
case "DesktopLauncherCommandNotFoundError":
|
||||
return {
|
||||
command: error.command,
|
||||
args: [],
|
||||
reason: "commandNotFound",
|
||||
detail: error.message,
|
||||
};
|
||||
case "DesktopLauncherSpawnError":
|
||||
return {
|
||||
command: error.command,
|
||||
args: error.args,
|
||||
reason: "spawnFailed",
|
||||
detail: error.message,
|
||||
};
|
||||
case "DesktopLauncherNonZeroExitError":
|
||||
return {
|
||||
command: error.command,
|
||||
args: error.args,
|
||||
reason: "nonZeroExit",
|
||||
detail: error.message,
|
||||
exitCode: error.exitCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detached GUI launches must call `unref()` after spawn. The Effect
|
||||
* `ChildProcessSpawner` owns spawned handles through scope finalizers and does
|
||||
* not expose `unref()`, which means it cannot provide true fire-and-forget
|
||||
* behavior for editor / file-manager launches.
|
||||
*/
|
||||
const DETACHED_SPAWN_GRACE_MS = 500;
|
||||
|
||||
function defaultSpawnDetached(
|
||||
input: DetachedSpawnInput,
|
||||
context: LaunchContext,
|
||||
): Effect.Effect<void, DesktopLauncherSpawnError> {
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
spawnNodeChildProcess(input.command, [...input.args], {
|
||||
...(input.detached !== undefined ? { detached: input.detached } : {}),
|
||||
...(input.shell !== undefined ? { shell: input.shell } : {}),
|
||||
...(input.stdin === "ignore" && input.stdout === "ignore" && input.stderr === "ignore"
|
||||
? { stdio: "ignore" as const }
|
||||
: {}),
|
||||
}),
|
||||
catch: (cause) => makeSpawnError(context, input.command, input.args, cause),
|
||||
}).pipe(
|
||||
Effect.flatMap((childProcess) =>
|
||||
Effect.callback<void, DesktopLauncherSpawnError>((resume) => {
|
||||
let graceTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const onEarlyExit = (code: number | null) => {
|
||||
if (graceTimer !== undefined) clearTimeout(graceTimer);
|
||||
if (code !== null && code !== 0) {
|
||||
resume(
|
||||
Effect.fail(
|
||||
makeSpawnError(
|
||||
context,
|
||||
input.command,
|
||||
input.args,
|
||||
new Error(`Process exited immediately with code ${code}`),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
childProcess.unref();
|
||||
resume(Effect.void);
|
||||
}
|
||||
};
|
||||
|
||||
const onError = (error: Error) => {
|
||||
childProcess.off("spawn", onSpawn);
|
||||
resume(Effect.fail(makeSpawnError(context, input.command, input.args, error)));
|
||||
};
|
||||
|
||||
const onSpawn = () => {
|
||||
childProcess.off("error", onError);
|
||||
childProcess.once("exit", onEarlyExit);
|
||||
graceTimer = setTimeout(() => {
|
||||
childProcess.off("exit", onEarlyExit);
|
||||
childProcess.unref();
|
||||
resume(Effect.void);
|
||||
}, DETACHED_SPAWN_GRACE_MS);
|
||||
};
|
||||
|
||||
childProcess.once("error", onError);
|
||||
childProcess.once("spawn", onSpawn);
|
||||
|
||||
return Effect.sync(() => {
|
||||
if (graceTimer !== undefined) clearTimeout(graceTimer);
|
||||
childProcess.off("error", onError);
|
||||
childProcess.off("spawn", onSpawn);
|
||||
childProcess.off("exit", onEarlyExit);
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeDesktopLauncher")(function* (
|
||||
options: LaunchRuntimeOptions = {},
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeEnv = options.env ?? process.env;
|
||||
const runtimePlatform = options.platform ?? process.platform;
|
||||
const isWsl = options.isWsl ?? detectWsl(runtimePlatform, runtimeEnv);
|
||||
|
||||
const isInsideContainer =
|
||||
options.isInsideContainer ??
|
||||
(typeof runtimeEnv.CONTAINER === "string" ||
|
||||
typeof runtimeEnv.container === "string" ||
|
||||
typeof runtimeEnv.KUBERNETES_SERVICE_HOST === "string"
|
||||
? true
|
||||
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
|
||||
|
||||
const runtime: LaunchRuntime = {
|
||||
platform: runtimePlatform,
|
||||
env: runtimeEnv,
|
||||
isWsl,
|
||||
isInsideContainer,
|
||||
powerShellCandidates:
|
||||
options.powerShellCommand !== undefined
|
||||
? [options.powerShellCommand]
|
||||
: isWsl
|
||||
? WSL_POWERSHELL_CANDIDATES
|
||||
: WINDOWS_POWERSHELL_CANDIDATES,
|
||||
windowsPathExtensions: resolveWindowsPathExtensions(runtimeEnv),
|
||||
};
|
||||
|
||||
const resolveCommand = Effect.fn("resolveCommand")(function* (
|
||||
command: string,
|
||||
): Effect.fn.Return<Option.Option<ResolvedCommand>> {
|
||||
const candidates = resolveCommandCandidates(command, runtime, pathService);
|
||||
|
||||
const resolveExecutableFile = Effect.fn("resolveExecutableFile")(function* (
|
||||
filePath: string,
|
||||
): Effect.fn.Return<Option.Option<ResolvedCommand>> {
|
||||
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
|
||||
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
|
||||
|
||||
if (runtime.platform === "win32") {
|
||||
const extension = pathService.extname(filePath);
|
||||
if (
|
||||
extension.length === 0 ||
|
||||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
|
||||
) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
path: filePath,
|
||||
usesCmdWrapper: isWindowsBatchShim(filePath),
|
||||
} satisfies ResolvedCommand);
|
||||
}
|
||||
|
||||
return (info.value.mode & 0o111) !== 0
|
||||
? Option.some({
|
||||
path: filePath,
|
||||
usesCmdWrapper: false,
|
||||
} satisfies ResolvedCommand)
|
||||
: Option.none();
|
||||
});
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
for (const candidate of candidates) {
|
||||
const resolved = yield* resolveExecutableFile(candidate);
|
||||
if (Option.isSome(resolved)) return resolved;
|
||||
}
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(runtime.env);
|
||||
if (pathValue.length === 0) return Option.none();
|
||||
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(runtime.platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of candidates) {
|
||||
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
|
||||
if (Option.isSome(resolved)) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const commandAvailable = (command: string) =>
|
||||
resolveCommand(command).pipe(Effect.map(Option.isSome));
|
||||
|
||||
const fileManagerAvailable = Effect.gen(function* () {
|
||||
const candidates =
|
||||
runtime.platform === "darwin"
|
||||
? ["open"]
|
||||
: runtime.platform === "win32"
|
||||
? [...runtime.powerShellCandidates, "explorer"]
|
||||
: ["xdg-open"];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* commandAvailable(candidate)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
const getAvailableEditors: DesktopLauncherShape["getAvailableEditors"] = Effect.gen(function* () {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.id === "file-manager") {
|
||||
if (yield* fileManagerAvailable) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (editor.command && (yield* commandAvailable(editor.command))) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLauncherDiscoveryError({
|
||||
operation: "getAvailableEditors",
|
||||
detail: "failed to resolve available editors",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const spawnPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
context: LaunchContext,
|
||||
) => {
|
||||
const input = resolveSpawnInput(runtime, plan, resolvedCommand);
|
||||
return spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.command, [...input.args], {
|
||||
detached: plan.detached,
|
||||
shell: plan.shell,
|
||||
...(plan.stdio === "ignore"
|
||||
? {
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError((cause) => makeSpawnError(context, input.command, input.args, cause)));
|
||||
};
|
||||
|
||||
const spawnDetached = options.spawnDetached ?? defaultSpawnDetached;
|
||||
|
||||
const waitForExit = (
|
||||
plan: LaunchPlan,
|
||||
context: LaunchContext,
|
||||
spawnInput: DetachedSpawnInput,
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
) =>
|
||||
handle.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
makeSpawnError(context, spawnInput.command, spawnInput.args, cause),
|
||||
),
|
||||
Effect.flatMap((exitCode) =>
|
||||
!plan.allowNonzeroExitCode && exitCode !== 0
|
||||
? Effect.fail(
|
||||
makeNonZeroExitError(context, spawnInput.command, spawnInput.args, exitCode),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
|
||||
const runWaitedPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
context: LaunchContext,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
Scope.make("sequential"),
|
||||
(scope) =>
|
||||
Effect.gen(function* () {
|
||||
const spawnInput = resolveSpawnInput(runtime, plan, resolvedCommand);
|
||||
const handle = yield* spawnPlan(plan, resolvedCommand, context).pipe(
|
||||
Scope.provide(scope),
|
||||
);
|
||||
yield* waitForExit(plan, context, spawnInput, handle);
|
||||
}),
|
||||
(scope, exit) => Scope.close(scope, exit),
|
||||
);
|
||||
|
||||
const runDetachedPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
context: LaunchContext,
|
||||
) => spawnDetached(resolveSpawnInput(runtime, plan, resolvedCommand), context);
|
||||
|
||||
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, context: LaunchContext) =>
|
||||
plan.wait
|
||||
? runWaitedPlan(plan, resolvedCommand, context)
|
||||
: runDetachedPlan(plan, resolvedCommand, context);
|
||||
|
||||
const runFirstAvailablePlan = Effect.fn("runFirstAvailablePlan")(function* (
|
||||
plans: ReadonlyArray<LaunchPlan>,
|
||||
context: LaunchContext,
|
||||
): Effect.fn.Return<void, LaunchPlanError> {
|
||||
const failures: LaunchAttemptError[] = [];
|
||||
|
||||
for (const plan of plans) {
|
||||
const resolvedCommand = yield* resolveCommand(plan.command);
|
||||
if (Option.isNone(resolvedCommand)) {
|
||||
failures.push(makeCommandNotFoundError(context, plan.command));
|
||||
continue;
|
||||
}
|
||||
|
||||
const attempt = yield* Effect.result(runPlan(plan, resolvedCommand.value, context));
|
||||
if (attempt._tag === "Success") {
|
||||
return;
|
||||
}
|
||||
|
||||
failures.push(attempt.failure);
|
||||
}
|
||||
|
||||
const [firstFailure] = failures;
|
||||
if (failures.length === 1 && firstFailure) {
|
||||
return yield* firstFailure;
|
||||
}
|
||||
|
||||
return yield* new DesktopLauncherLaunchAttemptsExhaustedError({
|
||||
operation: context.operation,
|
||||
...(context.target !== undefined ? { target: context.target } : {}),
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
attempts: failures.map(toLaunchAttemptFailure),
|
||||
});
|
||||
});
|
||||
|
||||
const openTarget = Effect.fn("openTarget")(function* (
|
||||
operation: Extract<DesktopLauncherOperation, "openBrowser" | "openExternal" | "openInEditor">,
|
||||
input: OpenExternalInput,
|
||||
context: Omit<LaunchContext, "operation"> = {},
|
||||
) {
|
||||
if (input.target.trim().length === 0) {
|
||||
return yield* new DesktopLauncherValidationError({
|
||||
operation,
|
||||
detail: "target must not be empty",
|
||||
target: input.target,
|
||||
});
|
||||
}
|
||||
|
||||
return yield* runFirstAvailablePlan(resolveExternalPlans(input, runtime), {
|
||||
operation,
|
||||
target: input.target,
|
||||
...(context.editor !== undefined ? { editor: context.editor } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const openExternal: DesktopLauncherShape["openExternal"] = Effect.fn("openExternal")(
|
||||
function* (input) {
|
||||
return yield* openTarget("openExternal", input);
|
||||
},
|
||||
);
|
||||
|
||||
const openBrowser: DesktopLauncherShape["openBrowser"] = Effect.fn("openBrowser")(function* (
|
||||
target,
|
||||
openOptions = {},
|
||||
) {
|
||||
return yield* openTarget("openBrowser", { ...openOptions, target });
|
||||
});
|
||||
|
||||
const openInEditor: DesktopLauncherShape["openInEditor"] = Effect.fn("openInEditor")(
|
||||
function* (input) {
|
||||
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
|
||||
if (!editor) {
|
||||
return yield* new DesktopLauncherUnknownEditorError({ editor: input.editor });
|
||||
}
|
||||
|
||||
if (editor.command) {
|
||||
return yield* runFirstAvailablePlan(
|
||||
[
|
||||
makeLaunchPlan(
|
||||
editor.command,
|
||||
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
|
||||
{
|
||||
wait: false,
|
||||
allowNonzeroExitCode: false,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
},
|
||||
),
|
||||
],
|
||||
{
|
||||
operation: "openInEditor",
|
||||
target: input.cwd,
|
||||
editor: input.editor,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return yield* openTarget(
|
||||
"openInEditor",
|
||||
{ target: input.cwd },
|
||||
{ target: input.cwd, editor: input.editor },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
getAvailableEditors,
|
||||
openExternal,
|
||||
openBrowser,
|
||||
openInEditor,
|
||||
} satisfies DesktopLauncherShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLauncher, make());
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser, workspace paths in
|
||||
* a configured editor, and generic external targets through the platform's
|
||||
* default opener.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
|
||||
import { type EditorId } from "@t3tools/contracts";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
|
||||
const DesktopLauncherLaunchAttemptSchema = Schema.Struct({
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
reason: Schema.Literals(["commandNotFound", "spawnFailed", "nonZeroExit"]),
|
||||
detail: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
});
|
||||
|
||||
export class DesktopLauncherDiscoveryError extends Schema.TaggedErrorClass<DesktopLauncherDiscoveryError>()(
|
||||
"DesktopLauncherDiscoveryError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop launcher discovery failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherValidationError extends Schema.TaggedErrorClass<DesktopLauncherValidationError>()(
|
||||
"DesktopLauncherValidationError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
target: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop launcher validation failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherUnknownEditorError extends Schema.TaggedErrorClass<DesktopLauncherUnknownEditorError>()(
|
||||
"DesktopLauncherUnknownEditorError",
|
||||
{
|
||||
editor: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unknown desktop editor: ${this.editor}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherCommandNotFoundError extends Schema.TaggedErrorClass<DesktopLauncherCommandNotFoundError>()(
|
||||
"DesktopLauncherCommandNotFoundError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
target: Schema.optional(Schema.String),
|
||||
editor: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = this.editor
|
||||
? ` for editor ${this.editor}`
|
||||
: this.target
|
||||
? ` for ${this.target}`
|
||||
: "";
|
||||
return `Desktop launcher command not found in ${this.operation}: ${this.command}${target}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherSpawnError extends Schema.TaggedErrorClass<DesktopLauncherSpawnError>()(
|
||||
"DesktopLauncherSpawnError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
target: Schema.optional(Schema.String),
|
||||
editor: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop launcher failed to spawn ${this.command} in ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherNonZeroExitError extends Schema.TaggedErrorClass<DesktopLauncherNonZeroExitError>()(
|
||||
"DesktopLauncherNonZeroExitError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
exitCode: Schema.Number,
|
||||
target: Schema.optional(Schema.String),
|
||||
editor: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop launcher command exited non-zero in ${this.operation}: ${this.command} (code=${this.exitCode})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLauncherLaunchAttemptsExhaustedError extends Schema.TaggedErrorClass<DesktopLauncherLaunchAttemptsExhaustedError>()(
|
||||
"DesktopLauncherLaunchAttemptsExhaustedError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
target: Schema.optional(Schema.String),
|
||||
editor: Schema.optional(Schema.String),
|
||||
attempts: Schema.Array(DesktopLauncherLaunchAttemptSchema),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const subject = this.editor ? `editor ${this.editor}` : this.target ? this.target : "target";
|
||||
return `Desktop launcher exhausted all launch attempts in ${this.operation} for ${subject}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopLauncherError = Schema.Union([
|
||||
DesktopLauncherCommandNotFoundError,
|
||||
DesktopLauncherDiscoveryError,
|
||||
DesktopLauncherLaunchAttemptsExhaustedError,
|
||||
DesktopLauncherNonZeroExitError,
|
||||
DesktopLauncherSpawnError,
|
||||
DesktopLauncherUnknownEditorError,
|
||||
DesktopLauncherValidationError,
|
||||
]);
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
export interface OpenApplicationInput {
|
||||
readonly name: string | ReadonlyArray<string>;
|
||||
readonly arguments?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface OpenExternalInput {
|
||||
readonly target: string;
|
||||
readonly wait?: boolean;
|
||||
readonly background?: boolean;
|
||||
readonly newInstance?: boolean;
|
||||
readonly allowNonzeroExitCode?: boolean;
|
||||
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
|
||||
}
|
||||
|
||||
export interface DesktopLauncherShape {
|
||||
readonly getAvailableEditors: Effect.Effect<
|
||||
ReadonlyArray<EditorId>,
|
||||
DesktopLauncherDiscoveryError
|
||||
>;
|
||||
readonly openExternal: (
|
||||
input: OpenExternalInput,
|
||||
) => Effect.Effect<
|
||||
void,
|
||||
| DesktopLauncherCommandNotFoundError
|
||||
| DesktopLauncherLaunchAttemptsExhaustedError
|
||||
| DesktopLauncherNonZeroExitError
|
||||
| DesktopLauncherSpawnError
|
||||
| DesktopLauncherValidationError
|
||||
>;
|
||||
readonly openBrowser: (
|
||||
target: string,
|
||||
options?: Omit<OpenExternalInput, "target">,
|
||||
) => Effect.Effect<
|
||||
void,
|
||||
| DesktopLauncherCommandNotFoundError
|
||||
| DesktopLauncherLaunchAttemptsExhaustedError
|
||||
| DesktopLauncherNonZeroExitError
|
||||
| DesktopLauncherSpawnError
|
||||
| DesktopLauncherValidationError
|
||||
>;
|
||||
readonly openInEditor: (
|
||||
input: OpenInEditorInput,
|
||||
) => Effect.Effect<
|
||||
void,
|
||||
| DesktopLauncherCommandNotFoundError
|
||||
| DesktopLauncherLaunchAttemptsExhaustedError
|
||||
| DesktopLauncherNonZeroExitError
|
||||
| DesktopLauncherSpawnError
|
||||
| DesktopLauncherUnknownEditorError
|
||||
| DesktopLauncherValidationError
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopLauncher extends ServiceMap.Service<DesktopLauncher, DesktopLauncherShape>()(
|
||||
"t3/desktop-launcher",
|
||||
) {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { killChildProcessTree } from "./killTree";
|
||||
|
||||
describe("killChildProcessTree", () => {
|
||||
it("uses taskkill on Windows when a pid is available", () => {
|
||||
const kill = vi.fn();
|
||||
const spawnSyncImpl = vi.fn(() => ({ status: 0 }));
|
||||
|
||||
killChildProcessTree({ pid: 123, kill } as never, "SIGTERM", {
|
||||
platform: "win32",
|
||||
spawnSyncImpl,
|
||||
});
|
||||
|
||||
expect(spawnSyncImpl).toHaveBeenCalledWith("taskkill", ["/pid", "123", "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to direct kill when taskkill fails", () => {
|
||||
const kill = vi.fn();
|
||||
const spawnSyncImpl = vi.fn(() => ({ status: 1 }));
|
||||
|
||||
killChildProcessTree({ pid: 456, kill } as never, "SIGKILL", {
|
||||
platform: "win32",
|
||||
spawnSyncImpl,
|
||||
});
|
||||
|
||||
expect(kill).toHaveBeenCalledWith("SIGKILL");
|
||||
});
|
||||
|
||||
it("falls back to direct kill when taskkill cannot be spawned", () => {
|
||||
const kill = vi.fn();
|
||||
const spawnSyncImpl = vi.fn(() => ({ status: null, error: new Error("ENOENT") }));
|
||||
|
||||
killChildProcessTree({ pid: 654, kill } as never, "SIGTERM", {
|
||||
platform: "win32",
|
||||
spawnSyncImpl,
|
||||
});
|
||||
|
||||
expect(kill).toHaveBeenCalledWith("SIGTERM");
|
||||
});
|
||||
|
||||
it("kills directly on non-Windows platforms", () => {
|
||||
const kill = vi.fn();
|
||||
const spawnSyncImpl = vi.fn();
|
||||
|
||||
killChildProcessTree({ pid: 789, kill } as never, "SIGTERM", {
|
||||
platform: "darwin",
|
||||
spawnSyncImpl,
|
||||
});
|
||||
|
||||
expect(spawnSyncImpl).not.toHaveBeenCalled();
|
||||
expect(kill).toHaveBeenCalledWith("SIGTERM");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { spawnSync, type ChildProcess as NodeChildProcess } from "node:child_process";
|
||||
|
||||
type KillableChildProcess = Pick<NodeChildProcess, "kill" | "pid">;
|
||||
type TaskkillResult = {
|
||||
readonly status: number | null;
|
||||
readonly error?: Error;
|
||||
};
|
||||
type TaskkillRunner = (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { readonly stdio: "ignore" },
|
||||
) => TaskkillResult;
|
||||
|
||||
interface KillChildProcessTreeOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly spawnSyncImpl?: TaskkillRunner;
|
||||
}
|
||||
|
||||
/**
|
||||
* On Windows with shell-backed processes, direct kill only terminates the
|
||||
* wrapper process. Use `taskkill /T` first so the spawned process tree exits.
|
||||
*/
|
||||
export function killChildProcessTree(
|
||||
child: KillableChildProcess,
|
||||
signal: NodeJS.Signals = "SIGTERM",
|
||||
options: KillChildProcessTreeOptions = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
const result = (options.spawnSyncImpl ?? spawnSync)(
|
||||
"taskkill",
|
||||
["/pid", String(child.pid), "/T", "/F"],
|
||||
{
|
||||
stdio: "ignore",
|
||||
},
|
||||
);
|
||||
if (!result.error && result.status === 0) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Fall through to direct kill when taskkill is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
child.kill(signal);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTextChunkWithinByteLimit, limitChunkToByteLimit } from "./outputBuffer";
|
||||
|
||||
describe("outputBuffer", () => {
|
||||
it("keeps a full chunk when it fits within the byte limit", () => {
|
||||
const chunk = Buffer.from("hello");
|
||||
|
||||
expect(limitChunkToByteLimit(chunk, 2, 10)).toEqual({
|
||||
chunk,
|
||||
nextBytes: 7,
|
||||
truncated: false,
|
||||
overflow: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("truncates a chunk to the remaining byte budget", () => {
|
||||
const chunk = Buffer.from("abcdef");
|
||||
const limited = limitChunkToByteLimit(chunk, 3, 5);
|
||||
|
||||
expect(Buffer.from(limited.chunk).toString()).toBe("ab");
|
||||
expect(limited.nextBytes).toBe(5);
|
||||
expect(limited.truncated).toBe(true);
|
||||
expect(limited.overflow).toBe(true);
|
||||
});
|
||||
|
||||
it("appends only the bytes that fit", () => {
|
||||
expect(appendTextChunkWithinByteLimit("pre", 3, Buffer.from("abcdef"), 7)).toEqual({
|
||||
next: "preabcd",
|
||||
nextBytes: 7,
|
||||
truncated: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
export interface LimitedChunk {
|
||||
readonly chunk: Uint8Array;
|
||||
readonly nextBytes: number;
|
||||
readonly truncated: boolean;
|
||||
readonly overflow: boolean;
|
||||
}
|
||||
|
||||
export function limitChunkToByteLimit(
|
||||
chunk: Uint8Array,
|
||||
currentBytes: number,
|
||||
maxBytes: number,
|
||||
): LimitedChunk {
|
||||
const remaining = maxBytes - currentBytes;
|
||||
if (remaining <= 0) {
|
||||
return {
|
||||
chunk: new Uint8Array(),
|
||||
nextBytes: currentBytes,
|
||||
truncated: true,
|
||||
overflow: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (chunk.byteLength <= remaining) {
|
||||
return {
|
||||
chunk,
|
||||
nextBytes: currentBytes + chunk.byteLength,
|
||||
truncated: false,
|
||||
overflow: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
chunk: chunk.subarray(0, remaining),
|
||||
nextBytes: currentBytes + remaining,
|
||||
truncated: true,
|
||||
overflow: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function appendTextChunkWithinByteLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
chunk: Uint8Array,
|
||||
maxBytes: number,
|
||||
): {
|
||||
readonly next: string;
|
||||
readonly nextBytes: number;
|
||||
readonly truncated: boolean;
|
||||
} {
|
||||
const limited = limitChunkToByteLimit(chunk, currentBytes, maxBytes);
|
||||
|
||||
return {
|
||||
next: `${target}${Buffer.from(limited.chunk).toString()}`,
|
||||
nextBytes: limited.nextBytes,
|
||||
truncated: limited.truncated,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { runProbeProcess } from "./runProbeProcess";
|
||||
|
||||
describe("runProbeProcess", () => {
|
||||
it("forces truncated output mode while preserving other options", async () => {
|
||||
const runner = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
await runProbeProcess(
|
||||
"ps",
|
||||
["-eo", "pid=,ppid="],
|
||||
{
|
||||
timeoutMs: 500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 1024,
|
||||
cwd: "/tmp",
|
||||
},
|
||||
runner,
|
||||
);
|
||||
|
||||
expect(runner).toHaveBeenCalledWith("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 1024,
|
||||
cwd: "/tmp",
|
||||
outputMode: "truncate",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { runProcess, type ProcessRunOptions, type ProcessRunResult } from "../processRunner";
|
||||
|
||||
type ProcessRunner = typeof runProcess;
|
||||
|
||||
export type ProbeProcessOptions = Omit<ProcessRunOptions, "stdin" | "outputMode">;
|
||||
|
||||
export function runProbeProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProbeProcessOptions = {},
|
||||
runner: ProcessRunner = runProcess,
|
||||
): Promise<ProcessRunResult> {
|
||||
return runner(command, args, {
|
||||
...options,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
isWindowsBatchShim,
|
||||
isWindowsCommandNotFound,
|
||||
makeWindowsCmdCommandLine,
|
||||
makeWindowsCmdSpawnArguments,
|
||||
quoteForWindowsCmd,
|
||||
resolveWindowsCommandShell,
|
||||
} from "./windowsCommand";
|
||||
|
||||
it("resolves cmd.exe from Windows command shell environment variables", () => {
|
||||
assert.equal(resolveWindowsCommandShell({}), "cmd.exe");
|
||||
assert.equal(
|
||||
resolveWindowsCommandShell({ COMSPEC: "C:\\Windows\\System32\\cmd.exe" }),
|
||||
"C:\\Windows\\System32\\cmd.exe",
|
||||
);
|
||||
assert.equal(
|
||||
resolveWindowsCommandShell({ ComSpec: "C:\\custom\\cmd.exe" }),
|
||||
"C:\\custom\\cmd.exe",
|
||||
);
|
||||
});
|
||||
|
||||
it("detects Windows batch shims case-insensitively", () => {
|
||||
assert.equal(isWindowsBatchShim("code.cmd"), true);
|
||||
assert.equal(isWindowsBatchShim("C:\\tools\\launcher.BAT"), true);
|
||||
assert.equal(isWindowsBatchShim("/tmp/code.exe"), false);
|
||||
});
|
||||
|
||||
it("detects Windows command-not-found exits", () => {
|
||||
assert.equal(isWindowsCommandNotFound(9009, "", "win32"), true);
|
||||
assert.equal(
|
||||
isWindowsCommandNotFound(
|
||||
1,
|
||||
"'foo' is not recognized as an internal or external command",
|
||||
"win32",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(isWindowsCommandNotFound(9009, "", "darwin"), false);
|
||||
});
|
||||
|
||||
it("quotes Windows cmd values safely", () => {
|
||||
assert.equal(
|
||||
quoteForWindowsCmd('C:\\work\\100% real\\"quoted".ts:12:4'),
|
||||
'"C:\\work\\100%% real\\""quoted"".ts:12:4"',
|
||||
);
|
||||
});
|
||||
|
||||
it("builds Windows cmd command lines safely", () => {
|
||||
assert.equal(
|
||||
makeWindowsCmdCommandLine("code.cmd", ["--goto", "file.ts:12:4"]),
|
||||
'""code.cmd" "--goto" "file.ts:12:4""',
|
||||
);
|
||||
});
|
||||
|
||||
it("builds Windows cmd spawn arguments with cmd control flags", () => {
|
||||
assert.deepEqual(makeWindowsCmdSpawnArguments("code.cmd", ["--goto", "file.ts:1:1"]), [
|
||||
"/d",
|
||||
"/v:off",
|
||||
"/s",
|
||||
"/c",
|
||||
'""code.cmd" "--goto" "file.ts:1:1""',
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
export function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(
|
||||
code: number | null,
|
||||
stderr: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean {
|
||||
if (platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
export function isWindowsBatchShim(filePath: string): boolean {
|
||||
return /\.(cmd|bat)$/i.test(filePath);
|
||||
}
|
||||
|
||||
export function quoteForWindowsCmd(value: string): string {
|
||||
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
export function makeWindowsCmdCommandLine(
|
||||
commandPath: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): string {
|
||||
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
|
||||
}
|
||||
|
||||
export function makeWindowsCmdSpawnArguments(
|
||||
commandPath: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
return ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(commandPath, args)];
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
import { killChildProcessTree } from "./process/killTree";
|
||||
import { appendTextChunkWithinByteLimit } from "./process/outputBuffer";
|
||||
import { isWindowsCommandNotFound } from "./process/windowsCommand";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -37,12 +40,6 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
@@ -80,51 +77,6 @@ function normalizeBufferError(
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 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 killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): 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(signal);
|
||||
}
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
chunk: Buffer,
|
||||
maxBytes: number,
|
||||
): {
|
||||
next: string;
|
||||
nextBytes: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
const remaining = maxBytes - currentBytes;
|
||||
if (remaining <= 0) {
|
||||
return { next: target, nextBytes: currentBytes, truncated: true };
|
||||
}
|
||||
if (chunk.length <= remaining) {
|
||||
return {
|
||||
next: `${target}${chunk.toString()}`,
|
||||
nextBytes: currentBytes + chunk.length,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
next: `${target}${chunk.subarray(0, remaining).toString()}`,
|
||||
nextBytes: currentBytes + remaining,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function runProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
@@ -154,9 +106,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killChild(child, "SIGTERM");
|
||||
killChildProcessTree(child, "SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killChild(child, "SIGKILL");
|
||||
killChildProcessTree(child, "SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -171,7 +123,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killChild(child, "SIGTERM");
|
||||
killChildProcessTree(child, "SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -183,7 +135,12 @@ export async function runProcess(
|
||||
const byteLength = chunkBuffer.length;
|
||||
if (stream === "stdout") {
|
||||
if (outputMode === "truncate") {
|
||||
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
|
||||
const appended = appendTextChunkWithinByteLimit(
|
||||
stdout,
|
||||
stdoutBytes,
|
||||
chunkBuffer,
|
||||
maxBufferBytes,
|
||||
);
|
||||
stdout = appended.next;
|
||||
stdoutBytes = appended.nextBytes;
|
||||
stdoutTruncated = stdoutTruncated || appended.truncated;
|
||||
@@ -196,7 +153,12 @@ export async function runProcess(
|
||||
}
|
||||
} else {
|
||||
if (outputMode === "truncate") {
|
||||
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
|
||||
const appended = appendTextChunkWithinByteLimit(
|
||||
stderr,
|
||||
stderrBytes,
|
||||
chunkBuffer,
|
||||
maxBufferBytes,
|
||||
);
|
||||
stderr = appended.next;
|
||||
stderrBytes = appended.nextBytes;
|
||||
stderrTruncated = stderrTruncated || appended.truncated;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
|
||||
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-favicon-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
describe("resolvePath", () => {
|
||||
it.effect("prefers well-known favicon files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from project source files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="/brand/logo.svg">');
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when no icon is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
ProjectFaviconResolver,
|
||||
type ProjectFaviconResolverShape,
|
||||
} from "../Services/ProjectFaviconResolver.ts";
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
] as const;
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
] as const;
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const resolveIconHref = (projectCwd: string, href: string): string[] => {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
};
|
||||
|
||||
const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
};
|
||||
|
||||
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
|
||||
projectCwd: string,
|
||||
candidates: ReadonlyArray<string>,
|
||||
): Effect.fn.Return<string | null> {
|
||||
for (const candidate of candidates) {
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
continue;
|
||||
}
|
||||
const stats = yield* fileSystem
|
||||
.stat(candidate)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (stats?.type === "File") {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
|
||||
"ProjectFaviconResolver.resolvePath",
|
||||
)(function* (cwd: string): Effect.fn.Return<string | null> {
|
||||
for (const candidate of FAVICON_CANDIDATES) {
|
||||
const resolved = path.join(cwd, candidate);
|
||||
const existing = yield* findExistingFile(cwd, [resolved]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sourceFile of ICON_SOURCE_FILES) {
|
||||
const sourcePath = path.join(cwd, sourceFile);
|
||||
const source = yield* fileSystem
|
||||
.readFileString(sourcePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
const href = extractIconHref(source);
|
||||
if (!href) {
|
||||
continue;
|
||||
}
|
||||
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return {
|
||||
resolvePath,
|
||||
} satisfies ProjectFaviconResolverShape;
|
||||
});
|
||||
|
||||
export const ProjectFaviconResolverLive = Layer.effect(
|
||||
ProjectFaviconResolver,
|
||||
makeProjectFaviconResolver,
|
||||
);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* ProjectFaviconResolver - Effect service contract for project icon discovery.
|
||||
*
|
||||
* Resolves a representative favicon or app icon file for a workspace by
|
||||
* checking common file locations and project source metadata.
|
||||
*
|
||||
* @module ProjectFaviconResolver
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolverShape - Service API for project favicon lookup.
|
||||
*/
|
||||
export interface ProjectFaviconResolverShape {
|
||||
/**
|
||||
* Resolve a favicon or icon file path for the provided workspace root.
|
||||
*
|
||||
* Returns `null` when no candidate icon file can be found.
|
||||
*/
|
||||
readonly resolvePath: (cwd: string) => Effect.Effect<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolver - Service tag for project favicon resolution.
|
||||
*/
|
||||
export class ProjectFaviconResolver extends ServiceMap.Service<
|
||||
ProjectFaviconResolver,
|
||||
ProjectFaviconResolverShape
|
||||
>()("t3/project/Services/ProjectFaviconResolver") {}
|
||||
@@ -3,7 +3,11 @@ import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
interface HttpResponse {
|
||||
@@ -23,11 +27,25 @@ function makeTempDir(prefix: string): string {
|
||||
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
void Effect.runPromise(
|
||||
tryHandleProjectFaviconRequest(url, res).pipe(
|
||||
Effect.provide(ProjectFaviconResolverLive),
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.flatMap((handled) =>
|
||||
handled
|
||||
? Effect.void
|
||||
: Effect.sync(() => {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
}),
|
||||
),
|
||||
),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
@@ -11,161 +13,64 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
];
|
||||
export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")(
|
||||
function* (
|
||||
url: URL,
|
||||
res: http.ServerResponse,
|
||||
): Effect.fn.Return<boolean, never, ProjectFaviconResolver | FileSystem.FileSystem> {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
];
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconHref(projectCwd: string, href: string): string[] {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
}
|
||||
|
||||
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Read error");
|
||||
return;
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(FALLBACK_FAVICON_SVG);
|
||||
}
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter");
|
||||
return true;
|
||||
}
|
||||
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const resolvedPath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("Missing cwd parameter");
|
||||
if (!resolvedPath) {
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
FALLBACK_FAVICON_SVG,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
const data = yield* fileSystem
|
||||
.readFile(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Read error");
|
||||
return true;
|
||||
}
|
||||
|
||||
const ext = path.extname(resolvedPath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
data,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
||||
if (index >= paths.length) {
|
||||
onExhausted();
|
||||
return;
|
||||
}
|
||||
const candidate = paths[index]!;
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
serveFallbackFavicon(res);
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
fs.readFile(sourceFile, "utf8", (err, content) => {
|
||||
if (err) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const href = extractIconHref(content);
|
||||
if (!href) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const candidates = resolveIconHref(projectCwd, href);
|
||||
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
||||
});
|
||||
};
|
||||
|
||||
const tryCandidates = (index: number): void => {
|
||||
if (index >= FAVICON_CANDIDATES.length) {
|
||||
trySourceFiles(0);
|
||||
return;
|
||||
}
|
||||
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
tryCandidates(0);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
import { killChildProcessTree } from "../process/killTree";
|
||||
|
||||
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 {
|
||||
killChildProcessTree(child);
|
||||
}
|
||||
|
||||
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(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import type {
|
||||
ServerProvider,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner";
|
||||
import { isWindowsCommandNotFound } from "../process/windowsCommand";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -34,6 +34,10 @@ import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
|
||||
import { PtyAdapter } from "./terminal/Services/PTY";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
type RuntimePtyAdapterLoader = {
|
||||
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
|
||||
@@ -91,7 +95,8 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const textGenerationLayer = RoutingTextGenerationLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const gitCoreLayer = GitCoreLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive;
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -116,11 +121,11 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
@@ -131,16 +136,26 @@ export function makeServerRuntimeServicesLayer() {
|
||||
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
|
||||
const workspacePathsLayer = WorkspacePathsLive;
|
||||
const workspaceEntriesLayer = WorkspaceEntriesLive;
|
||||
const workspaceFileSystemLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(workspacePathsLayer),
|
||||
Layer.provide(workspaceEntriesLayer),
|
||||
);
|
||||
const projectFaviconResolverLayer = ProjectFaviconResolverLive;
|
||||
|
||||
return Layer.mergeAll(
|
||||
orchestrationReactorLayer,
|
||||
GitCoreLive,
|
||||
workspacePathsLayer,
|
||||
workspaceEntriesLayer,
|
||||
workspaceFileSystemLayer,
|
||||
projectFaviconResolverLayer,
|
||||
gitManagerLayer,
|
||||
terminalLayer,
|
||||
KeybindingsLive,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
).pipe(Layer.provideMerge(gitCoreLayer), Layer.provideMerge(NodeServices.layer));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -14,47 +14,81 @@ import {
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSessionStatus,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { PtyProcess } from "./PTY";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
|
||||
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
if (this.reason === "notDirectory") {
|
||||
return `Terminal cwd is not a directory: ${this.cwd}`;
|
||||
}
|
||||
if (this.reason === "notFound") {
|
||||
return `Terminal cwd does not exist: ${this.cwd}`;
|
||||
}
|
||||
const causeMessage =
|
||||
this.cause && typeof this.cause === "object" && "message" in this.cause
|
||||
? this.cause.message
|
||||
: undefined;
|
||||
return causeMessage
|
||||
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
|
||||
: `Failed to access terminal cwd: ${this.cwd}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
|
||||
"TerminalHistoryError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "truncate", "migrate"]),
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalStartInput extends TerminalOpenInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
|
||||
"TerminalSessionLookupError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
|
||||
"TerminalNotRunningError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const TerminalError = Schema.Union([
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalNotRunningError,
|
||||
]);
|
||||
export type TerminalError = typeof TerminalError.Type;
|
||||
|
||||
/**
|
||||
* TerminalManagerShape - Service API for terminal session lifecycle operations.
|
||||
*/
|
||||
@@ -101,14 +135,13 @@ export interface TerminalManagerShape {
|
||||
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
|
||||
|
||||
/**
|
||||
* Subscribe to terminal runtime events.
|
||||
* Subscribe to terminal runtime events with a direct callback.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
|
||||
|
||||
/**
|
||||
* Dispose all managed terminal resources.
|
||||
*/
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
readonly subscribe: (
|
||||
listener: (event: TerminalEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import fsPromises from "node:fs/promises";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-entries-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const gitCore = yield* GitCore;
|
||||
const dir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: opts?.prefix ?? "t3code-workspace-entries-",
|
||||
});
|
||||
if (opts?.git) {
|
||||
yield* gitCore.initRepo({ cwd: dir });
|
||||
}
|
||||
return dir;
|
||||
});
|
||||
|
||||
function writeTextFile(
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(absolutePath, contents);
|
||||
});
|
||||
}
|
||||
|
||||
const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "WorkspaceEntries.test.git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
return yield* workspaceEntries.search(input);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("search", () => {
|
||||
it.effect("returns files and directories relative to cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/index.ts");
|
||||
yield* writeTextFile(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, ".git/HEAD");
|
||||
yield* writeTextFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/components");
|
||||
expect(paths).toContain("src/components/Composer.tsx");
|
||||
expect(paths).toContain("README.md");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false);
|
||||
expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters and ranks entries by query", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
expect(result.entries.length).toBeGreaterThan(0);
|
||||
expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true);
|
||||
expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe(
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports fuzzy subsequence queries for composer path search", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(result.entries.length).toBeGreaterThan(0);
|
||||
expect(paths).toContain("src/components");
|
||||
expect(paths).toContain("src/components/Composer.tsx");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tracks truncation without sorting every fuzzy match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
|
||||
|
||||
expect(result.entries).toHaveLength(1);
|
||||
expect(result.truncated).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes gitignored paths for git repositories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
|
||||
yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
yield* writeTextFile(cwd, "ignored.txt", "ignore me");
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths).not.toContain("ignored.txt");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes tracked paths that match ignore rules", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({
|
||||
prefix: "t3code-workspace-tracked-gitignore-",
|
||||
git: true,
|
||||
});
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes .convex in non-git workspaces", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" });
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates concurrent index builds for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-concurrent-build-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
yield* Effect.all(
|
||||
[
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
expect(rootReadCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("limits concurrent directory reads while walking the filesystem", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-read-concurrency-" });
|
||||
yield* Effect.forEach(
|
||||
Array.from({ length: 80 }, (_, index) => index),
|
||||
(index) => writeTextFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
expect(peakReads).toBeLessThanOrEqual(32);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,478 @@
|
||||
import fsPromises from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type ProjectEntry } from "@t3tools/contracts";
|
||||
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
WorkspaceEntries,
|
||||
WorkspaceEntriesError,
|
||||
type WorkspaceEntriesShape,
|
||||
} from "../Services/WorkspaceEntries.ts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: SearchableWorkspaceEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedPath: string;
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
return {
|
||||
...entry,
|
||||
normalizedPath,
|
||||
normalizedName: basenameOf(normalizedPath),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
const processErrorDetail = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const gitOption = yield* Effect.serviceOption(GitCore);
|
||||
|
||||
const isInsideGitWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
|
||||
onNone: () => Effect.succeed(false),
|
||||
});
|
||||
|
||||
const filterGitIgnoredPaths = (
|
||||
cwd: string,
|
||||
relativePaths: string[],
|
||||
): Effect.Effect<string[], never> =>
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) =>
|
||||
git.filterIgnoredPaths(cwd, relativePaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
),
|
||||
onNone: () => Effect.succeed(relativePaths),
|
||||
});
|
||||
|
||||
const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")(
|
||||
function* (cwd: string) {
|
||||
if (Option.isNone(gitOption)) {
|
||||
return null;
|
||||
}
|
||||
if (!(yield* isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = yield* gitOption.value
|
||||
.listWorkspaceFiles(cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
|
||||
if (!listedFiles) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = [...listedFiles.paths]
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(directoryPath): ProjectEntry => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
const fileEntries = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(filePath): ProjectEntry => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
|
||||
cwd: string,
|
||||
relativeDir: string,
|
||||
): Effect.fn.Return<
|
||||
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
|
||||
WorkspaceEntriesError
|
||||
> {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceEntriesError({
|
||||
cwd,
|
||||
operation: "workspaceEntries.readDirectoryEntries",
|
||||
detail: processErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.catchIf(
|
||||
() => relativeDir.length > 0,
|
||||
() => Effect.succeed({ relativeDir, dirents: null }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWorkspaceIndexFromFilesystem = Effect.fn(
|
||||
"WorkspaceEntries.buildWorkspaceIndexFromFilesystem",
|
||||
)(function* (cwd: string): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
|
||||
const directoryEntries = yield* Effect.forEach(
|
||||
currentDirectories,
|
||||
(relativeDir) => readDirectoryEntries(cwd, relativeDir),
|
||||
{ concurrency: WORKSPACE_SCAN_READDIR_CONCURRENCY },
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry = toSearchableWorkspaceEntry({
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
});
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
});
|
||||
|
||||
const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* (
|
||||
cwd: string,
|
||||
): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
return yield* buildWorkspaceIndexFromFilesystem(cwd);
|
||||
});
|
||||
|
||||
const workspaceIndexCache = yield* Cache.makeWith<string, WorkspaceIndex, WorkspaceEntriesError>({
|
||||
capacity: WORKSPACE_CACHE_MAX_KEYS,
|
||||
lookup: buildWorkspaceIndex,
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero,
|
||||
});
|
||||
|
||||
const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")(
|
||||
function* (cwd) {
|
||||
return yield* Cache.invalidate(workspaceIndexCache, cwd);
|
||||
},
|
||||
);
|
||||
|
||||
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
|
||||
function* (input) {
|
||||
return yield* Cache.get(workspaceIndexCache, input.cwd).pipe(
|
||||
Effect.map((index) => {
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
|
||||
for (const entry of index.entries) {
|
||||
const score = scoreEntry(entry, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
invalidate,
|
||||
search,
|
||||
} satisfies WorkspaceEntriesShape;
|
||||
});
|
||||
|
||||
export const WorkspaceEntriesLive = Layer.effect(WorkspaceEntries, makeWorkspaceEntries);
|
||||
@@ -0,0 +1,135 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const ProjectLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provide(WorkspaceEntriesLive),
|
||||
);
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-files-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-workspace-files-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
|
||||
describe("writeFile", () => {
|
||||
it.effect("writes files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const result = yield* workspaceFileSystem.writeFile({
|
||||
cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
const saved = yield* fileSystem
|
||||
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
|
||||
.pipe(Effect.orDie);
|
||||
|
||||
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
|
||||
expect(saved).toBe("# Plan\n");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("invalidates workspace entry search cache after writes", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
|
||||
|
||||
const beforeWrite = yield* workspaceEntries.search({
|
||||
cwd,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(beforeWrite).toEqual({
|
||||
entries: [],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
yield* workspaceFileSystem.writeFile({
|
||||
cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
|
||||
const afterWrite = yield* workspaceEntries.search({
|
||||
cwd,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(afterWrite.entries).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
|
||||
);
|
||||
expect(afterWrite.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects writes outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.writeFile({
|
||||
cwd,
|
||||
relativePath: "../escape.md",
|
||||
contents: "# nope\n",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
|
||||
const escapedPath = path.resolve(cwd, "..", "escape.md");
|
||||
const escapedStat = yield* fileSystem
|
||||
.stat(escapedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
expect(escapedStat).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
WorkspaceFileSystem,
|
||||
WorkspaceFileSystemError,
|
||||
type WorkspaceFileSystemShape,
|
||||
} from "../Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
|
||||
export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn(
|
||||
"WorkspaceFileSystem.writeFile",
|
||||
)(function* (input) {
|
||||
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.makeDirectory",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.writeFile",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
return { relativePath: target.relativePath };
|
||||
});
|
||||
return { writeFile } satisfies WorkspaceFileSystemShape;
|
||||
});
|
||||
|
||||
export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem);
|
||||
@@ -0,0 +1,113 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-paths-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspacePathsLive", (it) => {
|
||||
describe("normalizeWorkspaceRoot", () => {
|
||||
it.effect("resolves an existing directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
|
||||
const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd);
|
||||
|
||||
expect(resolved).toBe(cwd);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects missing directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const error = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(path.join(cwd, "missing"))
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Workspace root does not exist:");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects file paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
const filePath = path.join(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, "README.md", "# hi\n");
|
||||
|
||||
const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Workspace root is not a directory:");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveRelativePathWithinRoot", () => {
|
||||
it.effect("resolves relative paths inside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
});
|
||||
|
||||
expect(resolved).toEqual({
|
||||
absolutePath: path.join(cwd, "plans/effect-rpc.md"),
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects paths that escape the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
|
||||
const error = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "../escape.md",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
WorkspacePaths,
|
||||
WorkspacePathOutsideRootError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspaceRootNotExistsError,
|
||||
type WorkspacePathsShape,
|
||||
} from "../Services/WorkspacePaths.ts";
|
||||
|
||||
function toPosixRelativePath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
export const makeWorkspacePaths = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn(
|
||||
"WorkspacePaths.normalizeWorkspaceRoot",
|
||||
)(function* (workspaceRoot) {
|
||||
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new WorkspaceRootNotExistsError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new WorkspaceRootNotDirectoryError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
const resolveRelativePathWithinRoot: WorkspacePathsShape["resolveRelativePathWithinRoot"] =
|
||||
Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) {
|
||||
const normalizedInputPath = input.relativePath.trim();
|
||||
if (path.isAbsolute(normalizedInputPath)) {
|
||||
return yield* new WorkspacePathOutsideRootError({
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
}
|
||||
|
||||
const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);
|
||||
const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));
|
||||
if (
|
||||
relativeToRoot.length === 0 ||
|
||||
relativeToRoot === "." ||
|
||||
relativeToRoot.startsWith("../") ||
|
||||
relativeToRoot === ".." ||
|
||||
path.isAbsolute(relativeToRoot)
|
||||
) {
|
||||
return yield* new WorkspacePathOutsideRootError({
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
absolutePath,
|
||||
relativePath: relativeToRoot,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
normalizeWorkspaceRoot,
|
||||
resolveRelativePathWithinRoot,
|
||||
} satisfies WorkspacePathsShape;
|
||||
});
|
||||
|
||||
export const WorkspacePathsLive = Layer.effect(WorkspacePaths, makeWorkspacePaths);
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* WorkspaceEntries - Effect service contract for cached workspace entry search.
|
||||
*
|
||||
* Owns indexed workspace entry search plus cache invalidation for workspace
|
||||
* roots when the underlying filesystem changes.
|
||||
*
|
||||
* @module WorkspaceEntries
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
|
||||
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
|
||||
"WorkspaceEntriesError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* WorkspaceEntriesShape - Service API for workspace entry search and cache
|
||||
* invalidation.
|
||||
*/
|
||||
export interface WorkspaceEntriesShape {
|
||||
/**
|
||||
* Search indexed workspace entries for files and directories matching the
|
||||
* provided query.
|
||||
*/
|
||||
readonly search: (
|
||||
input: ProjectSearchEntriesInput,
|
||||
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
|
||||
|
||||
/**
|
||||
* Drop any cached workspace entries for the given workspace root.
|
||||
*/
|
||||
readonly invalidate: (cwd: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceEntries - Service tag for cached workspace entry search.
|
||||
*/
|
||||
export class WorkspaceEntries extends ServiceMap.Service<WorkspaceEntries, WorkspaceEntriesShape>()(
|
||||
"t3/workspace/Services/WorkspaceEntries",
|
||||
) {}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
|
||||
*
|
||||
* Owns workspace-root-relative file write operations and their associated
|
||||
* safety checks and cache invalidation hooks.
|
||||
*
|
||||
* @module WorkspaceFileSystem
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts";
|
||||
import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts";
|
||||
|
||||
export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceFileSystemError>()(
|
||||
"WorkspaceFileSystemError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
relativePath: Schema.optional(Schema.String),
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystemShape - Service API for workspace-relative file operations.
|
||||
*/
|
||||
export interface WorkspaceFileSystemShape {
|
||||
/**
|
||||
* Write a file relative to the workspace root.
|
||||
*
|
||||
* Creates parent directories as needed and rejects paths that escape the
|
||||
* workspace root.
|
||||
*/
|
||||
readonly writeFile: (
|
||||
input: ProjectWriteFileInput,
|
||||
) => Effect.Effect<
|
||||
ProjectWriteFileResult,
|
||||
WorkspaceFileSystemError | WorkspacePathOutsideRootError
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystem - Service tag for workspace file operations.
|
||||
*/
|
||||
export class WorkspaceFileSystem extends ServiceMap.Service<
|
||||
WorkspaceFileSystem,
|
||||
WorkspaceFileSystemShape
|
||||
>()("t3/workspace/Services/WorkspaceFileSystem") {}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* WorkspacePaths - Effect service contract for workspace path handling.
|
||||
*
|
||||
* Owns normalization and validation of workspace roots plus safe resolution of
|
||||
* workspace-root-relative paths.
|
||||
*
|
||||
* @module WorkspacePaths
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()(
|
||||
"WorkspaceRootNotExistsError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(
|
||||
"WorkspaceRootNotDirectoryError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<WorkspacePathOutsideRootError>()(
|
||||
"WorkspacePathOutsideRootError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
relativePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace file path must be relative to the project root: ${this.relativePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const WorkspacePathsError = Schema.Union([
|
||||
WorkspaceRootNotExistsError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspacePathOutsideRootError,
|
||||
]);
|
||||
export type WorkspacePathsError = typeof WorkspacePathsError.Type;
|
||||
|
||||
/**
|
||||
* WorkspacePathsShape - Service API for workspace path normalization and guards.
|
||||
*/
|
||||
export interface WorkspacePathsShape {
|
||||
/**
|
||||
* Normalize a user-provided workspace root and verify it exists as a directory.
|
||||
*/
|
||||
readonly normalizeWorkspaceRoot: (
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<string, WorkspaceRootNotExistsError | WorkspaceRootNotDirectoryError>;
|
||||
|
||||
/**
|
||||
* Resolve a relative path within a validated workspace root.
|
||||
*
|
||||
* Rejects absolute paths and traversal attempts outside the workspace root.
|
||||
*/
|
||||
readonly resolveRelativePathWithinRoot: (input: {
|
||||
workspaceRoot: string;
|
||||
relativePath: string;
|
||||
}) => Effect.Effect<
|
||||
{ absolutePath: string; relativePath: string },
|
||||
WorkspacePathOutsideRootError
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspacePaths - Service tag for workspace path normalization and resolution.
|
||||
*/
|
||||
export class WorkspacePaths extends ServiceMap.Service<WorkspacePaths, WorkspacePathsShape>()(
|
||||
"t3/workspace/Services/WorkspacePaths",
|
||||
) {}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
||||
|
||||
const { runProcessMock } = vi.hoisted(() => ({
|
||||
runProcessMock:
|
||||
vi.fn<
|
||||
(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("./processRunner", () => ({
|
||||
runProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
function processResult(
|
||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
||||
): ProcessRunResult {
|
||||
return {
|
||||
stdout: overrides.stdout,
|
||||
code: overrides.code,
|
||||
stderr: overrides.stderr ?? "",
|
||||
signal: overrides.signal ?? null,
|
||||
timedOut: overrides.timedOut ?? false,
|
||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
||||
beforeEach(() => {
|
||||
runProcessMock.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
||||
const ignoredPaths = Array.from(
|
||||
{ length: 5000 },
|
||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
||||
);
|
||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
||||
let checkIgnoreCalls = 0;
|
||||
|
||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
||||
if (args[0] === "rev-parse") {
|
||||
return processResult({ code: 0, stdout: "true\n" });
|
||||
}
|
||||
|
||||
if (args[0] === "ls-files") {
|
||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
||||
}
|
||||
|
||||
if (args[0] === "check-ignore") {
|
||||
checkIgnoreCalls += 1;
|
||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
||||
return processResult({
|
||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
||||
});
|
||||
|
||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
||||
const result = await searchWorkspaceEntries({
|
||||
cwd: "/virtual/workspace",
|
||||
query: "",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.isAbove(checkIgnoreCalls, 1);
|
||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns files and directories relative to cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/index.ts");
|
||||
writeFile(cwd, "README.md");
|
||||
writeFile(cwd, ".git/HEAD");
|
||||
writeFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
assert.include(paths, "README.md");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
||||
assert.isFalse(result.truncated);
|
||||
});
|
||||
|
||||
it("filters and ranks entries by query", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("supports fuzzy subsequence queries for composer path search", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
});
|
||||
|
||||
it("tracks truncation without sorting every fuzzy match", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-limit-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
|
||||
|
||||
assert.lengthOf(result.entries, 1);
|
||||
assert.isTrue(result.truncated);
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
writeFile(cwd, "ignored.txt", "ignore me");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.notInclude(paths, "ignored.txt");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
||||
});
|
||||
|
||||
it("excludes tracked paths that match ignore rules", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("excludes .convex in non-git workspaces", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
await Promise.all([
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
]);
|
||||
|
||||
assert.equal(rootReadCount, 1);
|
||||
});
|
||||
|
||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
||||
for (let index = 0; index < 80; index += 1) {
|
||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
||||
}
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
assert.isAtMost(peakReads, 32);
|
||||
});
|
||||
});
|
||||
@@ -1,565 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
import {
|
||||
ProjectEntry,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: SearchableWorkspaceEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedPath: string;
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
return {
|
||||
...entry,
|
||||
normalizedPath,
|
||||
normalizedName: basenameOf(normalizedPath),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
// If output was truncated, the final token can be partial.
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<TInput, TOutput>(
|
||||
items: readonly TInput[],
|
||||
concurrency: number,
|
||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
||||
): Promise<TOutput[]> {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
||||
const results = Array.from({ length: items.length }) as TOutput[];
|
||||
let nextIndex = 0;
|
||||
|
||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
||||
while (nextIndex < items.length) {
|
||||
const currentIndex = nextIndex;
|
||||
nextIndex += 1;
|
||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxBufferBytes: 4_096,
|
||||
}).catch(() => null);
|
||||
return Boolean(
|
||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
||||
);
|
||||
}
|
||||
|
||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
const flushChunk = async (): Promise<boolean> => {
|
||||
if (chunk.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
|
||||
if (!checkIgnore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
||||
checkIgnore.stdout,
|
||||
Boolean(checkIgnore.stdoutTruncated),
|
||||
);
|
||||
for (const ignoredPath of matchedIgnoredPaths) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (
|
||||
chunk.length > 0 &&
|
||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
||||
!(await flushChunk())
|
||||
) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
||||
if (!(await isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = await runProcess(
|
||||
"git",
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!listedFiles || listedFiles.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = splitNullSeparatedPaths(
|
||||
listedFiles.stdout,
|
||||
Boolean(listedFiles.stdoutTruncated),
|
||||
)
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(directoryPath): ProjectEntry => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
const fileEntries = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(filePath): ProjectEntry => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
const directoryEntries = await mapWithConcurrency(
|
||||
currentDirectories,
|
||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
||||
async (relativeDir) => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
try {
|
||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
} catch (error) {
|
||||
if (!relativeDir) {
|
||||
throw new Error(
|
||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry = toSearchableWorkspaceEntry({
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
});
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const cached = workspaceIndexCache.get(cwd);
|
||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
const nextPromise = buildWorkspaceIndex(cwd)
|
||||
.then((next) => {
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
});
|
||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
||||
return nextPromise;
|
||||
}
|
||||
|
||||
export function clearWorkspaceIndexCache(cwd: string): void {
|
||||
workspaceIndexCache.delete(cwd);
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
}
|
||||
|
||||
export async function searchWorkspaceEntries(
|
||||
input: ProjectSearchEntriesInput,
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const index = await getWorkspaceIndex(input.cwd);
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
|
||||
for (const entry of index.entries) {
|
||||
const score = scoreEntry(entry, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,17 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
PlatformError,
|
||||
PubSub,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -48,7 +58,7 @@ import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistenc
|
||||
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./provider/Services/ProviderRegistry";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
@@ -62,8 +72,10 @@ const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeU
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
const defaultOpenService: OpenShape = {
|
||||
openBrowser: () => Effect.void,
|
||||
const defaultDesktopLauncherService: DesktopLauncherShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: (_target) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
};
|
||||
|
||||
@@ -74,7 +86,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: [],
|
||||
},
|
||||
@@ -90,20 +102,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
|
||||
private activeSubscriptions = 0;
|
||||
|
||||
private key(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
emitEvent(event: TerminalEvent): void {
|
||||
for (const listener of this.listeners) {
|
||||
listener(event);
|
||||
}
|
||||
Effect.runSync(PubSub.publish(this.eventPubSub, event));
|
||||
}
|
||||
|
||||
subscriptionCount(): number {
|
||||
return this.listeners.size;
|
||||
return this.activeSubscriptions;
|
||||
}
|
||||
|
||||
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
|
||||
@@ -210,13 +221,15 @@ class MockTerminalManager implements TerminalManagerShape {
|
||||
|
||||
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
|
||||
Effect.sync(() => {
|
||||
this.listeners.add(listener);
|
||||
this.activeSubscriptions += 1;
|
||||
const fiber = Effect.runFork(
|
||||
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
|
||||
);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
this.activeSubscriptions -= 1;
|
||||
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
|
||||
};
|
||||
});
|
||||
|
||||
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -474,6 +487,7 @@ function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) {
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
let serverScope: Scope.Closeable | null = null;
|
||||
let disposeServerRuntime: (() => Promise<void>) | null = null;
|
||||
const connections: WebSocket[] = [];
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
@@ -498,7 +512,7 @@ describe("WebSocket Server", () => {
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerRegistry?: ProviderRegistryShape;
|
||||
open?: OpenShape;
|
||||
desktopLauncher?: DesktopLauncherShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
||||
terminalManager?: TerminalManagerShape;
|
||||
@@ -519,7 +533,16 @@ describe("WebSocket Server", () => {
|
||||
ProviderRegistry,
|
||||
options.providerRegistry ?? defaultProviderRegistryService,
|
||||
);
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const desktopLauncherLayer = Layer.succeed(
|
||||
DesktopLauncher,
|
||||
options.desktopLauncher ?? defaultDesktopLauncherService,
|
||||
);
|
||||
const nodeServicesLayer = NodeServices.layer;
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest(options.serverSettings);
|
||||
const serverSettingsRuntimeLayer = serverSettingsLayer.pipe(
|
||||
Layer.provideMerge(nodeServicesLayer),
|
||||
);
|
||||
const analyticsLayer = AnalyticsService.layerTest;
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
@@ -535,6 +558,11 @@ describe("WebSocket Server", () => {
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const providerRuntimeLayer = infrastructureLayer.pipe(
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(serverSettingsRuntimeLayer),
|
||||
Layer.provideMerge(analyticsLayer),
|
||||
);
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
options.gitCore
|
||||
@@ -547,41 +575,51 @@ describe("WebSocket Server", () => {
|
||||
|
||||
const runtimeLayer = Layer.merge(
|
||||
Layer.merge(
|
||||
makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)),
|
||||
infrastructureLayer,
|
||||
makeServerRuntimeServicesLayer().pipe(
|
||||
Layer.provideMerge(providerRuntimeLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(serverSettingsRuntimeLayer),
|
||||
Layer.provideMerge(analyticsLayer),
|
||||
Layer.provideMerge(nodeServicesLayer),
|
||||
),
|
||||
Layer.mergeAll(providerRuntimeLayer, serverSettingsRuntimeLayer, analyticsLayer),
|
||||
),
|
||||
runtimeOverrides,
|
||||
);
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(desktopLauncherLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(analyticsLayer),
|
||||
Layer.provideMerge(nodeServicesLayer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(dependenciesLayer);
|
||||
try {
|
||||
const runtime = await Effect.runPromise(
|
||||
createServer().pipe(Effect.provide(runtimeServices), Scope.provide(scope)),
|
||||
);
|
||||
const httpServer = await runtime.runPromise(createServer().pipe(Scope.provide(scope)));
|
||||
disposeServerRuntime = () => runtime.dispose();
|
||||
serverScope = scope;
|
||||
return runtime;
|
||||
return httpServer;
|
||||
} catch (error) {
|
||||
await runtime.dispose();
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function closeTestServer() {
|
||||
if (!serverScope) return;
|
||||
if (!serverScope && !disposeServerRuntime) return;
|
||||
const scope = serverScope;
|
||||
const disposeRuntime = disposeServerRuntime;
|
||||
serverScope = null;
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
disposeServerRuntime = null;
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
if (disposeRuntime) {
|
||||
await disposeRuntime();
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -1028,7 +1066,9 @@ describe("WebSocket Server", () => {
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
const openCalls: Array<{ cwd: string; editor: string }> = [];
|
||||
const openService: OpenShape = {
|
||||
const desktopLauncherService: DesktopLauncherShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: () => Effect.void,
|
||||
openInEditor: (input) => {
|
||||
openCalls.push({ cwd: input.cwd, editor: input.editor });
|
||||
@@ -1036,7 +1076,10 @@ describe("WebSocket Server", () => {
|
||||
},
|
||||
};
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", open: openService });
|
||||
server = await createTestServer({
|
||||
cwd: "/my/workspace",
|
||||
desktopLauncher: desktopLauncherService,
|
||||
});
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -1254,6 +1297,32 @@ describe("WebSocket Server", () => {
|
||||
expect(response.error?.message).toContain("exceeds current turn count");
|
||||
});
|
||||
|
||||
it("rejects project.create when the workspace root does not exist", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const missingWorkspaceRoot = path.join(makeTempDir("t3code-ws-project-missing-"), "missing");
|
||||
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-ws-project-create-missing",
|
||||
projectId: "project-missing",
|
||||
title: "Missing Project",
|
||||
workspaceRoot: missingWorkspaceRoot,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("Workspace root does not exist:");
|
||||
});
|
||||
|
||||
it("keeps orchestration domain push behavior for provider runtime events", async () => {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
|
||||
@@ -1454,19 +1523,25 @@ describe("WebSocket Server", () => {
|
||||
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
|
||||
});
|
||||
|
||||
it("detaches terminal event listener on stop for injected manager", async () => {
|
||||
it("shuts down cleanly for injected terminal managers", async () => {
|
||||
const terminalManager = new MockTerminalManager();
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(1);
|
||||
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(0);
|
||||
expect(() =>
|
||||
terminalManager.emitEvent({
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "after shutdown\n",
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns validation errors for invalid terminal open params", async () => {
|
||||
@@ -1523,14 +1598,19 @@ describe("WebSocket Server", () => {
|
||||
};
|
||||
process.on("unhandledRejection", onUnhandledRejection);
|
||||
|
||||
const brokenOpenService: OpenShape = {
|
||||
const brokenDesktopLauncherService: DesktopLauncherShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: () => Effect.void,
|
||||
openInEditor: () =>
|
||||
Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)),
|
||||
};
|
||||
|
||||
try {
|
||||
server = await createTestServer({ cwd: "/test", open: brokenOpenService });
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
desktopLauncher: brokenDesktopLauncherService,
|
||||
});
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -1658,6 +1738,50 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("invalidates workspace entry search cache after projects.writeFile", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-invalidate-");
|
||||
fs.mkdirSync(path.join(workspace, "src"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, "src", "existing.ts"), "export {};\n", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const beforeWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(beforeWrite.error).toBeUndefined();
|
||||
expect(beforeWrite.result).toEqual({
|
||||
entries: [],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
const writeResponse = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
|
||||
cwd: workspace,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
expect(writeResponse.error).toBeUndefined();
|
||||
|
||||
const afterWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(afterWrite.error).toBeUndefined();
|
||||
expect(afterWrite.result).toEqual({
|
||||
entries: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "plans/effect-rpc.md", kind: "file" }),
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects projects.writeFile paths outside the workspace root", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-reject-");
|
||||
|
||||
@@ -1676,7 +1800,7 @@ describe("WebSocket Server", () => {
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain(
|
||||
"Workspace file path must stay within the project root.",
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
|
||||
});
|
||||
|
||||
+37
-97
@@ -50,7 +50,6 @@ import { GitManager } from "./git/Services/GitManager.ts";
|
||||
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
@@ -58,7 +57,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { DesktopLauncher } from "./process/Services/DesktopLauncher";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
@@ -75,10 +74,13 @@ import {
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
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 { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -154,48 +156,6 @@ function websocketRawToString(raw: unknown): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function toPosixRelativePath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function resolveWorkspaceWritePath(params: {
|
||||
workspaceRoot: string;
|
||||
relativePath: string;
|
||||
path: Path.Path;
|
||||
}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
|
||||
const normalizedInputPath = params.relativePath.trim();
|
||||
if (params.path.isAbsolute(normalizedInputPath)) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must be relative to the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
|
||||
const relativeToRoot = toPosixRelativePath(
|
||||
params.path.relative(params.workspaceRoot, absolutePath),
|
||||
);
|
||||
if (
|
||||
relativeToRoot.length === 0 ||
|
||||
relativeToRoot === "." ||
|
||||
relativeToRoot.startsWith("../") ||
|
||||
relativeToRoot === ".." ||
|
||||
params.path.isAbsolute(relativeToRoot)
|
||||
) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must stay within the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
absolutePath,
|
||||
relativePath: relativeToRoot,
|
||||
});
|
||||
}
|
||||
|
||||
function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
@@ -218,7 +178,11 @@ export type ServerRuntimeServices =
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| DesktopLauncher
|
||||
| ProjectFaviconResolver
|
||||
| WorkspaceEntries
|
||||
| WorkspaceFileSystem
|
||||
| WorkspacePaths
|
||||
| AnalyticsService;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
@@ -250,7 +214,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
logWebSocketEvents,
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const open = yield* DesktopLauncher;
|
||||
const availableEditors = yield* open.getAvailableEditors.pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })),
|
||||
);
|
||||
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
@@ -263,6 +230,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
@@ -312,35 +282,21 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
|
||||
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
@@ -437,7 +393,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
if (yield* tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -615,7 +571,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const { openInEditor } = yield* Open;
|
||||
|
||||
const subscriptionsScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
|
||||
@@ -719,9 +674,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
@@ -768,46 +723,31 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.projectsSearchEntries: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => searchWorkspaceEntries(body),
|
||||
catch: (cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
return yield* workspaceEntries.search(body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${cause.detail}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsWriteFile: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const target = yield* resolveWorkspaceWritePath({
|
||||
workspaceRoot: body.cwd,
|
||||
relativePath: body.relativePath,
|
||||
path,
|
||||
});
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to prepare workspace path: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
|
||||
return yield* workspaceFileSystem.writeFile(body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to write workspace file: ${String(cause)}`,
|
||||
message: `Failed to write workspace file: ${cause.message}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { relativePath: target.relativePath };
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* openInEditor(body);
|
||||
return yield* open.openInEditor(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitStatus: {
|
||||
|
||||
@@ -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)}
|
||||
>
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
import "../index.css";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
type MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
@@ -57,6 +60,8 @@ interface TestFixture {
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
let wsClient: { send: (message: string) => void } | null = null;
|
||||
let pushSequence = 1;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -117,7 +122,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
},
|
||||
@@ -336,6 +341,79 @@ function addThreadToSnapshot(
|
||||
};
|
||||
}
|
||||
|
||||
function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
|
||||
return {
|
||||
sequence,
|
||||
eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: NOW_ISO,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: PROJECT_ID,
|
||||
title: "New thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
|
||||
if (!wsClient) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
wsClient.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
data: event,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
|
||||
let client: { send: (message: string) => void } | null = null;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
client = wsClient;
|
||||
expect(client).toBeTruthy();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
if (!client) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
|
||||
await waitForWsClient();
|
||||
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
|
||||
sendOrchestrationDomainEvent(
|
||||
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
|
||||
);
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
}
|
||||
|
||||
function createDraftOnlySnapshot(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-draft-target" as MessageId,
|
||||
@@ -500,10 +578,12 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
wsClient = client;
|
||||
pushSequence = 1;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
@@ -875,7 +955,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
bootstrapComplete: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1041,6 +1121,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();
|
||||
|
||||
@@ -1760,6 +1853,87 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -1787,21 +1961,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
// The composer editor should be present for the new draft thread.
|
||||
await waitForComposerEditor();
|
||||
|
||||
// Simulate the snapshot sync arriving from the server after the draft
|
||||
// thread has been promoted to a server thread (thread.create + turn.start
|
||||
// succeeded). The snapshot now includes the new thread, and the sync
|
||||
// should clear the draft without disrupting the route.
|
||||
const { syncServerReadModel } = useStore.getState();
|
||||
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
|
||||
|
||||
// Clear the draft now that the server thread exists (mirrors EventRouter behavior).
|
||||
useComposerDraftStore.getState().clearDraftThread(newThreadId);
|
||||
// Simulate the steady-state promotion path: the server emits
|
||||
// `thread.created`, the client materializes the thread incrementally,
|
||||
// and the draft is cleared by live batch effects.
|
||||
await promoteDraftThreadViaDomainEvent(newThreadId);
|
||||
|
||||
// The route should still be on the new thread — not redirected away.
|
||||
await waitForURL(
|
||||
mounted.router,
|
||||
(path) => path === newThreadPath,
|
||||
"New thread should remain selected after snapshot sync clears the draft.",
|
||||
"New thread should remain selected after server thread promotion clears the draft.",
|
||||
);
|
||||
|
||||
// The empty thread view and composer should still be visible.
|
||||
@@ -2123,9 +2292,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
|
||||
|
||||
const { syncServerReadModel } = useStore.getState();
|
||||
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
|
||||
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
|
||||
await promoteDraftThreadViaDomainEvent(promotedThreadId);
|
||||
|
||||
const freshThreadPath = await triggerChatNewShortcutUntilPath(
|
||||
mounted.router,
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useStore } from "../store";
|
||||
|
||||
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
|
||||
import {
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
|
||||
describe("deriveComposerSendState", () => {
|
||||
it("treats expired terminal pills as non-sendable content", () => {
|
||||
@@ -67,3 +74,290 @@ describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const makeThread = (input?: {
|
||||
id?: ThreadId;
|
||||
latestTurn?: {
|
||||
turnId: TurnId;
|
||||
state: "running" | "completed";
|
||||
requestedAt: string;
|
||||
startedAt: string | null;
|
||||
completedAt: string | null;
|
||||
} | null;
|
||||
}) => ({
|
||||
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
session: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:00.000Z",
|
||||
latestTurn: input?.latestTurn
|
||||
? {
|
||||
...input.latestTurn,
|
||||
assistantMessageId: null,
|
||||
}
|
||||
: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
projects: [],
|
||||
threads: [],
|
||||
bootstrapComplete: true,
|
||||
}));
|
||||
});
|
||||
|
||||
describe("waitForStartedServerThread", () => {
|
||||
it("resolves immediately when the thread is already started", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-started");
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [
|
||||
makeThread({
|
||||
id: threadId,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-started"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:00:01.000Z",
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("waits for the thread to start via subscription updates", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-wait");
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [makeThread({ id: threadId })],
|
||||
}));
|
||||
|
||||
const promise = waitForStartedServerThread(threadId, 500);
|
||||
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [
|
||||
makeThread({
|
||||
id: threadId,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-started"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:00:01.000Z",
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
await expect(promise).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("handles the thread starting between the initial read and subscription setup", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-race");
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [makeThread({ id: threadId })],
|
||||
}));
|
||||
|
||||
const originalSubscribe = useStore.subscribe.bind(useStore);
|
||||
let raced = false;
|
||||
vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
|
||||
if (!raced) {
|
||||
raced = true;
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [
|
||||
makeThread({
|
||||
id: threadId,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-race"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:00:01.000Z",
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}));
|
||||
}
|
||||
return originalSubscribe(listener);
|
||||
});
|
||||
|
||||
await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("returns false after the timeout when the thread never starts", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
const threadId = ThreadId.makeUnsafe("thread-timeout");
|
||||
useStore.setState((state) => ({
|
||||
...state,
|
||||
threads: [makeThread({ id: threadId })],
|
||||
}));
|
||||
const promise = waitForStartedServerThread(threadId, 500);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
|
||||
await expect(promise).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const previousLatestTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed" as const,
|
||||
requestedAt: "2026-03-29T00:00:00.000Z",
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: "2026-03-29T00:00:10.000Z",
|
||||
assistantMessageId: null,
|
||||
};
|
||||
|
||||
const previousSession = {
|
||||
provider: "codex" as const,
|
||||
status: "ready" as const,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
orchestrationStatus: "idle" as const,
|
||||
};
|
||||
|
||||
it("does not clear local dispatch before server state changes", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: previousSession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clears local dispatch when a new turn is already settled", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: {
|
||||
...previousLatestTurn,
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: "2026-03-29T00:01:30.000Z",
|
||||
},
|
||||
session: {
|
||||
...previousSession,
|
||||
updatedAt: "2026-03-29T00:01:30.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears local dispatch when the session changes without an observed running phase", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
updatedAt: "2026-03-29T00:00:11.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
|
||||
import { type ChatMessage, type Thread } from "../types";
|
||||
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
filterTerminalContextsWithText,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
@@ -34,7 +35,6 @@ export function buildLocalDraftThread(
|
||||
createdAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
lastVisitedAt: draftThread.createdAt,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
@@ -75,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;
|
||||
@@ -161,3 +159,116 @@ export function buildExpiredTerminalContextToastCopy(
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
};
|
||||
}
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
);
|
||||
}
|
||||
|
||||
export async function waitForStartedServerThread(
|
||||
threadId: ThreadId,
|
||||
timeoutMs = 1_000,
|
||||
): Promise<boolean> {
|
||||
const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId);
|
||||
const thread = getThread();
|
||||
|
||||
if (threadHasStarted(thread)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
let settled = false;
|
||||
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
|
||||
const finish = (result: boolean) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (timeoutId !== null) {
|
||||
globalThis.clearTimeout(timeoutId);
|
||||
}
|
||||
unsubscribe();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const unsubscribe = useStore.subscribe((state) => {
|
||||
if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) {
|
||||
return;
|
||||
}
|
||||
finish(true);
|
||||
});
|
||||
|
||||
if (threadHasStarted(getThread())) {
|
||||
finish(true);
|
||||
return;
|
||||
}
|
||||
|
||||
timeoutId = globalThis.setTimeout(() => {
|
||||
finish(false);
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
latestTurnStartedAt: string | null;
|
||||
latestTurnCompletedAt: string | null;
|
||||
sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null;
|
||||
sessionUpdatedAt: string | null;
|
||||
}
|
||||
|
||||
export function createLocalDispatchSnapshot(
|
||||
activeThread: Thread | undefined,
|
||||
options?: { preparingWorktree?: boolean },
|
||||
): LocalDispatchSnapshot {
|
||||
const latestTurn = activeThread?.latestTurn ?? null;
|
||||
const session = activeThread?.session ?? null;
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
latestTurnStartedAt: latestTurn?.startedAt ?? null,
|
||||
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
|
||||
sessionOrchestrationStatus: session?.orchestrationStatus ?? null,
|
||||
sessionUpdatedAt: session?.updatedAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
localDispatch: LocalDispatchSnapshot | null;
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
session: Thread["session"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
threadError: string | null | undefined;
|
||||
}): boolean {
|
||||
if (!input.localDispatch) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
input.phase === "running" ||
|
||||
input.hasPendingApproval ||
|
||||
input.hasPendingUserInput ||
|
||||
Boolean(input.threadError)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
|
||||
return (
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
|
||||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
replaceTextRange,
|
||||
} from "../composer-logic";
|
||||
import {
|
||||
deriveCompletionDividerBeforeEntryId,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
@@ -64,6 +66,8 @@ import {
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../pendingUserInput";
|
||||
import { useStore } from "../store";
|
||||
import { useProjectById, useThreadById } from "../storeSelectors";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
buildPlanImplementationThreadTitle,
|
||||
buildPlanImplementationPrompt,
|
||||
@@ -76,8 +80,12 @@ import {
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_TERMINALS_PER_GROUP,
|
||||
type ChatMessage,
|
||||
type SessionPhase,
|
||||
type Thread,
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
|
||||
import { basenameOfPath } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
@@ -168,14 +176,18 @@ import {
|
||||
buildTemporaryWorktreeBranchName,
|
||||
cloneComposerImageForRetry,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
type LocalDispatchSnapshot,
|
||||
PullRequestDialogState,
|
||||
readFileAsDataUrl,
|
||||
revokeBlobPreviewUrl,
|
||||
revokeUserMessagePreviewUrls,
|
||||
SendPhase,
|
||||
threadHasStarted,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
|
||||
@@ -190,6 +202,81 @@ const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
|
||||
|
||||
const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500;
|
||||
const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024;
|
||||
const threadPlanCatalogCache = new LRUCache<{
|
||||
proposedPlans: Thread["proposedPlans"];
|
||||
entry: ThreadPlanCatalogEntry;
|
||||
}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES);
|
||||
|
||||
function estimateThreadPlanCatalogEntrySize(thread: Thread): number {
|
||||
return Math.max(
|
||||
64,
|
||||
thread.id.length +
|
||||
thread.proposedPlans.reduce(
|
||||
(total, plan) =>
|
||||
total +
|
||||
plan.id.length +
|
||||
plan.planMarkdown.length +
|
||||
plan.updatedAt.length +
|
||||
(plan.turnId?.length ?? 0),
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry {
|
||||
const cached = threadPlanCatalogCache.get(thread.id);
|
||||
if (cached && cached.proposedPlans === thread.proposedPlans) {
|
||||
return cached.entry;
|
||||
}
|
||||
|
||||
const entry: ThreadPlanCatalogEntry = {
|
||||
id: thread.id,
|
||||
proposedPlans: thread.proposedPlans,
|
||||
};
|
||||
threadPlanCatalogCache.set(
|
||||
thread.id,
|
||||
{
|
||||
proposedPlans: thread.proposedPlans,
|
||||
entry,
|
||||
},
|
||||
estimateThreadPlanCatalogEntrySize(thread),
|
||||
);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
|
||||
const selector = useMemo(() => {
|
||||
let previousThreads: Array<Thread | undefined> | null = null;
|
||||
let previousEntries: ThreadPlanCatalogEntry[] = [];
|
||||
|
||||
return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => {
|
||||
const nextThreads = threadIds.map((threadId) =>
|
||||
state.threads.find((thread) => thread.id === threadId),
|
||||
);
|
||||
const cachedThreads = previousThreads;
|
||||
if (
|
||||
cachedThreads &&
|
||||
nextThreads.length === cachedThreads.length &&
|
||||
nextThreads.every((thread, index) => thread === cachedThreads[index])
|
||||
) {
|
||||
return previousEntries;
|
||||
}
|
||||
|
||||
previousThreads = nextThreads;
|
||||
previousEntries = nextThreads.flatMap((thread) =>
|
||||
thread ? [toThreadPlanCatalogEntry(thread)] : [],
|
||||
);
|
||||
return previousEntries;
|
||||
};
|
||||
}, [threadIds]);
|
||||
|
||||
return useStore(selector);
|
||||
}
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
provider: ProviderKind;
|
||||
model: string | null;
|
||||
@@ -245,13 +332,81 @@ interface PendingPullRequestSetupRequest {
|
||||
scriptId: string;
|
||||
}
|
||||
|
||||
function useLocalDispatchState(input: {
|
||||
activeThread: Thread | undefined;
|
||||
activeLatestTurn: Thread["latestTurn"] | null;
|
||||
phase: SessionPhase;
|
||||
activePendingApproval: ApprovalRequestId | null;
|
||||
activePendingUserInput: ApprovalRequestId | null;
|
||||
threadError: string | null | undefined;
|
||||
}) {
|
||||
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
|
||||
|
||||
const beginLocalDispatch = useCallback(
|
||||
(options?: { preparingWorktree?: boolean }) => {
|
||||
const preparingWorktree = Boolean(options?.preparingWorktree);
|
||||
setLocalDispatch((current) => {
|
||||
if (current) {
|
||||
return current.preparingWorktree === preparingWorktree
|
||||
? current
|
||||
: { ...current, preparingWorktree };
|
||||
}
|
||||
return createLocalDispatchSnapshot(input.activeThread, options);
|
||||
});
|
||||
},
|
||||
[input.activeThread],
|
||||
);
|
||||
|
||||
const resetLocalDispatch = useCallback(() => {
|
||||
setLocalDispatch(null);
|
||||
}, []);
|
||||
|
||||
const serverAcknowledgedLocalDispatch = useMemo(
|
||||
() =>
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: input.phase,
|
||||
latestTurn: input.activeLatestTurn,
|
||||
session: input.activeThread?.session ?? null,
|
||||
hasPendingApproval: input.activePendingApproval !== null,
|
||||
hasPendingUserInput: input.activePendingUserInput !== null,
|
||||
threadError: input.threadError,
|
||||
}),
|
||||
[
|
||||
input.activeLatestTurn,
|
||||
input.activePendingApproval,
|
||||
input.activePendingUserInput,
|
||||
input.activeThread?.session,
|
||||
input.phase,
|
||||
input.threadError,
|
||||
localDispatch,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverAcknowledgedLocalDispatch) {
|
||||
return;
|
||||
}
|
||||
resetLocalDispatch();
|
||||
}, [resetLocalDispatch, serverAcknowledgedLocalDispatch]);
|
||||
|
||||
return {
|
||||
beginLocalDispatch,
|
||||
resetLocalDispatch,
|
||||
localDispatchStartedAt: localDispatch?.startedAt ?? null,
|
||||
isPreparingWorktree: localDispatch?.preparingWorktree ?? false,
|
||||
isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch,
|
||||
};
|
||||
}
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const markThreadVisited = useStore((store) => store.markThreadVisited);
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const serverThread = useThreadById(threadId);
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const activeThreadLastVisitedAt = useUiStateStore(
|
||||
(store) => store.threadLastVisitedAtById[threadId],
|
||||
);
|
||||
const settings = useSettings();
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
@@ -330,8 +485,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
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[]>([]);
|
||||
@@ -466,8 +619,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
|
||||
);
|
||||
|
||||
const serverThread = threads.find((t) => t.id === threadId);
|
||||
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
|
||||
const fallbackDraftProject = useProjectById(draftThread?.projectId);
|
||||
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
|
||||
const localDraftThread = useMemo(
|
||||
() =>
|
||||
@@ -495,12 +647,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const diffOpen = rawSearch.diff === "1";
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const threadPlanCatalog = useThreadPlanCatalog(
|
||||
useMemo(() => {
|
||||
const threadIds: ThreadId[] = [];
|
||||
if (activeThread?.id) {
|
||||
threadIds.push(activeThread.id);
|
||||
}
|
||||
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
|
||||
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
|
||||
threadIds.push(sourceThreadId);
|
||||
}
|
||||
return threadIds;
|
||||
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
|
||||
);
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
|
||||
[activeThread?.activities],
|
||||
);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
|
||||
const activeProject = useProjectById(activeThread?.projectId);
|
||||
|
||||
const openPullRequestDialog = useCallback(
|
||||
(reference?: string) => {
|
||||
@@ -595,33 +760,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (!serverThread?.id) return;
|
||||
if (!latestTurnSettled) return;
|
||||
if (!activeLatestTurn?.completedAt) return;
|
||||
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
|
||||
if (Number.isNaN(turnCompletedAt)) return;
|
||||
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
|
||||
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
|
||||
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
|
||||
|
||||
markThreadVisited(activeThread.id);
|
||||
markThreadVisited(serverThread.id);
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThread?.lastVisitedAt,
|
||||
activeLatestTurn?.completedAt,
|
||||
activeThreadLastVisitedAt,
|
||||
latestTurnSettled,
|
||||
markThreadVisited,
|
||||
serverThread?.id,
|
||||
]);
|
||||
|
||||
const sessionProvider = activeThread?.session?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
|
||||
const hasThreadStarted = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.latestTurn !== null ||
|
||||
activeThread.messages.length > 0 ||
|
||||
activeThread.session !== null),
|
||||
);
|
||||
const hasThreadStarted = threadHasStarted(activeThread);
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
@@ -664,15 +824,6 @@ 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 nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
sendStartedAt,
|
||||
);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
@@ -735,12 +886,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const sidebarProposedPlan = useMemo(
|
||||
() =>
|
||||
findSidebarProposedPlan({
|
||||
threads,
|
||||
threads: threadPlanCatalog,
|
||||
latestTurn: activeLatestTurn,
|
||||
latestTurnSettled,
|
||||
threadId: activeThread?.id ?? null,
|
||||
}),
|
||||
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
|
||||
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
|
||||
);
|
||||
const activePlan = useMemo(
|
||||
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
@@ -752,6 +903,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
latestTurnSettled &&
|
||||
hasActionableProposedPlan(activeProposedPlan);
|
||||
const activePendingApproval = pendingApprovals[0] ?? null;
|
||||
const {
|
||||
beginLocalDispatch,
|
||||
resetLocalDispatch,
|
||||
localDispatchStartedAt,
|
||||
isPreparingWorktree,
|
||||
isSendBusy,
|
||||
} = useLocalDispatchState({
|
||||
activeThread,
|
||||
activeLatestTurn,
|
||||
phase,
|
||||
activePendingApproval: activePendingApproval?.requestId ?? null,
|
||||
activePendingUserInput: activePendingUserInput?.requestId ?? null,
|
||||
threadError: activeThread?.error,
|
||||
});
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
localDispatchStartedAt,
|
||||
);
|
||||
const isComposerApprovalState = activePendingApproval !== null;
|
||||
const hasComposerHeader =
|
||||
isComposerApprovalState ||
|
||||
@@ -980,35 +1152,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
const completionDividerBeforeEntryId = useMemo(() => {
|
||||
if (!latestTurnSettled) return null;
|
||||
if (!activeLatestTurn?.startedAt) return null;
|
||||
if (!activeLatestTurn.completedAt) return null;
|
||||
if (!completionSummary) return null;
|
||||
|
||||
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
|
||||
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
|
||||
if (Number.isNaN(turnStartedAt)) return null;
|
||||
if (Number.isNaN(turnCompletedAt)) return null;
|
||||
|
||||
let inRangeMatch: string | null = null;
|
||||
let fallbackMatch: string | null = null;
|
||||
for (const timelineEntry of timelineEntries) {
|
||||
if (timelineEntry.kind !== "message") continue;
|
||||
if (timelineEntry.message.role !== "assistant") continue;
|
||||
const messageAt = Date.parse(timelineEntry.message.createdAt);
|
||||
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue;
|
||||
fallbackMatch = timelineEntry.id;
|
||||
if (messageAt <= turnCompletedAt) {
|
||||
inRangeMatch = timelineEntry.id;
|
||||
}
|
||||
}
|
||||
return inRangeMatch ?? fallbackMatch;
|
||||
}, [
|
||||
activeLatestTurn?.completedAt,
|
||||
activeLatestTurn?.startedAt,
|
||||
completionSummary,
|
||||
latestTurnSettled,
|
||||
timelineEntries,
|
||||
]);
|
||||
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
|
||||
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
project: { cwd: activeProject.cwd },
|
||||
@@ -1230,7 +1376,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setThreadError = useCallback(
|
||||
(targetThreadId: ThreadId | null, error: string | null) => {
|
||||
if (!targetThreadId) return;
|
||||
if (threads.some((thread) => thread.id === targetThreadId)) {
|
||||
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
|
||||
setStoreThreadError(targetThreadId, error);
|
||||
return;
|
||||
}
|
||||
@@ -1244,7 +1390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
});
|
||||
},
|
||||
[setStoreThreadError, threads],
|
||||
[setStoreThreadError],
|
||||
);
|
||||
|
||||
const focusComposer = useCallback(() => {
|
||||
@@ -1411,7 +1557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
|
||||
...(options?.env ? { extraEnv: options.env } : {}),
|
||||
});
|
||||
const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
|
||||
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
|
||||
? {
|
||||
threadId: activeThreadId,
|
||||
terminalId: targetTerminalId,
|
||||
@@ -2020,15 +2166,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return [];
|
||||
});
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
resetLocalDispatch();
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
|
||||
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
setExpandedImage(null);
|
||||
}, [threadId]);
|
||||
}, [resetLocalDispatch, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -2161,37 +2306,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
}, [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,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
|
||||
@@ -2529,7 +2643,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
@@ -2603,7 +2717,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await (async () => {
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
if (baseBranchForWorktree) {
|
||||
beginSendPhase("preparing-worktree");
|
||||
beginLocalDispatch({ preparingWorktree: true });
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
@@ -2715,7 +2829,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}
|
||||
|
||||
beginSendPhase("sending-turn");
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
const turnAttachments = await turnAttachmentsPromise;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
@@ -2772,7 +2886,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
if (!turnStartSucceeded) {
|
||||
resetSendPhase();
|
||||
resetLocalDispatch();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2971,7 +3085,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
setThreadError(threadIdForSend, null);
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -3040,19 +3154,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
err instanceof Error ? err.message : "Failed to send plan follow-up.",
|
||||
);
|
||||
sendInFlightRef.current = false;
|
||||
resetSendPhase();
|
||||
resetLocalDispatch();
|
||||
}
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
activeProposedPlan,
|
||||
beginSendPhase,
|
||||
beginLocalDispatch,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
resetLocalDispatch,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
@@ -3094,10 +3208,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
const finish = () => {
|
||||
sendInFlightRef.current = false;
|
||||
resetSendPhase();
|
||||
resetLocalDispatch();
|
||||
};
|
||||
|
||||
await api.orchestration
|
||||
@@ -3132,9 +3246,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
createdAt,
|
||||
});
|
||||
})
|
||||
.then(() => api.orchestration.getSnapshot())
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
.then(() => {
|
||||
return waitForStartedServerThread(nextThreadId);
|
||||
})
|
||||
.then(() => {
|
||||
// Signal that the plan sidebar should open on the new thread.
|
||||
planSidebarOpenOnNextThreadRef.current = true;
|
||||
return navigate({
|
||||
@@ -3150,12 +3265,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: nextThreadId,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await api.orchestration
|
||||
.getSnapshot()
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start implementation thread",
|
||||
@@ -3168,18 +3277,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
beginLocalDispatch,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
resetLocalDispatch,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
},
|
||||
@@ -323,7 +323,7 @@ describe("Keybindings update toast", () => {
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
bootstrapComplete: false,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createThreadJumpHintVisibilityController,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
getProjectSortTimestamp,
|
||||
hasUnseenCompletion,
|
||||
isContextMenuPointerDown,
|
||||
orderItemsByPreferredIds,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
@@ -15,8 +17,9 @@ import {
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
@@ -27,7 +30,7 @@ import {
|
||||
function makeLatestTurn(overrides?: {
|
||||
completedAt?: string | null;
|
||||
startedAt?: string | null;
|
||||
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
|
||||
}): OrchestrationLatestTurn {
|
||||
return {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
@@ -52,6 +55,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 = {
|
||||
@@ -99,6 +164,50 @@ describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
items: [
|
||||
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
|
||||
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
|
||||
{ id: ProjectId.makeUnsafe("project-3"), name: "Three" },
|
||||
],
|
||||
preferredIds: [
|
||||
ProjectId.makeUnsafe("project-3"),
|
||||
ProjectId.makeUnsafe("project-missing"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
],
|
||||
getId: (project) => project.id,
|
||||
});
|
||||
|
||||
expect(ordered.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-3"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not duplicate items when preferred ids repeat", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
items: [
|
||||
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
|
||||
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
|
||||
],
|
||||
preferredIds: [
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
],
|
||||
getId: (project) => project.id,
|
||||
});
|
||||
|
||||
expect(ordered.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAdjacentThreadId", () => {
|
||||
it("resolves adjacent thread ids in ordered sidebar traversal", () => {
|
||||
const threads = [
|
||||
@@ -171,6 +280,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 +559,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 +582,7 @@ describe("getVisibleThreadsForProject", () => {
|
||||
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
|
||||
threads.map((thread) => thread.id),
|
||||
);
|
||||
expect(result.hiddenThreads).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -463,7 +597,6 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
model: "gpt-5.4",
|
||||
...defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
|
||||
@@ -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;
|
||||
@@ -15,7 +17,10 @@ type SidebarProject = {
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
|
||||
latestUserMessageAt?: string | null;
|
||||
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
@@ -43,8 +48,95 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
|
||||
|
||||
type ThreadStatusInput = Pick<
|
||||
Thread,
|
||||
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
|
||||
>;
|
||||
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
};
|
||||
|
||||
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;
|
||||
@@ -69,15 +161,46 @@ export function resolveSidebarNewThreadEnvMode(input: {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function orderItemsByPreferredIds<TItem, TId>(input: {
|
||||
items: readonly TItem[];
|
||||
preferredIds: readonly TId[];
|
||||
getId: (item: TItem) => TId;
|
||||
}): TItem[] {
|
||||
const { getId, items, preferredIds } = input;
|
||||
if (preferredIds.length === 0) {
|
||||
return [...items];
|
||||
}
|
||||
|
||||
const itemsById = new Map(items.map((item) => [getId(item), item] as const));
|
||||
const preferredIdSet = new Set(preferredIds);
|
||||
const emittedPreferredIds = new Set<TId>();
|
||||
const ordered = preferredIds.flatMap((id) => {
|
||||
if (emittedPreferredIds.has(id)) {
|
||||
return [];
|
||||
}
|
||||
const item = itemsById.get(id);
|
||||
if (!item) {
|
||||
return [];
|
||||
}
|
||||
emittedPreferredIds.add(id);
|
||||
return [item];
|
||||
});
|
||||
const remaining = items.filter((item) => !preferredIdSet.has(getId(item)));
|
||||
return [...ordered, ...remaining];
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -237,14 +360,15 @@ export function resolveProjectStatusIndicator(
|
||||
return highestPriorityStatus;
|
||||
}
|
||||
|
||||
export function getVisibleThreadsForProject(input: {
|
||||
threads: readonly Thread[];
|
||||
activeThreadId: Thread["id"] | undefined;
|
||||
export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
|
||||
threads: readonly T[];
|
||||
activeThreadId: T["id"] | undefined;
|
||||
isThreadListExpanded: boolean;
|
||||
previewLimit: number;
|
||||
}): {
|
||||
hasHiddenThreads: boolean;
|
||||
visibleThreads: Thread[];
|
||||
visibleThreads: T[];
|
||||
hiddenThreads: T[];
|
||||
} {
|
||||
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
|
||||
const hasHiddenThreads = threads.length > previewLimit;
|
||||
@@ -252,6 +376,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!hasHiddenThreads || isThreadListExpanded) {
|
||||
return {
|
||||
hasHiddenThreads,
|
||||
hiddenThreads: [],
|
||||
visibleThreads: [...threads],
|
||||
};
|
||||
}
|
||||
@@ -260,6 +385,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -268,6 +394,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThread) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -276,6 +403,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
|
||||
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
|
||||
};
|
||||
}
|
||||
@@ -287,9 +415,13 @@ function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
}
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
|
||||
if (thread.latestUserMessageAt) {
|
||||
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
for (const message of thread.messages) {
|
||||
for (const message of thread.messages ?? []) {
|
||||
if (message.role !== "user") continue;
|
||||
const messageTimestamp = toSortableTimestamp(message.createdAt);
|
||||
if (messageTimestamp === null) continue;
|
||||
@@ -317,7 +449,7 @@ function getThreadSortTimestamp(
|
||||
}
|
||||
|
||||
export function sortThreadsForSidebar<
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
|
||||
return threads.toSorted((left, right) => {
|
||||
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
|
||||
@@ -330,7 +462,7 @@ export function sortThreadsForSidebar<
|
||||
}
|
||||
|
||||
export function getFallbackThreadIdAfterDelete<
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(input: {
|
||||
threads: readonly T[];
|
||||
deletedThreadId: T["id"];
|
||||
@@ -374,7 +506,10 @@ export function getProjectSortTimestamp(
|
||||
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
|
||||
export function sortProjectsForSidebar<
|
||||
TProject extends SidebarProject,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
|
||||
+310
-138
@@ -21,6 +21,7 @@ import {
|
||||
type MouseEvent,
|
||||
type PointerEvent,
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import {
|
||||
DndContext,
|
||||
type DragCancelEvent,
|
||||
@@ -55,6 +56,7 @@ import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
import { useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
@@ -69,6 +71,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";
|
||||
@@ -113,13 +116,16 @@ import {
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
} from "./Sidebar.logic";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import type { Project, Thread } from "../types";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
@@ -136,6 +142,80 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = {
|
||||
duration: 180,
|
||||
easing: "ease-out",
|
||||
} as const;
|
||||
|
||||
type SidebarThreadSnapshot = Pick<
|
||||
Thread,
|
||||
| "activities"
|
||||
| "archivedAt"
|
||||
| "branch"
|
||||
| "createdAt"
|
||||
| "id"
|
||||
| "interactionMode"
|
||||
| "latestTurn"
|
||||
| "projectId"
|
||||
| "proposedPlans"
|
||||
| "session"
|
||||
| "title"
|
||||
| "updatedAt"
|
||||
| "worktreePath"
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
latestUserMessageAt: string | null;
|
||||
};
|
||||
|
||||
type SidebarProjectSnapshot = Project & {
|
||||
expanded: boolean;
|
||||
};
|
||||
|
||||
const sidebarThreadSnapshotCache = new WeakMap<
|
||||
Thread,
|
||||
{ lastVisitedAt?: string | undefined; snapshot: SidebarThreadSnapshot }
|
||||
>();
|
||||
|
||||
function getLatestUserMessageAt(thread: Thread): string | null {
|
||||
let latestUserMessageAt: string | null = null;
|
||||
|
||||
for (const message of thread.messages) {
|
||||
if (message.role !== "user") {
|
||||
continue;
|
||||
}
|
||||
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
|
||||
latestUserMessageAt = message.createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
return latestUserMessageAt;
|
||||
}
|
||||
|
||||
function toSidebarThreadSnapshot(
|
||||
thread: Thread,
|
||||
lastVisitedAt: string | undefined,
|
||||
): SidebarThreadSnapshot {
|
||||
const cached = sidebarThreadSnapshotCache.get(thread);
|
||||
if (cached && cached.lastVisitedAt === lastVisitedAt) {
|
||||
return cached.snapshot;
|
||||
}
|
||||
|
||||
const snapshot: SidebarThreadSnapshot = {
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
interactionMode: thread.interactionMode,
|
||||
session: thread.session,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
activities: thread.activities,
|
||||
proposedPlans: thread.proposedPlans,
|
||||
latestUserMessageAt: getLatestUserMessageAt(thread),
|
||||
};
|
||||
sidebarThreadSnapshotCache.set(thread, { lastVisitedAt, snapshot });
|
||||
return snapshot;
|
||||
}
|
||||
interface TerminalStatusIndicator {
|
||||
label: "Terminal process running";
|
||||
colorClass: string;
|
||||
@@ -151,6 +231,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 {
|
||||
@@ -321,10 +439,17 @@ function SortableProjectItem({
|
||||
|
||||
export default function Sidebar() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const reorderProjects = useStore((store) => store.reorderProjects);
|
||||
const serverThreads = useStore((store) => store.threads);
|
||||
const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore(
|
||||
useShallow((store) => ({
|
||||
projectExpandedById: store.projectExpandedById,
|
||||
projectOrder: store.projectOrder,
|
||||
threadLastVisitedAtById: store.threadLastVisitedAtById,
|
||||
})),
|
||||
);
|
||||
const markThreadUnread = useUiStateStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useUiStateStore((store) => store.toggleProject);
|
||||
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
@@ -356,14 +481,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);
|
||||
@@ -378,6 +503,28 @@ export default function Sidebar() {
|
||||
const platform = navigator.platform;
|
||||
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
|
||||
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
|
||||
const orderedProjects = useMemo(() => {
|
||||
return orderItemsByPreferredIds({
|
||||
items: projects,
|
||||
preferredIds: projectOrder,
|
||||
getId: (project) => project.id,
|
||||
});
|
||||
}, [projectOrder, projects]);
|
||||
const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(
|
||||
() =>
|
||||
orderedProjects.map((project) => ({
|
||||
...project,
|
||||
expanded: projectExpandedById[project.id] ?? true,
|
||||
})),
|
||||
[orderedProjects, projectExpandedById],
|
||||
);
|
||||
const threads = useMemo(
|
||||
() =>
|
||||
serverThreads.map((thread) =>
|
||||
toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]),
|
||||
),
|
||||
[serverThreads, threadLastVisitedAtById],
|
||||
);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[projects],
|
||||
@@ -712,7 +859,7 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadId);
|
||||
markThreadUnread(threadId, thread.latestTurn?.completedAt);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
@@ -774,7 +921,8 @@ export default function Sidebar() {
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const id of ids) {
|
||||
markThreadUnread(id);
|
||||
const thread = threads.find((candidate) => candidate.id === id);
|
||||
markThreadUnread(id, thread?.latestTurn?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
return;
|
||||
@@ -805,6 +953,7 @@ export default function Sidebar() {
|
||||
markThreadUnread,
|
||||
removeFromSelection,
|
||||
selectedThreadIds,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -947,12 +1096,12 @@ export default function Sidebar() {
|
||||
dragInProgressRef.current = false;
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
const activeProject = projects.find((project) => project.id === active.id);
|
||||
const overProject = projects.find((project) => project.id === over.id);
|
||||
const activeProject = sidebarProjects.find((project) => project.id === active.id);
|
||||
const overProject = sidebarProjects.find((project) => project.id === over.id);
|
||||
if (!activeProject || !overProject) return;
|
||||
reorderProjects(activeProject.id, overProject.id);
|
||||
},
|
||||
[appSettings.sidebarProjectSortOrder, projects, reorderProjects],
|
||||
[appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects],
|
||||
);
|
||||
|
||||
const handleProjectDragStart = useCallback(
|
||||
@@ -1012,8 +1161,9 @@ export default function Sidebar() {
|
||||
[threads],
|
||||
);
|
||||
const sortedProjects = useMemo(
|
||||
() => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder),
|
||||
[appSettings.sidebarProjectSortOrder, projects, visibleThreads],
|
||||
() =>
|
||||
sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder),
|
||||
[appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads],
|
||||
);
|
||||
const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
|
||||
const renderedProjects = useMemo(
|
||||
@@ -1023,14 +1173,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);
|
||||
@@ -1039,25 +1193,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,
|
||||
};
|
||||
@@ -1070,23 +1234,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],
|
||||
@@ -1101,10 +1264,7 @@ export default function Sidebar() {
|
||||
}
|
||||
return mapping;
|
||||
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
|
||||
const orderedSidebarThreadIds = useMemo(
|
||||
() => getVisibleSidebarThreadIds(renderedProjects),
|
||||
[renderedProjects],
|
||||
);
|
||||
const orderedSidebarThreadIds = visibleSidebarThreadIds;
|
||||
|
||||
useEffect(() => {
|
||||
const getShortcutContext = () => ({
|
||||
@@ -1113,7 +1273,7 @@ export default function Sidebar() {
|
||||
});
|
||||
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1161,7 +1321,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowKeyUp = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1170,7 +1330,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowBlur = () => {
|
||||
setShowThreadJumpHints(false);
|
||||
updateThreadJumpHintsVisibility(false);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
@@ -1190,6 +1350,7 @@ export default function Sidebar() {
|
||||
routeTerminalOpen,
|
||||
routeThreadId,
|
||||
threadJumpThreadIds,
|
||||
updateThreadJumpHintsVisibility,
|
||||
]);
|
||||
|
||||
function renderProjectItem(
|
||||
@@ -1198,11 +1359,14 @@ export default function Sidebar() {
|
||||
) {
|
||||
const {
|
||||
hasHiddenThreads,
|
||||
hiddenThreadStatus,
|
||||
orderedProjectThreadIds,
|
||||
project,
|
||||
projectStatus,
|
||||
projectThreads,
|
||||
threadStatuses,
|
||||
renderedThreads,
|
||||
showEmptyThreadState,
|
||||
shouldShowThreadPanel,
|
||||
isThreadListExpanded,
|
||||
} = renderedProject;
|
||||
@@ -1213,37 +1377,45 @@ export default function Sidebar() {
|
||||
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`}
|
||||
})} relative isolate`}
|
||||
onClick={(event) => {
|
||||
handleThreadClick(event, thread.id, orderedProjectThreadIds);
|
||||
}}
|
||||
@@ -1254,7 +1426,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,
|
||||
@@ -1291,18 +1462,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) => {
|
||||
@@ -1352,10 +1512,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) => {
|
||||
@@ -1367,80 +1535,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>
|
||||
@@ -1535,6 +1707,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 && (
|
||||
@@ -1548,7 +1730,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>
|
||||
)}
|
||||
@@ -1859,7 +2044,6 @@ export default function Sidebar() {
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{shouldShowProjectPathEntry && (
|
||||
<div className="mb-2 px-1">
|
||||
{isElectron && (
|
||||
@@ -1910,18 +2094,6 @@ export default function Sidebar() {
|
||||
{addProjectError}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-1.5 px-0.5">
|
||||
<button
|
||||
type="button"
|
||||
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
|
||||
onClick={() => {
|
||||
setAddingProject(false);
|
||||
setAddProjectError(null);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -9,6 +9,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
clearPromotedDraftThread,
|
||||
clearPromotedDraftThreads,
|
||||
type ComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
} from "./composerDraftStore";
|
||||
@@ -549,6 +551,57 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears a promoted draft by thread id", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "promote me");
|
||||
|
||||
clearPromotedDraftThread(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not clear composer drafts for existing server threads during promotion cleanup", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setPrompt(threadId, "keep me");
|
||||
|
||||
clearPromotedDraftThread(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
|
||||
});
|
||||
|
||||
it("clears promoted drafts from an iterable of server thread ids", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "promote me");
|
||||
store.setProjectDraftThreadId(otherProjectId, otherThreadId);
|
||||
store.setPrompt(otherThreadId, "keep me");
|
||||
|
||||
clearPromotedDraftThreads([threadId]);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
expect(
|
||||
useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,
|
||||
).toBe(otherThreadId);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[otherThreadId]?.prompt).toBe(
|
||||
"keep me",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps existing server-thread composer drafts during iterable promotion cleanup", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setPrompt(threadId, "keep me");
|
||||
|
||||
clearPromotedDraftThreads([threadId]);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
|
||||
});
|
||||
|
||||
it("updates branch context on an existing draft thread", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId, {
|
||||
|
||||
@@ -2195,18 +2195,21 @@ export function useEffectiveComposerModelState(input: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear draft threads that have been promoted to server threads.
|
||||
* Clear a draft thread once the server has materialized the same thread id.
|
||||
*
|
||||
* Call this after a snapshot sync so the route guard in `_chat.$threadId`
|
||||
* sees the server thread before the draft is removed — avoids a redirect
|
||||
* to `/` caused by a gap where neither draft nor server thread exists.
|
||||
* Use the single-thread helper for live `thread.created` events and the
|
||||
* iterable helper for bootstrap/recovery paths that discover multiple server
|
||||
* threads at once.
|
||||
*/
|
||||
export function clearPromotedDraftThreads(serverThreadIds: ReadonlySet<ThreadId>): void {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const draftThreadIds = Object.keys(store.draftThreadsByThreadId) as ThreadId[];
|
||||
for (const draftId of draftThreadIds) {
|
||||
if (serverThreadIds.has(draftId)) {
|
||||
store.clearDraftThread(draftId);
|
||||
}
|
||||
export function clearPromotedDraftThread(threadId: ThreadId): void {
|
||||
if (!useComposerDraftStore.getState().getDraftThread(threadId)) {
|
||||
return;
|
||||
}
|
||||
useComposerDraftStore.getState().clearDraftThread(threadId);
|
||||
}
|
||||
|
||||
export function clearPromotedDraftThreads(serverThreadIds: Iterable<ThreadId>): void {
|
||||
for (const threadId of serverThreadIds) {
|
||||
clearPromotedDraftThread(threadId);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,37 @@
|
||||
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import {
|
||||
type DraftThreadEnvMode,
|
||||
type DraftThreadState,
|
||||
useComposerDraftStore,
|
||||
} from "../composerDraftStore";
|
||||
import { newThreadId } from "../lib/utils";
|
||||
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
|
||||
import { useStore } from "../store";
|
||||
import { useThreadById } from "../storeSelectors";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
|
||||
const projectOrder = useUiStateStore((store) => store.projectOrder);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const activeThread = useThreadById(routeThreadId);
|
||||
const activeDraftThread = useComposerDraftStore((store) =>
|
||||
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
|
||||
);
|
||||
|
||||
const activeThread = routeThreadId
|
||||
? threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const orderedProjects = useMemo(() => {
|
||||
return orderItemsByPreferredIds({
|
||||
items: projectIds,
|
||||
preferredIds: projectOrder,
|
||||
getId: (projectId) => projectId,
|
||||
});
|
||||
}, [projectIds, projectOrder]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
@@ -111,8 +119,8 @@ export function useHandleNewThread() {
|
||||
return {
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectId: orderedProjects[0] ?? null,
|
||||
handleNewThread,
|
||||
projects,
|
||||
routeThreadId,
|
||||
};
|
||||
}
|
||||
@@ -16,8 +16,6 @@ import { toastManager } from "../components/ui/toast";
|
||||
import { useSettings } from "./useSettings";
|
||||
|
||||
export function useThreadActions() {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const appSettings = useSettings();
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||
@@ -37,7 +35,7 @@ export function useThreadActions() {
|
||||
async (threadId: ThreadId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
|
||||
throw new Error("Cannot archive a running thread.");
|
||||
@@ -53,7 +51,7 @@ export function useThreadActions() {
|
||||
await handleNewThread(thread.projectId);
|
||||
}
|
||||
},
|
||||
[handleNewThread, routeThreadId, threads],
|
||||
[handleNewThread, routeThreadId],
|
||||
);
|
||||
|
||||
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
|
||||
@@ -70,6 +68,7 @@ export function useThreadActions() {
|
||||
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const { projects, threads } = useStore.getState();
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
@@ -171,10 +170,8 @@ export function useThreadActions() {
|
||||
clearTerminalState,
|
||||
appSettings.sidebarThreadSortOrder,
|
||||
navigate,
|
||||
projects,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -182,7 +179,7 @@ export function useThreadActions() {
|
||||
async (threadId: ThreadId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
@@ -199,7 +196,7 @@ export function useThreadActions() {
|
||||
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[appSettings.confirmThreadDelete, deleteThread, threads],
|
||||
[appSettings.confirmThreadDelete, deleteThread],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects";
|
||||
|
||||
function makeEvent<T extends OrchestrationEvent["type"]>(
|
||||
type: T,
|
||||
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
|
||||
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
|
||||
): Extract<OrchestrationEvent, { type: T }> {
|
||||
const sequence = overrides.sequence ?? 1;
|
||||
return {
|
||||
sequence,
|
||||
eventId: EventId.makeUnsafe(`event-${sequence}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId:
|
||||
"threadId" in payload
|
||||
? payload.threadId
|
||||
: "projectId" in payload
|
||||
? payload.projectId
|
||||
: ProjectId.makeUnsafe("project-1"),
|
||||
occurredAt: "2026-02-27T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type,
|
||||
payload,
|
||||
...overrides,
|
||||
} as Extract<OrchestrationEvent, { type: T }>;
|
||||
}
|
||||
|
||||
describe("deriveOrchestrationBatchEffects", () => {
|
||||
it("targets draft promotion and terminal cleanup from thread lifecycle events", () => {
|
||||
const createdThreadId = ThreadId.makeUnsafe("thread-created");
|
||||
const deletedThreadId = ThreadId.makeUnsafe("thread-deleted");
|
||||
|
||||
const effects = deriveOrchestrationBatchEffects([
|
||||
makeEvent("thread.created", {
|
||||
threadId: createdThreadId,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Created thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
}),
|
||||
makeEvent("thread.deleted", {
|
||||
threadId: deletedThreadId,
|
||||
deletedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]);
|
||||
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
|
||||
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]);
|
||||
expect(effects.needsProviderInvalidation).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps only the final lifecycle outcome for a thread within one batch", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
|
||||
const effects = deriveOrchestrationBatchEffects([
|
||||
makeEvent("thread.deleted", {
|
||||
threadId,
|
||||
deletedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
makeEvent("thread.created", {
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Recreated thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-27T00:00:02.000Z",
|
||||
updatedAt: "2026-02-27T00:00:02.000Z",
|
||||
}),
|
||||
makeEvent("thread.turn-diff-completed", {
|
||||
threadId,
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
|
||||
completedAt: "2026-02-27T00:00:03.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(effects.clearPromotedDraftThreadIds).toEqual([threadId]);
|
||||
expect(effects.clearDeletedThreadIds).toEqual([]);
|
||||
expect(effects.removeTerminalStateThreadIds).toEqual([]);
|
||||
expect(effects.needsProviderInvalidation).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export interface OrchestrationBatchEffects {
|
||||
clearPromotedDraftThreadIds: ThreadId[];
|
||||
clearDeletedThreadIds: ThreadId[];
|
||||
removeTerminalStateThreadIds: ThreadId[];
|
||||
needsProviderInvalidation: boolean;
|
||||
}
|
||||
|
||||
export function deriveOrchestrationBatchEffects(
|
||||
events: readonly OrchestrationEvent[],
|
||||
): OrchestrationBatchEffects {
|
||||
const threadLifecycleEffects = new Map<
|
||||
ThreadId,
|
||||
{
|
||||
clearPromotedDraft: boolean;
|
||||
clearDeletedThread: boolean;
|
||||
removeTerminalState: boolean;
|
||||
}
|
||||
>();
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
for (const event of events) {
|
||||
switch (event.type) {
|
||||
case "thread.turn-diff-completed":
|
||||
case "thread.reverted": {
|
||||
needsProviderInvalidation = true;
|
||||
break;
|
||||
}
|
||||
|
||||
case "thread.created": {
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: true,
|
||||
clearDeletedThread: false,
|
||||
removeTerminalState: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: false,
|
||||
clearDeletedThread: true,
|
||||
removeTerminalState: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const clearPromotedDraftThreadIds: ThreadId[] = [];
|
||||
const clearDeletedThreadIds: ThreadId[] = [];
|
||||
const removeTerminalStateThreadIds: ThreadId[] = [];
|
||||
for (const [threadId, effect] of threadLifecycleEffects) {
|
||||
if (effect.clearPromotedDraft) {
|
||||
clearPromotedDraftThreadIds.push(threadId);
|
||||
}
|
||||
if (effect.clearDeletedThread) {
|
||||
clearDeletedThreadIds.push(threadId);
|
||||
}
|
||||
if (effect.removeTerminalState) {
|
||||
removeTerminalStateThreadIds.push(threadId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
clearPromotedDraftThreadIds,
|
||||
clearDeletedThreadIds,
|
||||
removeTerminalStateThreadIds,
|
||||
needsProviderInvalidation,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
|
||||
|
||||
describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
it("defers live events until bootstrap completes and then requests replay", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true);
|
||||
expect(coordinator.classifyDomainEvent(4)).toBe("defer");
|
||||
|
||||
expect(coordinator.completeSnapshotRecovery(2)).toBe(true);
|
||||
expect(coordinator.getState()).toMatchObject({
|
||||
latestSequence: 2,
|
||||
highestObservedSequence: 4,
|
||||
bootstrapped: true,
|
||||
pendingReplay: false,
|
||||
inFlight: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies sequence gaps as recovery-only replay work", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
|
||||
expect(coordinator.classifyDomainEvent(5)).toBe("recover");
|
||||
expect(coordinator.beginReplayRecovery("sequence-gap")).toBe(true);
|
||||
expect(coordinator.getState().inFlight).toEqual({
|
||||
kind: "replay",
|
||||
reason: "sequence-gap",
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks live event batches without entering recovery", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
|
||||
expect(coordinator.classifyDomainEvent(4)).toBe("apply");
|
||||
expect(coordinator.markEventBatchApplied([{ sequence: 4 }])).toEqual([{ sequence: 4 }]);
|
||||
expect(coordinator.getState()).toMatchObject({
|
||||
latestSequence: 4,
|
||||
highestObservedSequence: 4,
|
||||
bootstrapped: true,
|
||||
inFlight: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("requests another replay when deferred events arrive during replay recovery", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
coordinator.classifyDomainEvent(5);
|
||||
coordinator.beginReplayRecovery("sequence-gap");
|
||||
coordinator.classifyDomainEvent(7);
|
||||
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
|
||||
|
||||
expect(coordinator.completeReplayRecovery()).toBe(true);
|
||||
});
|
||||
|
||||
it("does not immediately replay again when replay returns no new events", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
coordinator.classifyDomainEvent(5);
|
||||
coordinator.beginReplayRecovery("sequence-gap");
|
||||
|
||||
expect(coordinator.completeReplayRecovery()).toBe(false);
|
||||
expect(coordinator.getState()).toMatchObject({
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
pendingReplay: false,
|
||||
inFlight: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
coordinator.beginReplayRecovery("sequence-gap");
|
||||
coordinator.failReplayRecovery();
|
||||
|
||||
expect(coordinator.getState()).toMatchObject({
|
||||
bootstrapped: false,
|
||||
inFlight: null,
|
||||
});
|
||||
expect(coordinator.beginSnapshotRecovery("replay-failed")).toBe(true);
|
||||
expect(coordinator.getState().inFlight).toEqual({
|
||||
kind: "snapshot",
|
||||
reason: "replay-failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
|
||||
|
||||
export interface OrchestrationRecoveryPhase {
|
||||
kind: "snapshot" | "replay";
|
||||
reason: OrchestrationRecoveryReason;
|
||||
}
|
||||
|
||||
export interface OrchestrationRecoveryState {
|
||||
latestSequence: number;
|
||||
highestObservedSequence: number;
|
||||
bootstrapped: boolean;
|
||||
pendingReplay: boolean;
|
||||
inFlight: OrchestrationRecoveryPhase | null;
|
||||
}
|
||||
|
||||
type SequencedEvent = Readonly<{ sequence: number }>;
|
||||
|
||||
export function createOrchestrationRecoveryCoordinator() {
|
||||
let state: OrchestrationRecoveryState = {
|
||||
latestSequence: 0,
|
||||
highestObservedSequence: 0,
|
||||
bootstrapped: false,
|
||||
pendingReplay: false,
|
||||
inFlight: null,
|
||||
};
|
||||
let replayStartSequence: number | null = null;
|
||||
|
||||
const snapshotState = (): OrchestrationRecoveryState => ({
|
||||
...state,
|
||||
...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),
|
||||
});
|
||||
|
||||
const observeSequence = (sequence: number) => {
|
||||
state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);
|
||||
};
|
||||
|
||||
const shouldReplayAfterRecovery = (): boolean => {
|
||||
const shouldReplay =
|
||||
state.pendingReplay || state.highestObservedSequence > state.latestSequence;
|
||||
state.pendingReplay = false;
|
||||
return shouldReplay;
|
||||
};
|
||||
|
||||
return {
|
||||
getState(): OrchestrationRecoveryState {
|
||||
return snapshotState();
|
||||
},
|
||||
|
||||
classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {
|
||||
observeSequence(sequence);
|
||||
if (sequence <= state.latestSequence) {
|
||||
return "ignore";
|
||||
}
|
||||
if (!state.bootstrapped || state.inFlight) {
|
||||
state.pendingReplay = true;
|
||||
return "defer";
|
||||
}
|
||||
if (sequence !== state.latestSequence + 1) {
|
||||
state.pendingReplay = true;
|
||||
return "recover";
|
||||
}
|
||||
return "apply";
|
||||
},
|
||||
|
||||
markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {
|
||||
const nextEvents = events
|
||||
.filter((event) => event.sequence > state.latestSequence)
|
||||
.toSorted((left, right) => left.sequence - right.sequence);
|
||||
if (nextEvents.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
|
||||
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
|
||||
return nextEvents;
|
||||
},
|
||||
|
||||
beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {
|
||||
if (state.inFlight?.kind === "snapshot") {
|
||||
state.pendingReplay = true;
|
||||
return false;
|
||||
}
|
||||
if (state.inFlight?.kind === "replay") {
|
||||
state.pendingReplay = true;
|
||||
return false;
|
||||
}
|
||||
state.inFlight = { kind: "snapshot", reason };
|
||||
return true;
|
||||
},
|
||||
|
||||
completeSnapshotRecovery(snapshotSequence: number): boolean {
|
||||
state.latestSequence = Math.max(state.latestSequence, snapshotSequence);
|
||||
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
|
||||
state.bootstrapped = true;
|
||||
state.inFlight = null;
|
||||
return shouldReplayAfterRecovery();
|
||||
},
|
||||
|
||||
failSnapshotRecovery(): void {
|
||||
state.inFlight = null;
|
||||
},
|
||||
|
||||
beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {
|
||||
if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {
|
||||
state.pendingReplay = true;
|
||||
return false;
|
||||
}
|
||||
if (state.inFlight?.kind === "replay") {
|
||||
state.pendingReplay = true;
|
||||
return false;
|
||||
}
|
||||
state.pendingReplay = false;
|
||||
replayStartSequence = state.latestSequence;
|
||||
state.inFlight = { kind: "replay", reason };
|
||||
return true;
|
||||
},
|
||||
|
||||
completeReplayRecovery(): boolean {
|
||||
const replayMadeProgress =
|
||||
replayStartSequence !== null && state.latestSequence > replayStartSequence;
|
||||
replayStartSequence = null;
|
||||
state.inFlight = null;
|
||||
if (!replayMadeProgress) {
|
||||
state.pendingReplay = false;
|
||||
return false;
|
||||
}
|
||||
return shouldReplayAfterRecovery();
|
||||
},
|
||||
|
||||
failReplayRecovery(): void {
|
||||
replayStartSequence = null;
|
||||
state.bootstrapped = false;
|
||||
state.inFlight = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+2
-10
@@ -1,11 +1,8 @@
|
||||
import { createElement } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRouter } from "@tanstack/react-router";
|
||||
import { createRouter, RouterHistory } from "@tanstack/react-router";
|
||||
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
|
||||
|
||||
export function getRouter(history: RouterHistory) {
|
||||
const queryClient = new QueryClient();
|
||||
@@ -16,12 +13,7 @@ export function getRouter(history: RouterHistory) {
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) =>
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
createElement(StoreProvider, null, children),
|
||||
),
|
||||
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+146
-47
@@ -1,4 +1,4 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
@@ -17,8 +17,13 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
clearPromotedDraftThread,
|
||||
clearPromotedDraftThreads,
|
||||
useComposerDraftStore,
|
||||
} from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
@@ -26,6 +31,8 @@ import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
|
||||
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
|
||||
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
|
||||
|
||||
export const Route = createRootRouteWithContext<{
|
||||
queryClient: QueryClient;
|
||||
@@ -135,8 +142,13 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
|
||||
const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
|
||||
const syncProjects = useUiStateStore((store) => store.syncProjects);
|
||||
const syncThreads = useUiStateStore((store) => store.syncThreads);
|
||||
const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
|
||||
const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
@@ -152,56 +164,40 @@ function EventRouter() {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
let disposed = false;
|
||||
let latestSequence = 0;
|
||||
let syncing = false;
|
||||
let pending = false;
|
||||
const recovery = createOrchestrationRecoveryCoordinator();
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
const flushSnapshotSync = async (): Promise<void> => {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (disposed) return;
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
syncServerReadModel(snapshot);
|
||||
clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id)));
|
||||
const reconcileSnapshotDerivedState = () => {
|
||||
const threads = useStore.getState().threads;
|
||||
const projects = useStore.getState().projects;
|
||||
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
|
||||
syncThreads(
|
||||
threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
|
||||
})),
|
||||
);
|
||||
clearPromotedDraftThreads(threads.map((thread) => thread.id));
|
||||
const draftThreadIds = Object.keys(
|
||||
useComposerDraftStore.getState().draftThreadsByThreadId,
|
||||
) as ThreadId[];
|
||||
const activeThreadIds = collectActiveTerminalThreadIds({
|
||||
snapshotThreads: snapshot.threads,
|
||||
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
|
||||
draftThreadIds,
|
||||
});
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
if (pending) {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
}
|
||||
};
|
||||
|
||||
const syncSnapshot = async () => {
|
||||
if (syncing) {
|
||||
pending = true;
|
||||
return;
|
||||
}
|
||||
syncing = true;
|
||||
pending = false;
|
||||
try {
|
||||
await flushSnapshotSync();
|
||||
} catch {
|
||||
// Keep prior state and wait for next domain event to trigger a resync.
|
||||
}
|
||||
syncing = false;
|
||||
};
|
||||
|
||||
const domainEventFlushThrottler = new Throttler(
|
||||
const queryInvalidationThrottler = new Throttler(
|
||||
() => {
|
||||
if (needsProviderInvalidation) {
|
||||
needsProviderInvalidation = false;
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
// Invalidate workspace entry queries so the @-mention file picker
|
||||
// reflects files created, deleted, or restored during this turn.
|
||||
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
|
||||
if (!needsProviderInvalidation) {
|
||||
return;
|
||||
}
|
||||
void syncSnapshot();
|
||||
needsProviderInvalidation = false;
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
// Invalidate workspace entry queries so the @-mention file picker
|
||||
// reflects files created, deleted, or restored during this turn.
|
||||
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
|
||||
},
|
||||
{
|
||||
wait: 100,
|
||||
@@ -210,15 +206,113 @@ function EventRouter() {
|
||||
},
|
||||
);
|
||||
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
if (event.sequence <= latestSequence) {
|
||||
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
|
||||
const nextEvents = recovery.markEventBatchApplied(events);
|
||||
if (nextEvents.length === 0) {
|
||||
return;
|
||||
}
|
||||
latestSequence = event.sequence;
|
||||
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
|
||||
|
||||
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
|
||||
const needsProjectUiSync = nextEvents.some(
|
||||
(event) =>
|
||||
event.type === "project.created" ||
|
||||
event.type === "project.meta-updated" ||
|
||||
event.type === "project.deleted",
|
||||
);
|
||||
|
||||
if (batchEffects.needsProviderInvalidation) {
|
||||
needsProviderInvalidation = true;
|
||||
void queryInvalidationThrottler.maybeExecute();
|
||||
}
|
||||
|
||||
applyOrchestrationEvents(nextEvents);
|
||||
if (needsProjectUiSync) {
|
||||
const projects = useStore.getState().projects;
|
||||
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
|
||||
}
|
||||
const needsThreadUiSync = nextEvents.some(
|
||||
(event) => event.type === "thread.created" || event.type === "thread.deleted",
|
||||
);
|
||||
if (needsThreadUiSync) {
|
||||
const threads = useStore.getState().threads;
|
||||
syncThreads(
|
||||
threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
|
||||
})),
|
||||
);
|
||||
}
|
||||
const draftStore = useComposerDraftStore.getState();
|
||||
for (const threadId of batchEffects.clearPromotedDraftThreadIds) {
|
||||
clearPromotedDraftThread(threadId);
|
||||
}
|
||||
for (const threadId of batchEffects.clearDeletedThreadIds) {
|
||||
draftStore.clearDraftThread(threadId);
|
||||
clearThreadUi(threadId);
|
||||
}
|
||||
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
|
||||
removeTerminalState(threadId);
|
||||
}
|
||||
};
|
||||
|
||||
const recoverFromSequenceGap = async (): Promise<void> => {
|
||||
if (!recovery.beginReplayRecovery("sequence-gap")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
|
||||
if (!disposed) {
|
||||
applyEventBatch(events);
|
||||
}
|
||||
} catch {
|
||||
recovery.failReplayRecovery();
|
||||
void fallbackToSnapshotRecovery();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!disposed && recovery.completeReplayRecovery()) {
|
||||
void recoverFromSequenceGap();
|
||||
}
|
||||
};
|
||||
|
||||
const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise<void> => {
|
||||
if (!recovery.beginSnapshotRecovery(reason)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (!disposed) {
|
||||
syncServerReadModel(snapshot);
|
||||
reconcileSnapshotDerivedState();
|
||||
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
|
||||
void recoverFromSequenceGap();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Keep prior state and wait for welcome or a later replay attempt.
|
||||
recovery.failSnapshotRecovery();
|
||||
}
|
||||
};
|
||||
|
||||
const bootstrapFromSnapshot = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("bootstrap");
|
||||
};
|
||||
|
||||
const fallbackToSnapshotRecovery = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("replay-failed");
|
||||
};
|
||||
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
applyEventBatch([event]);
|
||||
return;
|
||||
}
|
||||
if (action === "recover") {
|
||||
void recoverFromSequenceGap();
|
||||
}
|
||||
domainEventFlushThrottler.maybeExecute();
|
||||
});
|
||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
@@ -237,7 +331,7 @@ function EventRouter() {
|
||||
// Migrate old localStorage settings to server on first connect
|
||||
migrateLocalSettingsToServer();
|
||||
void (async () => {
|
||||
await syncSnapshot();
|
||||
await bootstrapFromSnapshot();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
@@ -319,7 +413,7 @@ function EventRouter() {
|
||||
return () => {
|
||||
disposed = true;
|
||||
needsProviderInvalidation = false;
|
||||
domainEventFlushThrottler.cancel();
|
||||
queryInvalidationThrottler.cancel();
|
||||
unsubDomainEvent();
|
||||
unsubTerminalEvent();
|
||||
unsubWelcome();
|
||||
@@ -327,11 +421,16 @@ function EventRouter() {
|
||||
unsubProvidersUpdated();
|
||||
};
|
||||
}, [
|
||||
applyOrchestrationEvents,
|
||||
navigate,
|
||||
queryClient,
|
||||
removeTerminalState,
|
||||
removeOrphanedTerminalStates,
|
||||
clearThreadUi,
|
||||
setProjectExpanded,
|
||||
syncProjects,
|
||||
syncServerReadModel,
|
||||
syncThreads,
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -161,7 +161,7 @@ const DiffPanelInlineSidebar = (props: {
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const threadsHydrated = useStore((store) => store.threadsHydrated);
|
||||
const bootstrapComplete = useStore((store) => store.bootstrapComplete);
|
||||
const navigate = useNavigate();
|
||||
const threadId = Route.useParams({
|
||||
select: (params) => ThreadId.makeUnsafe(params.threadId),
|
||||
@@ -202,7 +202,7 @@ function ChatThreadRouteView() {
|
||||
}, [diffOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadsHydrated) {
|
||||
if (!bootstrapComplete) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -210,9 +210,9 @@ function ChatThreadRouteView() {
|
||||
void navigate({ to: "/", replace: true });
|
||||
return;
|
||||
}
|
||||
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
|
||||
}, [bootstrapComplete, navigate, routeThreadExists, threadId]);
|
||||
|
||||
if (!threadsHydrated || !routeThreadExists) {
|
||||
if (!bootstrapComplete || !routeThreadExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size);
|
||||
const { activeDraftThread, activeThread, handleNewThread, projects, routeThreadId } =
|
||||
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } =
|
||||
useHandleNewThread();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
@@ -38,7 +38,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId;
|
||||
if (!projectId) return;
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
@@ -59,14 +59,17 @@ function ChatRouteGlobalShortcuts() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (command !== "chat.new") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
|
||||
});
|
||||
if (command === "chat.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||
envMode:
|
||||
activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
@@ -79,7 +82,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
clearSelection,
|
||||
handleNewThread,
|
||||
keybindings,
|
||||
projects,
|
||||
defaultProjectId,
|
||||
selectedThreadIdsSize,
|
||||
terminalOpen,
|
||||
appSettings.defaultThreadEnvMode,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
deriveCompletionDividerBeforeEntryId,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
PROVIDER_OPTIONS,
|
||||
@@ -964,6 +965,37 @@ describe("deriveTimelineEntries", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
|
||||
const entries = deriveTimelineEntries(
|
||||
[
|
||||
{
|
||||
id: MessageId.makeUnsafe("assistant-earlier"),
|
||||
role: "assistant",
|
||||
text: "progress update",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: MessageId.makeUnsafe("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "final answer",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(
|
||||
deriveCompletionDividerBeforeEntryId(entries, {
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-final"),
|
||||
startedAt: "2026-02-23T00:00:00.000Z",
|
||||
completedAt: "2026-02-23T00:00:02.000Z",
|
||||
}),
|
||||
).toBe("assistant-final");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries context window handling", () => {
|
||||
|
||||
@@ -852,6 +852,53 @@ export function deriveTimelineEntries(
|
||||
);
|
||||
}
|
||||
|
||||
export function deriveCompletionDividerBeforeEntryId(
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>,
|
||||
latestTurn: Pick<
|
||||
OrchestrationLatestTurn,
|
||||
"assistantMessageId" | "startedAt" | "completedAt"
|
||||
> | null,
|
||||
): string | null {
|
||||
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (latestTurn.assistantMessageId) {
|
||||
const exactMatch = timelineEntries.find(
|
||||
(timelineEntry) =>
|
||||
timelineEntry.kind === "message" &&
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
timelineEntry.message.id === latestTurn.assistantMessageId,
|
||||
);
|
||||
if (exactMatch) {
|
||||
return exactMatch.id;
|
||||
}
|
||||
}
|
||||
|
||||
const turnStartedAt = Date.parse(latestTurn.startedAt);
|
||||
const turnCompletedAt = Date.parse(latestTurn.completedAt);
|
||||
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let inRangeMatch: string | null = null;
|
||||
let fallbackMatch: string | null = null;
|
||||
for (const timelineEntry of timelineEntries) {
|
||||
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
|
||||
continue;
|
||||
}
|
||||
const messageAt = Date.parse(timelineEntry.message.createdAt);
|
||||
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
|
||||
continue;
|
||||
}
|
||||
fallbackMatch = timelineEntry.id;
|
||||
if (messageAt <= turnCompletedAt) {
|
||||
inRangeMatch = timelineEntry.id;
|
||||
}
|
||||
}
|
||||
return inRangeMatch ?? fallbackMatch;
|
||||
}
|
||||
|
||||
export function inferCheckpointTurnCountByTurnId(
|
||||
summaries: TurnDiffSummary[],
|
||||
): Record<TurnId, number> {
|
||||
|
||||
+488
-94
@@ -1,13 +1,22 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
|
||||
import {
|
||||
applyOrchestrationEvent,
|
||||
applyOrchestrationEvents,
|
||||
syncServerReadModel,
|
||||
type AppState,
|
||||
} from "./store";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -48,15 +57,41 @@ function makeState(thread: Thread): AppState {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
threadsHydrated: true,
|
||||
bootstrapComplete: true,
|
||||
};
|
||||
}
|
||||
|
||||
function makeEvent<T extends OrchestrationEvent["type"]>(
|
||||
type: T,
|
||||
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
|
||||
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
|
||||
): Extract<OrchestrationEvent, { type: T }> {
|
||||
const sequence = overrides.sequence ?? 1;
|
||||
return {
|
||||
sequence,
|
||||
eventId: EventId.makeUnsafe(`event-${sequence}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId:
|
||||
"threadId" in payload
|
||||
? payload.threadId
|
||||
: "projectId" in payload
|
||||
? payload.projectId
|
||||
: ProjectId.makeUnsafe("project-1"),
|
||||
occurredAt: "2026-02-27T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type,
|
||||
payload,
|
||||
...overrides,
|
||||
} as Extract<OrchestrationEvent, { type: T }>;
|
||||
}
|
||||
|
||||
function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
|
||||
return {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
@@ -126,97 +161,18 @@ function makeReadModelProject(
|
||||
};
|
||||
}
|
||||
|
||||
describe("store pure functions", () => {
|
||||
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
|
||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-25T12:28:00.000Z",
|
||||
startedAt: "2026-02-25T12:28:30.000Z",
|
||||
completedAt: latestTurnCompletedAt,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
const updatedThread = next.threads[0];
|
||||
expect(updatedThread).toBeDefined();
|
||||
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
|
||||
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
|
||||
Date.parse(latestTurnCompletedAt),
|
||||
);
|
||||
});
|
||||
|
||||
it("markThreadUnread does not change a thread without a completed turn", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: null,
|
||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
|
||||
expect(next).toEqual(initialState);
|
||||
});
|
||||
|
||||
it("reorderProjects moves a project to a target index", () => {
|
||||
const project1 = ProjectId.makeUnsafe("project-1");
|
||||
const project2 = ProjectId.makeUnsafe("project-2");
|
||||
const project3 = ProjectId.makeUnsafe("project-3");
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: project1,
|
||||
name: "Project 1",
|
||||
cwd: "/tmp/project-1",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: project2,
|
||||
name: "Project 2",
|
||||
cwd: "/tmp/project-2",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: project3,
|
||||
name: "Project 3",
|
||||
cwd: "/tmp/project-3",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
threadsHydrated: true,
|
||||
describe("store read model sync", () => {
|
||||
it("marks bootstrap complete after snapshot sync", () => {
|
||||
const initialState: AppState = {
|
||||
...makeState(makeThread()),
|
||||
bootstrapComplete: false,
|
||||
};
|
||||
|
||||
const next = reorderProjects(state, project1, project3);
|
||||
const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({})));
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
|
||||
expect(next.bootstrapComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
it("preserves claude model slugs without an active session", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
@@ -287,7 +243,7 @@ describe("store read model sync", () => {
|
||||
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
|
||||
});
|
||||
|
||||
it("preserves the current project order when syncing incoming read model updates", () => {
|
||||
it("replaces projects using snapshot order during recovery", () => {
|
||||
const project1 = ProjectId.makeUnsafe("project-1");
|
||||
const project2 = ProjectId.makeUnsafe("project-2");
|
||||
const project3 = ProjectId.makeUnsafe("project-3");
|
||||
@@ -301,7 +257,6 @@ describe("store read model sync", () => {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -312,12 +267,11 @@ describe("store read model sync", () => {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
threadsHydrated: true,
|
||||
bootstrapComplete: true,
|
||||
};
|
||||
const readModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 2,
|
||||
@@ -344,6 +298,446 @@ describe("store read model sync", () => {
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("incremental orchestration updates", () => {
|
||||
it("does not mark bootstrap complete for incremental events", () => {
|
||||
const state: AppState = {
|
||||
...makeState(makeThread()),
|
||||
bootstrapComplete: false,
|
||||
};
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.meta-updated", {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
title: "Updated title",
|
||||
updatedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.bootstrapComplete).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves state identity for no-op project and thread deletes", () => {
|
||||
const thread = makeThread();
|
||||
const state = makeState(thread);
|
||||
|
||||
const nextAfterProjectDelete = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("project.deleted", {
|
||||
projectId: ProjectId.makeUnsafe("project-missing"),
|
||||
deletedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
const nextAfterThreadDelete = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.deleted", {
|
||||
threadId: ThreadId.makeUnsafe("thread-missing"),
|
||||
deletedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(nextAfterProjectDelete).toBe(state);
|
||||
expect(nextAfterThreadDelete).toBe(state);
|
||||
});
|
||||
|
||||
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
|
||||
const originalProjectId = ProjectId.makeUnsafe("project-1");
|
||||
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: originalProjectId,
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
bootstrapComplete: true,
|
||||
};
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("project.created", {
|
||||
projectId: recreatedProjectId,
|
||||
title: "Project Recreated",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-02-27T00:00:01.000Z",
|
||||
updatedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe(recreatedProjectId);
|
||||
expect(next.projects[0]?.cwd).toBe("/tmp/project");
|
||||
expect(next.projects[0]?.name).toBe("Project Recreated");
|
||||
});
|
||||
|
||||
it("updates only the affected thread for message events", () => {
|
||||
const thread1 = makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.makeUnsafe("message-1"),
|
||||
role: "assistant",
|
||||
text: "hello",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
completedAt: "2026-02-27T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
|
||||
const state: AppState = {
|
||||
...makeState(thread1),
|
||||
threads: [thread1, thread2],
|
||||
};
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.message-sent", {
|
||||
threadId: thread1.id,
|
||||
messageId: MessageId.makeUnsafe("message-1"),
|
||||
role: "assistant",
|
||||
text: " world",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
streaming: true,
|
||||
createdAt: "2026-02-27T00:00:01.000Z",
|
||||
updatedAt: "2026-02-27T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
|
||||
expect(next.threads[0]?.latestTurn?.state).toBe("running");
|
||||
expect(next.threads[1]).toBe(thread2);
|
||||
});
|
||||
|
||||
it("applies replay batches in sequence and updates session state", () => {
|
||||
const thread = makeThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "running",
|
||||
requestedAt: "2026-02-27T00:00:00.000Z",
|
||||
startedAt: "2026-02-27T00:00:00.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
});
|
||||
const state = makeState(thread);
|
||||
|
||||
const next = applyOrchestrationEvents(state, [
|
||||
makeEvent(
|
||||
"thread.session-set",
|
||||
{
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:02.000Z",
|
||||
},
|
||||
},
|
||||
{ sequence: 2 },
|
||||
),
|
||||
makeEvent(
|
||||
"thread.message-sent",
|
||||
{
|
||||
threadId: thread.id,
|
||||
messageId: MessageId.makeUnsafe("assistant-1"),
|
||||
role: "assistant",
|
||||
text: "done",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-27T00:00:03.000Z",
|
||||
updatedAt: "2026-02-27T00:00:03.000Z",
|
||||
},
|
||||
{ sequence: 3 },
|
||||
),
|
||||
]);
|
||||
|
||||
expect(next.threads[0]?.session?.status).toBe("running");
|
||||
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
|
||||
expect(next.threads[0]?.messages).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not regress latestTurn when an older turn diff completes late", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
state: "running",
|
||||
requestedAt: "2026-02-27T00:00:02.000Z",
|
||||
startedAt: "2026-02-27T00:00:03.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.turn-diff-completed", {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
|
||||
completedAt: "2026-02-27T00:00:04.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
|
||||
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
|
||||
});
|
||||
|
||||
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
|
||||
const turnId = TurnId.makeUnsafe("turn-1");
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-27T00:00:00.000Z",
|
||||
startedAt: "2026-02-27T00:00:00.000Z",
|
||||
completedAt: "2026-02-27T00:00:02.000Z",
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
|
||||
},
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId,
|
||||
completedAt: "2026-02-27T00:00:02.000Z",
|
||||
status: "ready",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
|
||||
files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.message-sent", {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: MessageId.makeUnsafe("assistant-real"),
|
||||
role: "assistant",
|
||||
text: "final answer",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-02-27T00:00:03.000Z",
|
||||
updatedAt: "2026-02-27T00:00:03.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
|
||||
MessageId.makeUnsafe("assistant-real"),
|
||||
);
|
||||
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
|
||||
MessageId.makeUnsafe("assistant-real"),
|
||||
);
|
||||
});
|
||||
|
||||
it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.makeUnsafe("user-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
completedAt: "2026-02-27T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: MessageId.makeUnsafe("assistant-1"),
|
||||
role: "assistant",
|
||||
text: "first reply",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-02-27T00:00:01.000Z",
|
||||
completedAt: "2026-02-27T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: MessageId.makeUnsafe("user-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
createdAt: "2026-02-27T00:00:02.000Z",
|
||||
completedAt: "2026-02-27T00:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "plan 1",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "plan-2",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
planMarkdown: "plan 2",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-27T00:00:02.000Z",
|
||||
updatedAt: "2026-02-27T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: EventId.makeUnsafe("activity-1"),
|
||||
tone: "info",
|
||||
kind: "step",
|
||||
summary: "one",
|
||||
payload: {},
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: EventId.makeUnsafe("activity-2"),
|
||||
tone: "info",
|
||||
kind: "step",
|
||||
summary: "two",
|
||||
payload: {},
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
createdAt: "2026-02-27T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
completedAt: "2026-02-27T00:00:01.000Z",
|
||||
status: "ready",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
|
||||
files: [],
|
||||
},
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
completedAt: "2026-02-27T00:00:03.000Z",
|
||||
status: "ready",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
|
||||
files: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
state,
|
||||
makeEvent("thread.reverted", {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
|
||||
"user-1",
|
||||
"assistant-1",
|
||||
]);
|
||||
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
|
||||
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
|
||||
EventId.makeUnsafe("activity-1"),
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
TurnId.makeUnsafe("turn-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears pending source proposed plans after revert before a new session-set event", () => {
|
||||
const thread = makeThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-27T00:00:02.000Z",
|
||||
startedAt: "2026-02-27T00:00:02.000Z",
|
||||
completedAt: "2026-02-27T00:00:03.000Z",
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-2"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-source"),
|
||||
planId: "plan-2" as never,
|
||||
},
|
||||
},
|
||||
pendingSourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-source"),
|
||||
planId: "plan-2" as never,
|
||||
},
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
completedAt: "2026-02-27T00:00:01.000Z",
|
||||
status: "ready",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
|
||||
files: [],
|
||||
},
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
completedAt: "2026-02-27T00:00:03.000Z",
|
||||
status: "ready",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
|
||||
files: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
const reverted = applyOrchestrationEvent(
|
||||
makeState(thread),
|
||||
makeEvent("thread.reverted", {
|
||||
threadId: thread.id,
|
||||
turnCount: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
|
||||
|
||||
const next = applyOrchestrationEvent(
|
||||
reverted,
|
||||
makeEvent("thread.session-set", {
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-3"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:04.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.latestTurn).toMatchObject({
|
||||
turnId: TurnId.makeUnsafe("turn-3"),
|
||||
state: "running",
|
||||
});
|
||||
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+788
-308
File diff suppressed because it is too large.
Load diff
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user