Compare commits

..
Author SHA1 Message Date
Cursor Agent 755bf3aa0d Fix Windows process tree traversal, remove dead code, deduplicate normalizeRunningPorts
- win32.ts: Replace direct-child-only query with full BFS traversal
  (collectWindowsProcessFamilyPids) to match POSIX behavior for
  detecting grandchild processes and their listening ports
- index.ts: Remove unused subprocessCheckerToInspector export and
  clean up unused type imports
- Deduplicate normalizeRunningPorts by exporting from terminalStateStore
  and importing in Sidebar.tsx and ThreadTerminalDrawer.tsx
2026-04-04 20:40:03 +00:00
Julius Marmingeandcodex 05a7018f03 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-04-04 13:28:00 -07:00
Julius Marminge 6de4b47ecb Return replay retry state from orchestration recovery (#1728) 2026-04-03 22:05:33 -07:00
27c2b145f8 feat(cli): allow optional positional cwd argument (#1727)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-03 19:49:10 -07:00
8515f02770 Move worktree bootstrap to the server and persist terminal launch context (#1518)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-03 19:49:01 -07:00
Julius Marmingeandcodex e9ed849b53 Persist server OTLP tracing settings across restarts (#1705)
Co-authored-by: codex <[email protected]>
2026-04-02 20:33:30 -07:00
Julius Marmingeandcodex e8f5b4ad5b [codex] Revert stale send spinner fix (#1704)
Co-authored-by: codex <[email protected]>
2026-04-02 20:19:58 -07:00
Julius Marmingeandcodex 752f96e9ae Add server observability tracing and metrics (#1697)
Co-authored-by: codex <[email protected]>
2026-04-03 02:30:51 +00:00
c1yde3 1b272fd709 feat: support IntelliJ IDEA open-in launch (#1673) 2026-04-02 23:57:09 +00:00
Julius Marminge 9013c07f6d Clean up terminal state when threads are archived (#1702) 2026-04-02 16:26:18 -07:00
Vakhtang Vakhtangishvili 085340588a Fix scroll to bottom button flickering near bottom of the chat (#1692) 2026-04-02 23:04:47 +00:00
Harry 48481aa923 Fix stale send spinner after completed turns (#1700) 2026-04-02 22:59:27 +00:00
Julius Marminge da107f315c Fix websocket closing and reopening connections too eagerly (#1701) 2026-04-02 15:56:53 -07:00
IshanandJulius Marminge d2822a8883 fix: use explicit refspec for push in worktrees with slashed branch names (#1684)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 15:29:30 -07:00
Svilen Petrov ae3ea3980d Clicking logo now navigates to threads (#1617) 2026-04-02 21:45:34 +00:00
915a0548c0 Paginate git branch listing and search results (#1691)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 12:38:19 -07:00
Julius Marminge 5ce5472bc3 Scope git action progress toasts to the originating thread (#1675) 2026-04-02 11:39:27 -07:00
Julius Marminge 9ea443d73a Split PR creation into granular progress stages (#1694) 2026-04-02 11:24:24 -07:00
60f7ae86bb Add copy-to-clipboard action for proposed plan card (#1620)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 00:47:47 -07:00
Julius Marmingeandcodex 867cf4cf09 fix: stabilize messages timeline virtualization (#1664)
Co-authored-by: codex <[email protected]>
2026-04-02 00:10:34 -07:00
Julius MarmingeandCursor Agent ae6f9715c6 Normalize sidebar thread state for faster updates (#1668)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 23:56:40 +00:00
Julius Marminge b92c78f552 Scope git query invalidation by cwd (#1670) 2026-04-01 23:52:28 +00:00
801dfe5b41 [codex] fix git remote parsing, PR resolution, and sidebar PR state (#1619)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 16:13:19 -07:00
Julius Marmingeandcodex 823d69f621 perf(server): bootstrap engine from persisted projections (#1648)
Co-authored-by: codex <[email protected]>
2026-04-01 15:07:15 -07:00
Julius Marmingeandcodex 4963fccb05 perf(server): avoid thread-wide scans for message projection (#1647)
Co-authored-by: codex <[email protected]>
2026-04-01 14:48:39 -07:00
Julius Marmingeandcodex dd89d5ce1a perf(server): add targeted projection queries (#1646)
Co-authored-by: codex <[email protected]>
2026-04-01 14:41:03 -07:00
Julius Marmingeandcodex 9132c37c86 [codex] migrate Effect.fn in apps/server/src/persistence/NodeSqliteClient.ts (#1633)
Co-authored-by: codex <[email protected]>
2026-04-01 16:34:52 +00:00
Julius Marmingeandcodex b9c7ea0581 [codex] migrate Effect.fn in apps/server/src/orchestration/Layers/ProviderCommandReactor.ts (#1629)
Co-authored-by: codex <[email protected]>
2026-04-01 16:26:52 +00:00
Julius Marmingeandcodex 556a195c9d [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderService.ts (#1639)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:38 +00:00
Julius Marmingeandcodex 80b282ece7 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderRegistry.ts (#1638)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:36 +00:00
Julius Marmingeandcodex d377e566f8 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-02-16 01:01:24 -08:00
Julius Marminge 38644b0d81 Detect root-process ports and harden web port probing
- Include terminal root PID in port scans so listener-only sessions are marked active
- Improve web port detection for slow/large HTML responses and redirects
- Add integration-style tests for terminal subprocess and web port inspectors
2026-02-15 19:46:11 -08:00
Julius Marminge c11027be4d Show terminal runtime status and web port actions in thread UI
- Pass running terminal IDs/ports from `ChatView` into `ThreadTerminalDrawer`
- Add runtime badges/icons for running terminals and localhost web ports
- Make sidebar thread rows keyboard-activatable and add web-port quick open button
2026-02-15 18:25:22 -08:00
Julius Marminge b3e967e2cf adapters 2026-02-15 16:48:08 -08:00
Julius Marminge 3d082fc73b Detect real web ports and add one-click localhost shortcut
- Probe terminal subprocess ports and keep only likely web servers
- Cache/dedupe port probes and ignore root-path 404 responses
- Show a globe status icon in Sidebar that opens `http://localhost:<port>`
2026-02-15 16:47:19 -08:00
Julius Marminge 94a83ab48e Require all lsof filters when checking listening ports
- Add `-a` to the `lsof` command in terminal port detection
- Prevent mismatched results by combining TCP listen and PID filters correctly
2026-02-15 16:46:51 -08:00
Julius Marminge f2ec777443 Track running terminal ports across terminal activity events
- add `runningPorts` to terminal activity contract and validation
- detect/listen ports in server subprocess inspection and emit activity updates on port changes
- persist terminal-to-port state in web store and show active ports in sidebar indicator
- update server/web/contracts tests for port-aware activity behavior
2026-02-15 16:46:51 -08:00
149 changed files with 15157 additions and 3431 deletions

No files matched your search

+2
View File
@@ -45,6 +45,8 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+34 -1
View File
@@ -28,6 +28,7 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
@@ -76,6 +77,7 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
@@ -99,8 +101,10 @@ let aboutCommitHashCache: string | null | undefined;
let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
@@ -121,6 +125,21 @@ function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function readPersistedBackendObservabilitySettings(): {
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
} {
try {
if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
} catch (error) {
console.warn("[desktop] failed to read persisted backend observability settings", error);
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
}
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
@@ -988,6 +1007,7 @@ function scheduleBackendRestart(reason: string): void {
function startBackend(): void {
if (isQuitting || backendProcess) return;
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
const backendEntry = resolveBackendEntry();
if (!FS.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
@@ -1016,6 +1036,12 @@ function startBackend(): void {
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
...(backendObservabilitySettings.otlpMetricsUrl
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
: {}),
})}\n`,
);
bootstrapStream.end();
@@ -1042,21 +1068,26 @@ function startBackend(): void {
});
child.on("error", (error) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
if (wasExpected) {
return;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
);
if (isQuitting) return;
if (isQuitting || wasExpected) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
@@ -1073,6 +1104,7 @@ function stopBackend(): void {
if (!child) return;
if (child.exitCode === null && child.signalCode === null) {
expectedBackendExitChildren.add(child);
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
@@ -1093,6 +1125,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
if (!child) return;
const backendChild = child;
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
expectedBackendExitChildren.add(backendChild);
await new Promise<void>((resolve) => {
let settled = false;
@@ -289,9 +289,10 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
@@ -333,7 +334,9 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
@@ -1,83 +1,38 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import {
ProjectionSnapshotQuery,
type ProjectionThreadCheckpointContext,
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
function makeSnapshot(input: {
function makeThreadCheckpointContext(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
}): ProjectionThreadCheckpointContext {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
threadId: input.threadId,
projectId: input.projectId,
workspaceRoot: input.workspaceRoot,
worktreePath: input.worktreePath,
checkpoints: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
};
@@ -95,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
@@ -125,7 +80,12 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(snapshot),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
}),
),
);
@@ -175,12 +135,11 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
);
@@ -4,11 +4,11 @@ import {
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { Effect, Layer, Option, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import {
CheckpointDiffQuery,
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.checkpoints.reduce(
const maxTurnCount = threadContext.value.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
});
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
: threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
});
}
const toCheckpointRef = thread.checkpoints.find(
const toCheckpointRef = threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
@@ -80,7 +80,7 @@ function initRepoWithCommit(
});
}
function buildLargeText(lineCount = 20_000): string {
function buildLargeText(lineCount = 5_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("diff --git");
expect(diff).not.toContain("[truncated]");
expect(diff).toContain("+line 19999");
expect(diff).toContain("+line 04999");
}),
);
});
+93
View File
@@ -9,6 +9,18 @@ import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
} as const;
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
@@ -28,6 +40,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -62,6 +75,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Warn",
...defaultObservabilityConfig,
mode: "desktop",
port: 4001,
cwd: process.cwd(),
@@ -89,6 +103,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(true),
authToken: Option.some("flag-token"),
@@ -123,6 +138,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Debug",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
@@ -153,6 +169,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
@@ -162,6 +180,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -187,6 +206,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
@@ -209,6 +231,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
const customCwd = path.join(baseDir, "nested", "project");
const resolved = yield* resolveServerConfig(
{
@@ -216,6 +239,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.some(customCwd),
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -234,6 +258,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
);
for (const directory of [
customCwd,
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
@@ -241,9 +266,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
resolved.attachmentsDir,
resolved.worktreesDir,
path.dirname(resolved.serverLogPath),
path.dirname(resolved.serverTracePath),
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
expect(resolved.cwd).toBe(path.resolve(customCwd));
}),
);
@@ -270,6 +297,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.none(),
authToken: Option.some("flag-token"),
@@ -300,6 +328,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Debug",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
@@ -315,4 +344,68 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
});
}),
);
it.effect("falls back to persisted observability settings when env vars are absent", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
`${JSON.stringify({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
})}\n`,
);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
NetService.layer,
),
),
);
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
authToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
});
+80 -4
View File
@@ -1,6 +1,7 @@
import { NetService } from "@t3tools/shared/Net";
import { Config, Effect, LogLevel, Option, Schema } from "effect";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
@@ -12,7 +13,7 @@ import {
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { resolveBaseDir } from "./os-jank";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -27,6 +28,8 @@ const BootstrapEnvelopeSchema = Schema.Struct({
authToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
@@ -81,6 +84,27 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -116,6 +140,7 @@ interface CliServerFlags {
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
@@ -131,12 +156,25 @@ const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
return parsePersistedServerObservabilitySettings(raw);
});
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const env = yield* EnvServerConfig;
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -188,8 +226,16 @@ export const resolveServerConfig = (
),
),
);
const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
);
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const noBrowser = resolveBooleanFlag(
flags.noBrowser,
Option.getOrElse(
@@ -248,11 +294,35 @@ export const resolveServerConfig = (
const config: ServerConfigShape = {
logLevel,
traceMinLevel: env.traceMinLevel,
traceTimingEnabled: env.traceTimingEnabled,
traceBatchWindowMs: env.traceBatchWindowMs,
traceMaxBytes: env.traceMaxBytes,
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
),
) ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
),
) ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
mode,
port,
cwd: process.cwd(),
cwd,
baseDir,
...derivedPaths,
serverTracePath,
host,
staticDir,
devUrl,
@@ -270,6 +340,12 @@ const commandFlags = {
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
Argument.withDescription(
"Working directory for provider sessions (defaults to the current directory).",
),
Argument.optional,
),
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
+20
View File
@@ -25,6 +25,7 @@ export interface ServerDerivedPaths {
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly serverTracePath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
@@ -36,6 +37,15 @@ export interface ServerDerivedPaths {
*/
export interface ServerConfigShape extends ServerDerivedPaths {
readonly logLevel: LogLevel.LogLevel;
readonly traceMinLevel: LogLevel.LogLevel;
readonly traceTimingEnabled: boolean;
readonly traceBatchWindowMs: number;
readonly traceMaxBytes: number;
readonly traceMaxFiles: number;
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
readonly otlpExportIntervalMs: number;
readonly otlpServiceName: string;
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
@@ -68,6 +78,7 @@ export const deriveServerPaths = Effect.fn(function* (
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
serverTracePath: join(logsDir, "server.trace.ndjson"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
@@ -117,6 +128,15 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
return {
logLevel: "Error",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
cwd,
baseDir,
...derivedPaths,
+289 -70
View File
@@ -59,6 +59,23 @@ function git(
});
}
function configureRemote(
cwd: string,
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
return yield* git(cwd, [
"config",
"--replace-all",
`remote.${remoteName}.fetch`,
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
]);
});
}
function runShellCommand(input: {
command: string;
cwd: string;
@@ -369,6 +386,36 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("paginates branch results and returns paging metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });
const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });
expect(firstPage.totalCount).toBe(4);
expect(firstPage.nextCursor).toBe(2);
expect(firstPage.branches.map((branch) => branch.name)).toEqual([
initialBranch,
"feature-a",
]);
const secondPage = yield* (yield* GitCore).listBranches({
cwd: tmp,
cursor: firstPage.nextCursor ?? 0,
limit: 2,
});
expect(secondPage.totalCount).toBe(4);
expect(secondPage.nextCursor).toBeNull();
expect(secondPage.branches.map((branch) => branch.name)).toEqual([
"feature-b",
"feature-c",
]);
}),
);
it.effect("parses separate branch names when column.ui is always enabled", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -514,6 +561,41 @@ it.layer(TestLayer)("git integration", (it) => {
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
it.effect(
"filters branch queries before pagination and dedupes origin refs with local matches",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
const result = yield* (yield* GitCore).listBranches({
cwd: tmp,
query: "feature/",
limit: 10,
});
expect(result.totalCount).toBe(2);
expect(result.nextCursor).toBeNull();
expect(result.branches.map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
}),
);
});
// ── checkoutGitBranch ──
@@ -587,7 +669,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("keeps checkout successful when upstream refresh fails", () =>
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -612,7 +694,7 @@ it.layer(TestLayer)("git integration", (it) => {
const realGitCore = yield* GitCore;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
refreshFetchAttempts += 1;
return Effect.fail(
new GitCommandError({
@@ -626,16 +708,15 @@ it.layer(TestLayer)("git integration", (it) => {
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(refreshFetchAttempts).toBe(1);
}),
);
const status = yield* core.statusDetails(source);
expect(refreshFetchAttempts).toBe(1);
expect(status.branch).toBe(featureBranch);
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
}),
);
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
it.effect("defers upstream refresh until statusDetails is requested", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -657,10 +738,10 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchArgs = [...input.args];
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
refreshFetchAttempts += 1;
return Effect.succeed({
code: 0,
stdout: "",
@@ -672,73 +753,137 @@ it.layer(TestLayer)("git integration", (it) => {
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchArgs).not.toBeNull();
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
expect(fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
expect(refreshFetchAttempts).toBe(0);
const status = yield* core.statusDetails(source);
expect(status.branch).toBe(featureBranch);
expect(refreshFetchAttempts).toBe(1);
}),
);
it.effect("returns checkout result before background upstream refresh completes", () =>
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature/background-refresh";
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchStarted = false;
let releaseFetch!: () => void;
const waitForReleasePromise = new Promise<void>((resolve) => {
releaseFetch = resolve;
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchStarted = true;
return Effect.promise(() =>
waitForReleasePromise.then(() => ({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
})),
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
expect(input.cwd).toBe("/repo");
return ok();
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in shared refresh cache test.",
}),
);
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
);
}
return realGitCore.execute(input);
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchStarted).toBe(true);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
releaseFetch();
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
@@ -779,16 +924,21 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(source, remoteName, remote, remoteName);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
@@ -805,6 +955,34 @@ it.layer(TestLayer)("git integration", (it) => {
});
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchArgs = [...input.args];
return Effect.succeed({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
}
return realGitCore.execute(input);
});
const status = yield* core.statusDetails(source);
expect(status.branch).toBe("upstream/feature");
expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`);
expect(fetchArgs).toEqual([
"--git-dir",
path.join(source, ".git"),
"fetch",
"--quiet",
"--no-tags",
remoteName,
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
]);
}),
);
@@ -1691,6 +1869,47 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature/slash-remote-push";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(tmp, remoteName, remote, remoteName);
yield* git(tmp, ["push", "-u", remoteName, initialBranch]);
yield* git(tmp, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature base"]);
yield* git(tmp, ["push", "-u", remoteName, featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature update"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(false);
expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`${remoteName}/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+229 -96
View File
@@ -18,7 +18,10 @@ import {
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { compactTraceAttributes } from "../../observability/Attributes.ts";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
import {
GitCore,
type ExecuteGitProgress,
@@ -27,6 +30,11 @@ import {
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
import {
parseRemoteNames,
parseRemoteNamesInGitOrder,
parseRemoteRefWithRemoteNames,
} from "../remoteRefs.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
@@ -41,8 +49,10 @@ 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_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
type TraceTailState = {
processedChars: number;
@@ -50,7 +60,7 @@ type TraceTailState = {
};
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
gitCommonDir: string;
upstreamRef: string;
remoteName: string;
upstreamBranch: string;
@@ -177,12 +187,38 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
function filterBranchesForListQuery(
branches: ReadonlyArray<GitBranch>,
query?: string,
): ReadonlyArray<GitBranch> {
if (!query) {
return branches;
}
const normalizedQuery = query.toLowerCase();
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
}
function paginateBranches(input: {
branches: ReadonlyArray<GitBranch>;
cursor?: number | undefined;
limit?: number | undefined;
}): {
branches: ReadonlyArray<GitBranch>;
nextCursor: number | null;
totalCount: number;
} {
const cursor = input.cursor ?? 0;
const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
const totalCount = input.branches.length;
const branches = input.branches.slice(cursor, cursor + limit);
const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null;
return {
branches,
nextCursor,
totalCount,
};
}
function sanitizeRemoteName(value: string): string {
@@ -217,30 +253,41 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
return remotes;
}
function parseRemoteRefWithRemoteNames(
branchName: string,
function parseUpstreamRefWithRemoteNames(
upstreamRef: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
if (!parsed) {
return null;
}
return null;
return {
upstreamRef,
remoteName: parsed.remoteName,
upstreamBranch: parsed.branchName,
};
}
function parseUpstreamRefByFirstSeparator(
upstreamRef: string,
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex).trim();
const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim();
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
}
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
@@ -327,6 +374,18 @@ interface Trace2Monitor {
readonly flush: Effect.Effect<void, never>;
}
const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
Effect.currentSpan.pipe(
Effect.tap((span) =>
Effect.sync(() => {
span.event(name, nowUnixNano(), compactTraceAttributes(attributes));
}),
),
Effect.catch(() => Effect.void),
);
function trace2ChildKey(record: Record<string, unknown>): string | null {
const childId = record.child_id;
if (typeof childId === "number" || typeof childId === "string") {
@@ -399,6 +458,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_start") {
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
yield* addCurrentSpanEvent("git.hook.started", {
hookName,
});
if (progress.onHookStarted) {
yield* progress.onHookStarted(hookName);
}
@@ -407,12 +469,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_exit") {
hookStartByChildKey.delete(childKey);
const code = traceRecord.success.code;
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null;
yield* addCurrentSpanEvent("git.hook.finished", {
hookName: started?.hookName ?? hookName,
exitCode,
durationMs,
});
if (progress.onHookFinished) {
const code = traceRecord.success.code;
yield* progress.onHookFinished({
hookName: started?.hookName ?? hookName,
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
exitCode,
durationMs,
});
}
}
@@ -564,13 +633,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const path = yield* Path.Path;
const { worktreesDir } = yield* ServerConfig;
let execute: GitCoreShape["execute"];
let executeRaw: GitCoreShape["execute"];
if (options?.executeOverride) {
execute = options.executeOverride;
executeRaw = options.executeOverride;
} else {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
execute = Effect.fnUntraced(function* (input) {
executeRaw = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
@@ -671,6 +740,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
const execute: GitCoreShape["execute"] = (input) =>
executeRaw(input).pipe(
withMetrics({
counter: gitCommandsTotal,
timer: gitCommandDuration,
attributes: {
operation: input.operation,
},
}),
Effect.withSpan(input.operation, {
kind: "client",
attributes: {
"git.operation": input.operation,
"git.cwd": input.cwd,
"git.args_count": input.args.length,
},
}),
);
const executeGit = (
operation: string,
cwd: string,
@@ -792,45 +880,27 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return null;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNames),
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
);
return (
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
parseUpstreamRefByFirstSeparator(upstreamRef)
);
});
const fetchUpstreamRef = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
return runGit(
"GitCore.fetchUpstreamRef",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
true,
);
};
const fetchUpstreamRefForStatus = (
cwd: string,
gitCommonDir: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
"GitCore.fetchUpstreamRefForStatus",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
{
allowNonZeroExit: true,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -838,10 +908,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
).pipe(Effect.asVoid);
};
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
const gitCommonDir = yield* runGitStdout("GitCore.resolveGitCommonDir", cwd, [
"rev-parse",
"--git-common-dir",
]).pipe(Effect.map((stdout) => stdout.trim()));
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
cacheKey: StatusUpstreamRefreshCacheKey,
) {
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
upstreamRef: cacheKey.upstreamRef,
remoteName: cacheKey.remoteName,
upstreamBranch: cacheKey.upstreamBranch,
@@ -852,8 +930,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const statusUpstreamRefreshCache = yield* Cache.makeWith({
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: refreshStatusUpstreamCacheEntry,
// Keep successful refreshes warm; drop failures immediately so next request can retry.
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
? STATUS_UPSTREAM_REFRESH_INTERVAL
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
});
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
@@ -861,10 +942,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusUpstreamRefreshCache,
new StatusUpstreamRefreshCacheKey({
cwd,
gitCommonDir,
upstreamRef: upstream.upstreamRef,
remoteName: upstream.remoteName,
upstreamBranch: upstream.upstreamBranch,
@@ -872,14 +954,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
);
});
const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* (
cwd: string,
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
@@ -919,7 +993,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
Effect.map(parseRemoteNamesInGitOrder),
);
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
@@ -1106,15 +1180,52 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
],
{ concurrency: "unbounded" },
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
{
allowNonZeroExit: true,
},
);
if (statusResult.code !== 0) {
const stderr = statusResult.stderr.trim();
return yield* createGitCommandError(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
stderr || "git status failed",
);
}
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
"diff",
"--cached",
"--numstat",
]),
executeGit(
"GitCore.statusDetails.defaultRef",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
allowNonZeroExit: true,
},
),
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
],
{ concurrency: "unbounded" },
);
const statusStdout = statusResult.stdout;
const defaultBranch =
defaultRefResult.code === 0
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
@@ -1181,6 +1292,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
files.sort((a, b) => a.path.localeCompare(b.path));
return {
isRepo: true,
hasOriginRemote,
isDefaultBranch:
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master"))),
branch,
upstreamRef,
hasWorkingTreeChanges,
@@ -1198,6 +1315,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const status: GitCoreShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
isRepo: details.isRepo,
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
@@ -1346,7 +1466,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
"push",
"-u",
publishRemoteName,
branch,
`HEAD:refs/heads/${branch}`,
]);
return {
status: "pushed" as const,
@@ -1576,7 +1696,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false, hasOriginRemote: false };
return {
branches: [],
isRepo: false,
hasOriginRemote: false,
nextCursor: null,
totalCount: 0,
};
}
return yield* createGitCommandError(
"GitCore.listBranches",
@@ -1740,9 +1866,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
})
: [];
const branches = [...localBranches, ...remoteBranches];
const branches = paginateBranches({
branches: filterBranchesForListQuery(
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
input.query,
),
cursor: input.cursor,
limit: input.limit,
});
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
return {
branches: [...branches.branches],
isRepo: true,
hasOriginRemote: remoteNames.includes("origin"),
nextCursor: branches.nextCursor,
totalCount: branches.totalCount,
};
});
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
@@ -1939,12 +2078,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
},
);
+1 -1
View File
@@ -187,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -56,7 +56,7 @@ export interface GitManagerShape {
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
+67
View File
@@ -0,0 +1,67 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
}
export function parseRemoteRefWithRemoteNames(
ref: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; branchName: string } | null {
const trimmedRef = ref.trim();
if (trimmedRef.length === 0) {
return null;
}
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedRef.startsWith(remotePrefix)) {
continue;
}
const branchName = trimmedRef.slice(remotePrefix.length).trim();
if (branchName.length === 0) {
return null;
}
return {
remoteRef: trimmedRef,
remoteName,
branchName,
};
}
return null;
}
export function extractBranchNameFromRemoteRef(
ref: string,
options?: {
remoteName?: string | null;
remoteNames?: ReadonlyArray<string>;
},
): string {
const normalized = ref.trim();
if (normalized.length === 0) {
return "";
}
if (normalized.startsWith("refs/remotes/")) {
return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options);
}
const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);
const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);
if (parsedRemoteRef) {
return parsedRemoteRef.branchName;
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
@@ -0,0 +1,46 @@
import { assert, describe, it } from "@effect/vitest";
import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts";
describe("Attributes", () => {
it("normalizes circular arrays, maps, and sets without recursing forever", () => {
const array: Array<unknown> = ["alpha"];
array.push(array);
const map = new Map<string, unknown>();
map.set("self", map);
const set = new Set<unknown>();
set.add(set);
assert.deepStrictEqual(
compactTraceAttributes({
array,
map,
set,
}),
{
array: ["alpha", "[Circular]"],
map: { self: "[Circular]" },
set: ["[Circular]"],
},
);
});
it("normalizes invalid dates without throwing", () => {
assert.deepStrictEqual(
compactTraceAttributes({
invalidDate: new Date("not-a-real-date"),
}),
{
invalidDate: "Invalid Date",
},
);
});
it("groups GPT-family models under a shared metric label", () => {
assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude");
});
});
+128
View File
@@ -0,0 +1,128 @@
import { Cause, Exit } from "effect";
export type MetricAttributeValue = string;
export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
export type TraceAttributes = Readonly<Record<string, unknown>>;
export type ObservabilityOutcome = "success" | "failure" | "interrupt";
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function markSeen(value: object, seen: WeakSet<object>): boolean {
if (seen.has(value)) {
return true;
}
seen.add(value);
return false;
}
function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
if (
value === null ||
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
return value ?? null;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
...(value.stack ? { stack: value.stack } : {}),
};
}
if (Array.isArray(value)) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return value.map((entry) => normalizeJsonValue(entry, seen));
}
if (value instanceof Map) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Array.from(value.entries(), ([key, entryValue]) => [
String(key),
normalizeJsonValue(entryValue, seen),
]),
);
}
if (value instanceof Set) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
}
if (!isPlainObject(value)) {
return String(value);
}
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
);
}
export function compactTraceAttributes(
attributes: Readonly<Record<string, unknown>>,
): TraceAttributes {
return Object.fromEntries(
Object.entries(attributes)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, normalizeJsonValue(value)]),
);
}
export function compactMetricAttributes(
attributes: Readonly<Record<string, unknown>>,
): MetricAttributes {
return Object.fromEntries(
Object.entries(attributes).flatMap(([key, value]) => {
if (value === undefined || value === null) {
return [];
}
if (typeof value === "string") {
return [[key, value]];
}
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
return [[key, String(value)]];
}
return [];
}),
);
}
export function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {
if (Exit.isSuccess(exit)) {
return "success";
}
return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure";
}
export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {
const normalized = model?.trim().toLowerCase();
if (!normalized) {
return undefined;
}
if (normalized.includes("gpt")) {
return "gpt";
}
if (normalized.includes("claude")) {
return "claude";
}
if (normalized.includes("gemini")) {
return "gemini";
}
return "other";
}
@@ -0,0 +1,64 @@
import { Effect, Layer, References, Tracer } from "effect";
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { ServerConfig } from "../../config.ts";
import { ServerLoggerLive } from "../../serverLogger.ts";
import { makeLocalFileTracer } from "../LocalFileTracer.ts";
const otlpSerializationLayer = OtlpSerialization.layerJson;
export const ObservabilityLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
);
const tracerLayer = Layer.effect(
Tracer.Tracer,
Effect.gen(function* () {
const delegate =
config.otlpTracesUrl === undefined
? undefined
: yield* OtlpTracer.make({
url: config.otlpTracesUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
});
return yield* makeLocalFileTracer({
filePath: config.serverTracePath,
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
...(delegate ? { delegate } : {}),
});
}),
).pipe(Layer.provideMerge(otlpSerializationLayer));
const metricsLayer =
config.otlpMetricsUrl === undefined
? Layer.empty
: OtlpMetrics.layer({
url: config.otlpMetricsUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
}).pipe(Layer.provideMerge(otlpSerializationLayer));
return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);
}),
);
@@ -0,0 +1,117 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Layer, Logger, References, Tracer } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
import { makeLocalFileTracer } from "./LocalFileTracer.ts";
const makeTestLayer = (tracePath: string) =>
Layer.mergeAll(
Layer.effect(
Tracer.Tracer,
makeLocalFileTracer({
filePath: tracePath,
maxBytes: 1024 * 1024,
maxFiles: 2,
batchWindowMs: 10_000,
}),
),
Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
);
const readTraceRecords = (tracePath: string): Array<TraceRecord> =>
fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as TraceRecord);
describe("LocalFileTracer", () => {
it.effect("writes nested spans to disk and captures log messages as span events", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.gen(function* () {
const program = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.parent": true,
});
yield* Effect.logInfo("parent event");
yield* Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.child": true,
});
yield* Effect.logInfo("child event");
}).pipe(Effect.withSpan("child-span"));
}).pipe(Effect.withSpan("parent-span"));
yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
}),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 2);
const parent = records.find((record) => record.name === "parent-span");
const child = records.find((record) => record.name === "child-span");
assert.notEqual(parent, undefined);
assert.notEqual(child, undefined);
if (!parent || !child) {
return;
}
assert.equal(child.parentSpanId, parent.spanId);
assert.equal(parent.attributes["demo.parent"], true);
assert.equal(child.attributes["demo.child"], true);
assert.equal(
parent.events.some((event) => event.name === "parent event"),
true,
);
assert.equal(
child.events.some((event) => event.name === "child event"),
true,
);
assert.equal(
child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
true,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("serializes interrupted spans with an interrupted exit status", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.exit(
Effect.interrupt.pipe(
Effect.withSpan("interrupt-span"),
Effect.provide(makeTestLayer(tracePath)),
),
),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 1);
assert.equal(records[0]?.name, "interrupt-span");
assert.equal(records[0]?.exit._tag, "Interrupted");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
});
@@ -0,0 +1,104 @@
import type * as Exit from "effect/Exit";
import { Effect, Option, Tracer } from "effect";
import { spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
export interface LocalFileTracerOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly delegate?: Tracer.Tracer;
}
class LocalFileSpan implements Tracer.Span {
readonly _tag = "Span";
readonly name: string;
readonly spanId: string;
readonly traceId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly annotations: Tracer.Span["annotations"];
readonly links: Array<Tracer.SpanLink>;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
status: Tracer.SpanStatus;
attributes: Map<string, unknown>;
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
private readonly delegate: Tracer.Span,
private readonly push: (record: ReturnType<typeof spanToTraceRecord>) => void,
) {
this.name = delegate.name;
this.spanId = delegate.spanId;
this.traceId = delegate.traceId;
this.parent = options.parent;
this.annotations = options.annotations;
this.links = [...options.links];
this.sampled = delegate.sampled;
this.kind = delegate.kind;
this.status = {
_tag: "Started",
startTime: options.startTime,
};
this.attributes = new Map();
this.events = [];
}
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
this.status = {
_tag: "Ended",
startTime: this.status.startTime,
endTime,
exit,
};
this.delegate.end(endTime, exit);
if (this.sampled) {
this.push(spanToTraceRecord(this));
}
}
attribute(key: string, value: unknown): void {
this.attributes.set(key, value);
this.delegate.attribute(key, value);
}
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
const nextAttributes = attributes ?? {};
this.events.push([name, startTime, nextAttributes]);
this.delegate.event(name, startTime, nextAttributes);
}
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
this.links.push(...links);
this.delegate.addLinks(links);
}
}
export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
options: LocalFileTracerOptions,
) {
const sink = yield* makeTraceSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
batchWindowMs: options.batchWindowMs,
});
const delegate =
options.delegate ??
Tracer.make({
span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
});
return Tracer.make({
span(spanOptions) {
return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
},
...(delegate.context ? { context: delegate.context } : {}),
});
});
@@ -0,0 +1,111 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("withMetrics", () => {
it.effect("supports pipe-style usage", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_pipe_total");
const timer = Metric.timer("with_metrics_pipe_duration");
const result = yield* Effect.succeed("ok").pipe(
withMetrics({
counter,
timer,
attributes: {
operation: "pipe",
},
}),
);
assert.equal(result, "ok");
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_total", {
operation: "pipe",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", {
operation: "pipe",
}),
true,
);
}),
);
it.effect("supports direct invocation", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_direct_total");
yield* withMetrics(Effect.fail("boom"), {
counter,
attributes: {
operation: "direct",
},
}).pipe(Effect.exit);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_direct_total", {
operation: "direct",
outcome: "failure",
}),
true,
);
}),
);
it.effect("evaluates attributes lazily after the wrapped effect runs", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = "unknown";
yield* Effect.sync(() => {
provider = "codex";
}).pipe(
withMetrics({
counter,
timer,
attributes: () => ({
provider,
operation: "lazy",
}),
}),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: "codex",
operation: "lazy",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: "codex",
operation: "lazy",
}),
true,
);
}),
);
});
+160
View File
@@ -0,0 +1,160 @@
import { Duration, Effect, Exit, Metric } from "effect";
import { dual } from "effect/Function";
import {
compactMetricAttributes,
normalizeModelMetricLabel,
outcomeFromExit,
} from "./Attributes.ts";
export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
description: "Total RPC requests handled by the websocket RPC server.",
});
export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
description: "RPC request handling duration.",
});
export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
description: "Total orchestration commands dispatched.",
});
export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
description: "Orchestration command dispatch duration.",
});
export const orchestrationCommandAckDuration = Metric.timer(
"t3_orchestration_command_ack_duration",
{
description:
"Time from orchestration command dispatch to the first committed domain event emitted for that command.",
},
);
export const orchestrationEventsProcessedTotal = Metric.counter(
"t3_orchestration_events_processed_total",
{
description: "Total orchestration intent events processed by runtime reactors.",
},
);
export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
description: "Total provider session lifecycle operations.",
});
export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
description: "Total provider turn lifecycle operations.",
});
export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
description: "Provider turn request duration.",
});
export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
description: "Total canonical provider runtime events processed.",
});
export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
description: "Total git commands executed by the server runtime.",
});
export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
description: "Git command execution duration.",
});
export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
description: "Total terminal sessions started.",
});
export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
description: "Total terminal restart requests handled.",
});
export const metricAttributes = (
attributes: Readonly<Record<string, unknown>>,
): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
export const increment = (
metric: Metric.Metric<number, unknown>,
attributes: Readonly<Record<string, unknown>>,
amount = 1,
) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
export interface WithMetricsOptions {
readonly counter?: Metric.Metric<number, unknown>;
readonly timer?: Metric.Metric<Duration.Duration, unknown>;
readonly attributes?:
| Readonly<Record<string, unknown>>
| (() => Readonly<Record<string, unknown>>);
readonly outcomeAttributes?: (
outcome: ReturnType<typeof outcomeFromExit>,
) => Readonly<Record<string, unknown>>;
}
const withMetricsImpl = <A, E, R>(
effect: Effect.Effect<A, E, R>,
options: WithMetricsOptions,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
const baseAttributes =
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
if (options.timer) {
yield* Metric.update(
Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
duration,
);
}
if (options.counter) {
const outcome = outcomeFromExit(exit);
yield* Metric.update(
Metric.withAttributes(
options.counter,
metricAttributes({
...baseAttributes,
outcome,
...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
}),
),
1,
);
}
if (Exit.isSuccess(exit)) {
return exit.value;
}
return yield* Effect.failCause(exit.cause);
});
export const withMetrics: {
<A, E, R>(
options: WithMetricsOptions,
): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
<A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
} = dual(2, withMetricsImpl);
export const providerMetricAttributes = (
provider: string,
extra?: Readonly<Record<string, unknown>>,
) =>
compactMetricAttributes({
provider,
...extra,
});
export const providerTurnMetricAttributes = (input: {
readonly provider: string;
readonly model: string | null | undefined;
readonly extra?: Readonly<Record<string, unknown>>;
}) => {
const modelFamily = normalizeModelMetricLabel(input.model);
return compactMetricAttributes({
provider: input.provider,
...(modelFamily ? { modelFamily } : {}),
...input.extra,
});
};
@@ -0,0 +1,161 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Exit, Metric, Stream } from "effect";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./RpcInstrumentation.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("RpcInstrumentation", () => {
it.effect("records success metrics for unary RPC handlers", () =>
Effect.gen(function* () {
yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.success.span"));
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.success",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.success",
}),
true,
);
}),
);
it.effect("records failure outcomes for unary RPC handlers", () =>
Effect.gen(function* () {
yield* Effect.exit(
observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.failure.span")),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.failure",
}),
true,
);
}),
);
it.effect("records subscription activation metrics for stream RPC handlers", () =>
Effect.gen(function* () {
const events = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream",
Effect.succeed(Stream.make("a", "b")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.span")),
);
assert.deepStrictEqual(Array.from(events), ["a", "b"]);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream",
}),
true,
);
}),
);
it.effect("records failure outcomes for direct stream RPC handlers during consumption", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.stream.failure",
Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.failure",
}),
true,
);
}),
);
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream.effect.failure",
Effect.succeed(Stream.fail("boom")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.effect.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.effect.failure",
}),
true,
);
}),
);
});
@@ -0,0 +1,89 @@
import { Duration, Effect, Exit, Metric, Stream } from "effect";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
const annotateRpcSpan = (
method: string,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<void, never, never> =>
Effect.annotateCurrentSpan({
"rpc.method": method,
...traceAttributes,
});
const recordRpcStreamMetrics = <E>(
method: string,
startedAt: number,
exit: Exit.Exit<unknown, E>,
): Effect.Effect<void, never, never> =>
Effect.gen(function* () {
yield* Metric.update(
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
Duration.millis(Math.max(0, Date.now() - startedAt)),
);
yield* Metric.update(
Metric.withAttributes(
rpcRequestsTotal,
metricAttributes({
method,
outcome: outcomeFromExit(exit),
}),
),
1,
);
});
export const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
return yield* effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
attributes: {
method,
},
}),
);
});
export const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
}),
);
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
if (Exit.isFailure(exit)) {
yield* recordRpcStreamMetrics(method, startedAt, exit);
return yield* Effect.failCause(exit.cause);
}
return exit.value.pipe(
Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
);
}),
);
@@ -0,0 +1,100 @@
import { Cause, Exit, Option, Tracer } from "effect";
import { compactTraceAttributes } from "./Attributes.ts";
export interface TraceRecord {
readonly type: "effect-span";
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly parentSpanId?: string;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
readonly startTimeUnixNano: string;
readonly endTimeUnixNano: string;
readonly durationMs: number;
readonly attributes: Readonly<Record<string, unknown>>;
readonly events: ReadonlyArray<{
readonly name: string;
readonly timeUnixNano: string;
readonly attributes: Readonly<Record<string, unknown>>;
}>;
readonly links: ReadonlyArray<{
readonly traceId: string;
readonly spanId: string;
readonly attributes: Readonly<Record<string, unknown>>;
}>;
readonly exit:
| {
readonly _tag: "Success";
}
| {
readonly _tag: "Interrupted";
readonly cause: string;
}
| {
readonly _tag: "Failure";
readonly cause: string;
};
}
interface SerializableSpan {
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly status: Tracer.SpanStatus;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
readonly attributes: ReadonlyMap<string, unknown>;
readonly links: ReadonlyArray<Tracer.SpanLink>;
readonly events: ReadonlyArray<
readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
>;
}
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): TraceRecord["exit"] {
if (Exit.isSuccess(exit)) {
return { _tag: "Success" };
}
if (Cause.hasInterruptsOnly(exit.cause)) {
return {
_tag: "Interrupted",
cause: Cause.pretty(exit.cause),
};
}
return {
_tag: "Failure",
cause: Cause.pretty(exit.cause),
};
}
export function spanToTraceRecord(span: SerializableSpan): TraceRecord {
const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
return {
type: "effect-span",
name: span.name,
traceId: span.traceId,
spanId: span.spanId,
...(parentSpanId ? { parentSpanId } : {}),
sampled: span.sampled,
kind: span.kind,
startTimeUnixNano: String(status.startTime),
endTimeUnixNano: String(status.endTime),
durationMs: Number(status.endTime - status.startTime) / 1_000_000,
attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
events: span.events.map(([name, startTime, attributes]) => ({
name,
timeUnixNano: String(startTime),
attributes: compactTraceAttributes(attributes),
})),
links: span.links.map((link) => ({
traceId: link.span.traceId,
spanId: link.span.spanId,
attributes: compactTraceAttributes(link.attributes),
})),
exit: formatTraceExit(status.exit),
};
}
@@ -0,0 +1,152 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
const makeRecord = (name: string, suffix = ""): TraceRecord => ({
type: "effect-span",
name,
traceId: `trace-${name}-${suffix}`,
spanId: `span-${name}-${suffix}`,
sampled: true,
kind: "internal",
startTimeUnixNano: "1",
endTimeUnixNano: "2",
durationMs: 1,
attributes: {
payload: suffix,
},
events: [],
links: [],
exit: {
_tag: "Success",
},
});
describe("TraceSink", () => {
it.effect("flushes buffered records on close", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
sink.push(makeRecord("alpha"));
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.name, "alpha");
assert.equal(lines[1]?.name, "beta");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("rotates the trace file when the configured max size is exceeded", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 180,
maxFiles: 2,
batchWindowMs: 10_000,
});
for (let index = 0; index < 8; index += 1) {
sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
yield* sink.flush;
}
yield* sink.close();
const matchingFiles = fs
.readdirSync(tempDir)
.filter(
(entry) =>
entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."),
)
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.1"),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.3"),
false,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("drops only the invalid record when serialization fails", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const circular: Array<unknown> = [];
circular.push(circular);
sink.push(makeRecord("alpha"));
sink.push({
...makeRecord("invalid"),
attributes: {
circular,
},
} as TraceRecord);
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.deepStrictEqual(
lines.map((line) => line.name),
["alpha", "beta"],
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
});
@@ -0,0 +1,68 @@
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
const FLUSH_BUFFER_THRESHOLD = 32;
export interface TraceSinkOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
}
export interface TraceSink {
readonly filePath: string;
push: (record: TraceRecord) => void;
flush: Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
const sink = new RotatingFileSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
});
let buffer: Array<string> = [];
const flushUnsafe = () => {
if (buffer.length === 0) {
return;
}
const chunk = buffer.join("");
buffer = [];
try {
sink.write(chunk);
} catch {
buffer.unshift(chunk);
}
};
const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
yield* Effect.forkScoped(
Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
);
return {
filePath: options.filePath,
push(record) {
try {
buffer.push(`${JSON.stringify(record)}\n`);
if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
flushUnsafe();
}
} catch {
return;
}
},
flush,
close: () => flush,
} satisfies TraceSink;
});
+37 -1
View File
@@ -75,10 +75,19 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace"],
});
const ideaLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLaunch, {
command: "idea",
args: ["/tmp/workspace"],
});
}),
);
it.effect("uses --goto when editor supports line/column suffixes", () =>
it.effect("applies launch-style-specific navigation arguments", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
@@ -142,6 +151,33 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
const zedLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineOnly, {
command: "zed",
args: ["/tmp/workspace/AGENTS.md:48"],
});
const ideaLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineOnly, {
command: "idea",
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
});
const ideaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineAndColumn, {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
}),
);
+48 -7
View File
@@ -34,10 +34,45 @@ interface CommandAvailabilityOptions {
readonly env?: NodeJS.ProcessEnv;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
function parseTargetPathAndPosition(target: string): {
path: string;
line: string | undefined;
column: string | undefined;
} | null {
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
if (!match?.[1] || !match[2]) {
return null;
}
return {
path: match[1],
line: match[2],
column: match[3],
};
}
function resolveCommandEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const parsedTarget = parseTargetPathAndPosition(target);
switch (editor.launchStyle) {
case "direct-path":
return [target];
case "goto":
return parsedTarget ? ["--goto", target] : [target];
case "line-column": {
if (!parsedTarget) {
return [target];
}
const { path, line, column } = parsedTarget;
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
}
}
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -198,19 +233,25 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
yield* Effect.annotateCurrentSpan({
"open.editor": input.editor,
"open.cwd": input.cwd,
"open.platform": platform,
});
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] };
return {
command: editorDef.command,
args: resolveCommandEditorArgs(editorDef, input.cwd),
};
}
if (editorDef.id !== "file-manager") {
@@ -23,6 +23,7 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -249,6 +250,7 @@ describe("CheckpointReactor", () => {
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -119,7 +119,7 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
threadId: ThreadId,
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -153,7 +153,7 @@ const make = Effect.gen(function* () {
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
@@ -188,7 +188,7 @@ const make = Effect.gen(function* () {
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
// it against the previous turn, then dispatches the domain events to update
// the orchestration read model.
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly thread: {
@@ -321,70 +321,70 @@ const make = Effect.gen(function* () {
});
// Captures a real git checkpoint when a turn completes via a runtime event.
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
});
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
},
);
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
// is detected via a domain event. This replaces the placeholder with a real
@@ -394,7 +394,7 @@ const make = Effect.gen(function* () {
// events from the Codex runtime. This handler fires when the corresponding
// domain event arrives, allowing the reactor to capture the actual filesystem
// state into a git ref and dispatch a replacement checkpoint.
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
) {
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
@@ -448,57 +448,59 @@ const make = Effect.gen(function* () {
});
});
const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
});
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
},
);
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
"ensurePreTurnBaselineFromDomainTurnStart",
)(function* (
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
@@ -557,7 +559,7 @@ const make = Effect.gen(function* () {
});
});
const handleRevertRequested = Effect.fnUntraced(function* (
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
) {
const now = new Date().toISOString();
@@ -685,7 +687,7 @@ const make = Effect.gen(function* () {
);
});
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
@@ -724,7 +726,9 @@ const make = Effect.gen(function* () {
}
});
const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
) {
if (event.type === "turn.started") {
yield* ensurePreTurnBaselineFromTurnStart(event);
return;
@@ -8,7 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -21,11 +21,13 @@ import {
} from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -39,6 +41,7 @@ async function createOrchestrationSystem() {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -59,7 +62,117 @@ function now() {
return new Date().toISOString();
}
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
append: () =>
Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append should not be called during bootstrap",
}),
),
readFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
new PersistenceSqlError({
operation: "test.readAll",
detail: "historical replay should not be used during bootstrap",
}),
),
};
const projectionSnapshot = {
snapshotSequence: 7,
updatedAt: "2026-03-03T00:00:04.000Z",
projects: [
{
id: asProjectId("project-bootstrap"),
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
createdAt: "2026-03-03T00:00:00.000Z",
updatedAt: "2026-03-03T00:00:01.000Z",
deletedAt: null,
},
],
threads: [
{
id: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
};
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(projectionSnapshot),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
Layer.succeed(OrchestrationProjectionPipeline, {
bootstrap: Effect.void,
projectEvent: () => Effect.void,
} satisfies OrchestrationProjectionPipelineShape),
),
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const readModel = await runtime.runPromise(engine.getReadModel());
expect(readModel.snapshotSequence).toBe(7);
expect(readModel.projects).toHaveLength(1);
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
expect(readModel.threads).toHaveLength(1);
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
await runtime.dispose();
});
it("returns deterministic read models for repeated reads", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
@@ -306,6 +419,95 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("records command ack duration using the first committed event type", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
projectId: asProjectId("project-ack"),
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
threadId: ThreadId.makeUnsafe("thread-ack"),
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
);
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
commandType: "thread.create",
aggregateKind: "thread",
ackEventType: "thread.created",
}),
).toBe(true);
await system.dispose();
});
it("records failed command dispatches as metric failures", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await expect(
system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
threadId: ThreadId.makeUnsafe("thread-missing-project"),
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
),
).rejects.toThrow("does not exist");
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
commandType: "thread.create",
aggregateKind: "thread",
outcome: "failure",
}),
).toBe(true);
await system.dispose();
});
it("stores completed checkpoint summaries even when no files changed", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -417,6 +619,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -512,6 +715,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -653,6 +857,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -5,9 +5,28 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
import {
Cause,
Deferred,
Duration,
Effect,
Exit,
Layer,
Metric,
Option,
PubSub,
Queue,
Schema,
Stream,
} from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
metricAttributes,
orchestrationCommandAckDuration,
orchestrationCommandsTotal,
orchestrationCommandDuration,
} from "../../observability/Metrics.ts";
import { toPersistenceSqlError } from "../../persistence/Errors.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
@@ -19,6 +38,7 @@ import {
import { decideOrchestrationCommand } from "../decider.ts";
import { createEmptyReadModel, projectEvent } from "../projector.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -27,6 +47,7 @@ import {
interface CommandEnvelope {
command: OrchestrationCommand;
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
startedAtMs: number;
}
function commandToAggregateRef(command: OrchestrationCommand): {
@@ -54,6 +75,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let readModel = createEmptyReadModel(new Date().toISOString());
@@ -62,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
const dispatchStartSequence = readModel.snapshotSequence;
const processingStartedAtMs = Date.now();
const aggregateRef = commandToAggregateRef(envelope.command);
const baseMetricAttributes = {
commandType: envelope.command.type,
aggregateKind: aggregateRef.aggregateKind,
} as const;
const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
const persistedEvents = yield* Stream.runCollect(
eventStore.readFromSequence(dispatchStartSequence),
@@ -81,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () {
}
});
return Effect.gen(function* () {
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
yield* Deferred.succeed(envelope.result, {
sequence: existingReceipt.value.resultSequence,
});
return;
}
yield* Deferred.fail(
envelope.result,
new OrchestrationCommandPreviouslyRejectedError({
return Effect.exit(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"orchestration.command_id": envelope.command.commandId,
"orchestration.command_type": envelope.command.type,
"orchestration.aggregate_kind": aggregateRef.aggregateKind,
"orchestration.aggregate_id": aggregateRef.aggregateId,
});
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
return {
sequence: existingReceipt.value.resultSequence,
};
}
return yield* new OrchestrationCommandPreviouslyRejectedError({
commandId: envelope.command.commandId,
detail: existingReceipt.value.error ?? "Previously rejected.",
}),
);
return;
}
});
}
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
),
);
readModel = committedCommand.nextReadModel;
for (const event of committedCommand.committedEvents) {
yield* PubSub.publish(eventPubSub, event);
}
yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
}).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
const aggregateRef = commandToAggregateRef(envelope.command);
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
readModel = committedCommand.nextReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandAckDuration,
metricAttributes({
...baseMetricAttributes,
ackEventType: event.type,
}),
),
Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)),
);
}
}
return { sequence: committedCommand.lastSequence };
}).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
).pipe(
Effect.flatMap((exit) =>
Effect.gen(function* () {
const outcome = Exit.isSuccess(exit)
? "success"
: Cause.hasInterruptsOnly(exit.cause)
? "interrupt"
: "failure";
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandDuration,
metricAttributes(baseMetricAttributes),
),
Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandsTotal,
metricAttributes({
...baseMetricAttributes,
outcome,
}),
),
1,
);
if (Exit.isSuccess(exit)) {
yield* Deferred.succeed(envelope.result, exit.value);
return;
}
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
}
yield* Deferred.fail(envelope.result, error);
}),
),
@@ -195,13 +270,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
};
yield* projectionPipeline.bootstrap;
// bootstrap in-memory read model from event store
yield* Stream.runForEach(eventStore.readAll(), (event) =>
Effect.gen(function* () {
readModel = yield* projectEvent(readModel, event);
}),
);
readModel = yield* projectionSnapshotQuery.getSnapshot();
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
@@ -218,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result });
yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() });
return yield* Deferred.await(result);
});
@@ -25,6 +25,7 @@ import {
ORCHESTRATION_PROJECTOR_NAMES,
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1841,6 +1842,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -623,24 +623,28 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
messageId: event.payload.messageId,
});
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
: existingMessage && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: previousMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
@@ -649,7 +653,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
@@ -338,4 +338,290 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-active',
'Active Project',
'/tmp/workspace',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-03-01T00:00:00.000Z',
'2026-03-01T00:00:01.000Z',
NULL
),
(
'project-deleted',
'Deleted Project',
'/tmp/deleted',
NULL,
'[]',
'2026-03-01T00:00:02.000Z',
'2026-03-01T00:00:03.000Z',
'2026-03-01T00:00:04.000Z'
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-first',
'project-active',
'First Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:05.000Z',
'2026-03-01T00:00:06.000Z',
NULL,
NULL
),
(
'thread-second',
'project-active',
'Second Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:07.000Z',
'2026-03-01T00:00:08.000Z',
NULL,
NULL
),
(
'thread-deleted',
'project-active',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:09.000Z',
'2026-03-01T00:00:10.000Z',
NULL,
'2026-03-01T00:00:11.000Z'
)
`;
const counts = yield* snapshotQuery.getCounts();
assert.deepEqual(counts, {
projectCount: 2,
threadCount: 3,
});
const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace");
assert.equal(project._tag, "Some");
if (project._tag === "Some") {
assert.equal(project.value.id, asProjectId("project-active"));
}
const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing");
assert.equal(missingProject._tag, "None");
const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId(
asProjectId("project-active"),
);
assert.equal(firstThreadId._tag, "Some");
if (firstThreadId._tag === "Some") {
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
}
}),
);
it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-context',
'Context Project',
'/tmp/context-workspace',
NULL,
'[]',
'2026-03-02T00:00:00.000Z',
'2026-03-02T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-context',
'project-context',
'Context Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
'feature/perf',
'/tmp/context-worktree',
NULL,
'2026-03-02T00:00:02.000Z',
'2026-03-02T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-context',
'turn-1',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
1,
'checkpoint-a',
'ready',
'[]'
),
(
'thread-context',
'turn-2',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
2,
'checkpoint-b',
'ready',
'[]'
)
`;
const context = yield* snapshotQuery.getThreadCheckpointContext(
ThreadId.makeUnsafe("thread-context"),
);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
threadId: ThreadId.makeUnsafe("thread-context"),
projectId: asProjectId("project-context"),
workspaceRoot: "/tmp/context-workspace",
worktreePath: "/tmp/context-worktree",
checkpoints: [
{
turnId: asTurnId("turn-1"),
checkpointTurnCount: 1,
checkpointRef: asCheckpointRef("checkpoint-a"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:04.000Z",
},
{
turnId: asTurnId("turn-2"),
checkpointTurnCount: 2,
checkpointRef: asCheckpointRef("checkpoint-b"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:05.000Z",
},
],
});
}
}),
);
});
@@ -7,7 +7,6 @@ import {
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -18,8 +17,10 @@ import {
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
@@ -40,6 +41,8 @@ import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.t
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
ProjectionSnapshotQuery,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
@@ -86,6 +89,29 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
threadCount: Schema.Number,
});
const WorkspaceRootLookupInput = Schema.Struct({
workspaceRoot: Schema.String,
});
const ProjectIdLookupInput = Schema.Struct({
projectId: ProjectId,
});
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
});
const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
});
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -319,6 +345,94 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const readProjectionCounts = SqlSchema.findOne({
Request: Schema.Void,
Result: ProjectionCountsRowSchema,
execute: () =>
sql`
SELECT
(SELECT COUNT(*) FROM projection_projects) AS "projectCount",
(SELECT COUNT(*) FROM projection_threads) AS "threadCount"
`,
});
const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({
Request: WorkspaceRootLookupInput,
Result: ProjectionProjectLookupRowSchema,
execute: ({ workspaceRoot }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
FROM projection_projects
WHERE workspace_root = ${workspaceRoot}
AND deleted_at IS NULL
ORDER BY created_at ASC, project_id ASC
LIMIT 1
`,
});
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
Request: ProjectIdLookupInput,
Result: ProjectionThreadIdLookupRowSchema,
execute: ({ projectId }) =>
sql`
SELECT
thread_id AS "threadId"
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
});
const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadCheckpointContextThreadRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
threads.thread_id AS "threadId",
threads.project_id AS "projectId",
projects.workspace_root AS "workspaceRoot",
threads.worktree_path AS "worktreePath"
FROM projection_threads AS threads
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
LIMIT 1
`,
});
const listCheckpointRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionCheckpointDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
checkpoint_turn_count AS "checkpointTurnCount",
checkpoint_ref AS "checkpointRef",
checkpoint_status AS "status",
checkpoint_files_json AS "files",
assistant_message_id AS "assistantMessageId",
completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
AND checkpoint_turn_count IS NOT NULL
ORDER BY checkpoint_turn_count ASC
`,
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql
.withTransaction(
@@ -593,8 +707,109 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
readProjectionCounts(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCounts:query",
"ProjectionSnapshotQuery.getCounts:decodeRow",
),
),
Effect.map(
(row): ProjectionSnapshotCounts => ({
projectCount: row.projectCount,
threadCount: row.threadCount,
}),
),
);
const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] =
(workspaceRoot) =>
getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query",
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",
),
),
Effect.map(
Option.map(
(row): OrchestrationProject => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
),
),
);
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
(projectId) =>
getFirstActiveThreadIdByProject({ projectId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query",
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow",
),
),
Effect.map(Option.map((row) => row.threadId)),
);
const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = (
threadId,
) =>
Effect.gen(function* () {
const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow",
),
),
);
if (Option.isNone(threadRow)) {
return Option.none<ProjectionThreadCheckpointContext>();
}
const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows",
),
),
);
return Option.some({
threadId: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceRoot: threadRow.value.workspaceRoot,
worktreePath: threadRow.value.worktreePath,
checkpoints: checkpointRows.map(
(row): OrchestrationCheckpointSummary => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
checkpointRef: row.checkpointRef,
status: row.status,
files: row.files,
assistantMessageId: row.assistantMessageId,
completedAt: row.completedAt,
}),
),
});
});
return {
getSnapshot,
getCounts,
getActiveProjectByWorkspaceRoot,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -30,6 +30,7 @@ import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -211,6 +212,7 @@ describe("ProviderCommandReactor", () => {
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -16,6 +16,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
@@ -212,12 +213,12 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
const ensureSessionForThread = Effect.fnUntraced(function* (
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
threadId: ThreadId,
createdAt: string,
options?: {
@@ -357,7 +358,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fnUntraced(function* (input: {
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -409,7 +410,9 @@ const make = Effect.gen(function* () {
});
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
"maybeGenerateAndRenameWorktreeBranchForFirstTurn",
)(function* (input: {
readonly threadId: ThreadId;
readonly branch: string | null;
readonly worktreePath: string | null;
@@ -461,50 +464,52 @@ const make = Effect.gen(function* () {
);
});
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")(
function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
});
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const processTurnStartRequested = Effect.fnUntraced(function* (
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
},
);
const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
) {
const key = turnStartKeyForEvent(event);
@@ -583,7 +588,7 @@ const make = Effect.gen(function* () {
);
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -606,7 +611,7 @@ const make = Effect.gen(function* () {
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
});
const processApprovalResponseRequested = Effect.fnUntraced(function* (
const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -653,50 +658,52 @@ const make = Effect.gen(function* () {
);
});
const processUserInputResponseRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")(
function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
});
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
},
);
const processSessionStopRequested = Effect.fnUntraced(function* (
const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -724,39 +731,48 @@ const make = Effect.gen(function* () {
});
});
const processDomainEvent = (event: ProviderIntentEvent) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
) {
yield* Effect.annotateCurrentSpan({
"orchestration.event_type": event.type,
"orchestration.thread_id": event.payload.threadId,
...(event.commandId ? { "orchestration.command_id": event.commandId } : {}),
});
yield* increment(orchestrationEventsProcessedTotal, {
eventType: event.type,
});
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
return;
}
});
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
}
});
const processDomainEventSafely = (event: ProviderIntentEvent) =>
processDomainEvent(event).pipe(
@@ -31,6 +31,7 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
@@ -197,6 +198,7 @@ describe("ProviderRuntimeIngestion", () => {
fs.mkdirSync(path.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -524,7 +524,7 @@ const make = Effect.fn("make")(function* () {
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
});
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
@@ -796,9 +796,9 @@ const make = Effect.fn("make")(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForPendingTurnStart",
)(function* (threadId: ThreadId) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
@@ -818,16 +818,17 @@ const make = Effect.fn("make")(function* () {
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")(
function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
},
);
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForAcceptedTurnStart",
)(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {
if (eventTurnId === undefined) {
return null;
}
@@ -840,34 +841,36 @@ const make = Effect.fn("make")(function* () {
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")(
function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
},
);
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
@@ -6,12 +6,32 @@
*
* @module ProjectionSnapshotQuery
*/
import type { OrchestrationReadModel } from "@t3tools/contracts";
import type {
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationReadModel,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
export interface ProjectionSnapshotCounts {
readonly projectCount: number;
readonly threadCount: number;
}
export interface ProjectionThreadCheckpointContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -23,6 +43,32 @@ export interface ProjectionSnapshotQueryShape {
* projector cursor state.
*/
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
/**
* Read aggregate projection counts without hydrating the full read model.
*/
readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;
/**
* Read the active project for an exact workspace root match.
*/
readonly getActiveProjectByWorkspaceRoot: (
workspaceRoot: string,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read the earliest active thread for a project.
*/
readonly getFirstActiveThreadIdByProjectId: (
projectId: ProjectId,
) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;
/**
* Read the checkpoint context needed to resolve a single thread diff.
*/
readonly getThreadCheckpointContext: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
}
/**
@@ -55,6 +55,13 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "updated");
assert.deepEqual(rowById.value.attachments, persistedAttachments);
}
}),
);
@@ -1,10 +1,11 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -19,6 +20,22 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
function toProjectionThreadMessage(
row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
): ProjectionThreadMessage {
return {
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
};
}
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -74,6 +91,27 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
},
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ messageId }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE message_id = ${messageId}
LIMIT 1
`,
});
const listProjectionThreadMessageRows = SqlSchema.findAll({
Request: ListProjectionThreadMessagesInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -109,24 +147,20 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadMessageRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) =>
rows.map((row) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
);
const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
@@ -138,6 +172,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
getByMessageId,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
+11 -1
View File
@@ -6,6 +6,7 @@ import { ServerConfig } from "../../config.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
readonly spanAttributes?: Record<string, unknown>;
};
type Loader = {
@@ -41,7 +42,16 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
return Layer.provideMerge(
setup,
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
"db.name": path.basename(dbPath),
"service.name": "t3-server",
},
}),
);
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
@@ -31,6 +31,7 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -61,6 +62,7 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionSnapshotLookupIndexes", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,73 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("019_ProjectionSnapshotLookupIndexes", (it) => {
it.effect("creates indexes for targeted projection lookup filters", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 18 });
yield* runMigrations({ toMigrationInclusive: 19 });
const projectIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_projects)
`;
assert.ok(
projectIndexes.some(
(index) => index.name === "idx_projection_projects_workspace_root_deleted_at",
),
);
const projectIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at')
`;
assert.deepStrictEqual(
projectIndexColumns.map((column) => column.name),
["workspace_root", "deleted_at"],
);
const threadIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_threads)
`;
assert.ok(
threadIndexes.some(
(index) => index.name === "idx_projection_threads_project_deleted_created",
),
);
const threadIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_threads_project_deleted_created')
`;
assert.deepStrictEqual(
threadIndexColumns.map((column) => column.name),
["project_id", "deleted_at", "created_at"],
);
}),
);
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at
ON projection_projects(workspace_root, deleted_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created
ON projection_threads(project_id, deleted_at, created_at)
`;
});
+127 -134
View File
@@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => {
return Effect.void;
};
const makeWithDatabase = (
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
yield* checkNodeSqliteCompat();
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
yield* checkNodeSqliteCompat();
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
}),
}),
}),
});
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const runStatement = (
statement: StatementSync,
params: ReadonlyArray<unknown>,
raw: boolean,
) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () =>
Scope.addFinalizer(scope, semaphore.release(1)),
),
connection,
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
connection,
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
});
});
const make = (
options: SqliteClientConfig,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
@@ -8,13 +8,14 @@
*/
import {
ChatAttachment,
OrchestrationMessageRole,
MessageId,
OrchestrationMessageRole,
ThreadId,
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -37,6 +38,11 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
});
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
export const GetProjectionThreadMessageInput = Schema.Struct({
messageId: MessageId,
});
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
threadId: ThreadId,
});
@@ -55,6 +61,13 @@ export interface ProjectionThreadMessageRepositoryShape {
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Read a projected thread message by id.
*/
readonly getByMessageId: (
input: GetProjectionThreadMessageInput,
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* List projected thread messages for a thread.
*
@@ -0,0 +1,166 @@
import { Effect, Layer, Stream } from "effect";
import { describe, expect, it, vi } from "vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
const emptySnapshot = (
scripts: OrchestrationReadModel["projects"][number]["scripts"],
): OrchestrationReadModel =>
({
snapshotSequence: 1,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: "project-1",
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: null,
scripts,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [],
providerSessions: [],
providerStatuses: [],
pendingApprovals: [],
latestTurnByThreadId: {},
}) as unknown as OrchestrationReadModel;
describe("ProjectSetupScriptRunner", () => {
it("returns no-script when no setup script exists", async () => {
const open = vi.fn();
const write = vi.fn();
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () => Effect.succeed(emptySnapshot([])),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectId: "project-1",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({ status: "no-script" });
expect(open).not.toHaveBeenCalled();
expect(write).not.toHaveBeenCalled();
});
it("opens the deterministic setup terminal with worktree env and writes the command", async () => {
const open = vi.fn(() =>
Effect.succeed({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-01-01T00:00:00.000Z",
}),
);
const write = vi.fn(() => Effect.void);
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () =>
Effect.succeed(
emptySnapshot([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectCwd: "/repo/project",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({
status: "started",
scriptId: "setup",
scriptName: "Setup",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
});
expect(open).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
},
});
expect(write).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
data: "bun install\r",
});
});
});
@@ -0,0 +1,75 @@
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
import { Effect, Layer } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import {
type ProjectSetupScriptRunnerShape,
ProjectSetupScriptRunner,
} from "../Services/ProjectSetupScriptRunner.ts";
const makeProjectSetupScriptRunner = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const terminalManager = yield* TerminalManager;
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const project =
(input.projectId
? readModel.projects.find((entry) => entry.id === input.projectId)
: null) ??
(input.projectCwd
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
: null) ??
null;
if (!project) {
return yield* Effect.fail(new Error("Project was not found for setup script execution."));
}
const script = setupProjectScript(project.scripts);
if (!script) {
return {
status: "no-script",
} as const;
}
const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
const cwd = input.worktreePath;
const env = projectScriptRuntimeEnv({
project: { cwd: project.workspaceRoot },
worktreePath: input.worktreePath,
});
yield* terminalManager.open({
threadId: input.threadId,
terminalId,
cwd,
worktreePath: input.worktreePath,
env,
});
yield* terminalManager.write({
threadId: input.threadId,
terminalId,
data: `${script.command}\r`,
});
return {
status: "started",
scriptId: script.id,
scriptName: script.name,
terminalId,
cwd,
} as const;
});
return {
runForThread,
} satisfies ProjectSetupScriptRunnerShape;
});
export const ProjectSetupScriptRunnerLive = Layer.effect(
ProjectSetupScriptRunner,
makeProjectSetupScriptRunner,
);
@@ -0,0 +1,37 @@
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProjectSetupScriptRunnerResultNoScript {
readonly status: "no-script";
}
export interface ProjectSetupScriptRunnerResultStarted {
readonly status: "started";
readonly scriptId: string;
readonly scriptName: string;
readonly terminalId: string;
readonly cwd: string;
}
export type ProjectSetupScriptRunnerResult =
| ProjectSetupScriptRunnerResultNoScript
| ProjectSetupScriptRunnerResultStarted;
export interface ProjectSetupScriptRunnerInput {
readonly threadId: string;
readonly projectId?: string;
readonly projectCwd?: string;
readonly worktreePath: string;
readonly preferredTerminalId?: string;
}
export interface ProjectSetupScriptRunnerShape {
readonly runForThread: (
input: ProjectSetupScriptRunnerInput,
) => Effect.Effect<ProjectSetupScriptRunnerResult, Error>;
}
export class ProjectSetupScriptRunner extends ServiceMap.Service<
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerShape
>()("t3/project/ProjectSetupScriptRunner") {}
@@ -40,18 +40,19 @@ export const ProviderRegistryLive = Layer.effect(
yield* loadProviders(codexProvider, claudeProvider),
);
const syncProviders = (options?: { readonly publish?: boolean }) =>
Effect.gen(function* () {
const previousProviders = yield* Ref.get(providersRef);
const providers = yield* loadProviders(codexProvider, claudeProvider);
yield* Ref.set(providersRef, providers);
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
readonly publish?: boolean;
}) {
const previousProviders = yield* Ref.get(providersRef);
const providers = yield* loadProviders(codexProvider, claudeProvider);
yield* Ref.set(providersRef, providers);
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
return providers;
});
return providers;
});
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
Effect.forkScoped,
@@ -60,28 +61,30 @@ export const ProviderRegistryLive = Layer.effect(
Effect.forkScoped,
);
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
switch (provider) {
case "codex":
yield* codexProvider.refresh;
break;
case "claudeAgent":
yield* claudeProvider.refresh;
break;
default:
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
concurrency: "unbounded",
});
break;
}
return yield* syncProviders();
});
return {
getProviders: syncProviders({ publish: false }).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
refresh: (provider?: ProviderKind) =>
Effect.gen(function* () {
switch (provider) {
case "codex":
yield* codexProvider.refresh;
break;
case "claudeAgent":
yield* claudeProvider.refresh;
break;
default:
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
concurrency: "unbounded",
});
break;
}
return yield* syncProviders();
}).pipe(
refresh(provider).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
@@ -20,7 +20,7 @@ import {
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -230,6 +230,17 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
@@ -1060,6 +1071,120 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
);
}),
);
it.effect("records provider metrics with the routed provider label", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-metrics"), {
provider: "claudeAgent",
threadId: asThreadId("thread-metrics"),
cwd: "/tmp/project",
runtimeMode: "full-access",
});
yield* provider.interruptTurn({ threadId: session.threadId });
yield* provider.respondToRequest({
threadId: session.threadId,
requestId: asRequestId("req-metrics-1"),
decision: "accept",
});
yield* provider.respondToUserInput({
threadId: session.threadId,
requestId: asRequestId("req-metrics-2"),
answers: {
sandbox_mode: "workspace-write",
},
});
yield* provider.rollbackConversation({
threadId: session.threadId,
numTurns: 1,
});
yield* provider.stopSession({ threadId: session.threadId });
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "interrupt",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "approval-response",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "user-input-response",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "rollback",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_sessions_total", {
provider: "claudeAgent",
operation: "stop",
outcome: "success",
}),
true,
);
}),
);
it.effect(
"records sendTurn metrics with the resolved provider when modelSelection is omitted",
() =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-send-metrics"), {
provider: "claudeAgent",
threadId: asThreadId("thread-send-metrics"),
cwd: "/tmp/project-send-metrics",
runtimeMode: "full-access",
});
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "send",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turn_duration", {
provider: "claudeAgent",
operation: "send",
}),
true,
);
}),
);
});
const validation = makeProviderServiceLayer();
+523 -363
View File
@@ -24,6 +24,16 @@ import {
} from "@t3tools/contracts";
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
import {
increment,
providerMetricAttributes,
providerRuntimeEventsTotal,
providerSessionsTotal,
providerTurnDuration,
providerTurnsTotal,
providerTurnMetricAttributes,
withMetrics,
} from "../../observability/Metrics.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
@@ -131,169 +141,190 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
);
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
) =>
directory.upsert({
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
});
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
increment(providerRuntimeEventsTotal, {
provider: event.provider,
eventType: event.type,
}).pipe(Effect.andThen(publishRuntimeEvent(event)));
const worker = Effect.forever(
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
);
yield* Effect.forkScoped(worker);
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) {
yield* Effect.annotateCurrentSpan({
"provider.operation": "recover-session",
"provider.kind": input.binding.provider,
"provider.thread_id": input.binding.threadId,
});
return yield* Effect.gen(function* () {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
}).pipe(
withMetrics({
counter: providerSessionsTotal,
attributes: providerMetricAttributes(input.binding.provider, {
operation: "recover",
}),
}),
);
});
const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
readonly threadId: ThreadId;
readonly operation: string;
readonly allowRecovery: boolean;
}) {
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* toValidationError(
input.operation,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const adapter = yield* registry.getByProvider(binding.provider);
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
) =>
directory.upsert({
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
return { adapter, threadId: input.threadId, isActive: true } as const;
}
if (!input.allowRecovery) {
return { adapter, threadId: input.threadId, isActive: false } as const;
}
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.startSession",
schema: ProviderSessionStartInput,
payload: rawInput,
});
const input = {
...parsed,
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
provider: parsed.provider ?? "codex",
};
yield* Effect.annotateCurrentSpan({
"provider.operation": "start-session",
"provider.kind": input.provider,
"provider.thread_id": threadId,
"provider.runtime_mode": input.runtimeMode,
});
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) =>
registry.getByProvider(provider),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
const worker = Effect.forever(
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
);
yield* Effect.forkScoped(worker);
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) =>
Effect.gen(function* () {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
});
const resolveRoutableSession = (input: {
readonly threadId: ThreadId;
readonly operation: string;
readonly allowRecovery: boolean;
}) =>
Effect.gen(function* () {
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* toValidationError(
input.operation,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const adapter = yield* registry.getByProvider(binding.provider);
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
return { adapter, threadId: input.threadId, isActive: true } as const;
}
if (!input.allowRecovery) {
return { adapter, threadId: input.threadId, isActive: false } as const;
}
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
Effect.gen(function* () {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.startSession",
schema: ProviderSessionStartInput,
payload: rawInput,
});
const input = {
...parsed,
threadId,
provider: parsed.provider ?? "codex",
};
return yield* Effect.gen(function* () {
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
@@ -342,118 +373,220 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
});
return session;
}).pipe(
withMetrics({
counter: providerSessionsTotal,
attributes: providerMetricAttributes(input.provider, {
operation: "start",
}),
}),
);
},
);
const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
"provider.interaction_mode": input.interactionMode,
"provider.attachment_count": input.attachments.length,
});
let metricProvider = "unknown";
let metricModel = input.modelSelection?.model;
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) =>
Effect.gen(function* () {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
metricProvider = routed.adapter.provider;
metricModel = input.modelSelection?.model;
yield* Effect.annotateCurrentSpan({
"provider.kind": routed.adapter.provider,
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
}).pipe(
withMetrics({
counter: providerTurnsTotal,
timer: providerTurnDuration,
attributes: () =>
providerTurnMetricAttributes({
provider: metricProvider,
model: metricModel,
extra: {
operation: "send",
},
}),
}),
);
});
const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.interruptTurn",
schema: ProviderInterruptTurnInput,
payload: rawInput,
});
const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.interruptTurn",
schema: ProviderInterruptTurnInput,
payload: rawInput,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "interrupt-turn",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.turn_id": input.turnId,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "interrupt",
}),
}),
);
},
);
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-request",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "approval-response",
}),
}),
);
},
);
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToUserInput",
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
"respondToUserInput",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToUserInput",
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-user-input",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "user-input-response",
}),
}),
);
});
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopSession",
schema: ProviderStopSessionInput,
payload: rawInput,
});
const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopSession",
schema: ProviderStopSessionInput,
payload: rawInput,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "stop-session",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
@@ -461,142 +594,169 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
});
}).pipe(
withMetrics({
counter: providerSessionsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "stop",
}),
}),
);
},
);
const listSessions: ProviderServiceShape["listSessions"] = () =>
Effect.gen(function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory.listThreadIds().pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory
.getBinding(threadId)
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
{ concurrency: "unbounded" },
),
const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory.listThreadIds().pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory
.getBinding(threadId)
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
{ concurrency: "unbounded" },
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
for (const bindingOption of persistedBindings) {
const binding = Option.getOrUndefined(bindingOption);
if (binding) {
bindingsByThreadId.set(binding.threadId, binding);
}
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
for (const bindingOption of persistedBindings) {
const binding = Option.getOrUndefined(bindingOption);
if (binding) {
bindingsByThreadId.set(binding.threadId, binding);
}
}
return activeSessions.map((session) => {
const binding = bindingsByThreadId.get(session.threadId);
if (!binding) {
return session;
}
return activeSessions.map((session) => {
const binding = bindingsByThreadId.get(session.threadId);
if (!binding) {
return session;
}
const overrides: {
resumeCursor?: ProviderSession["resumeCursor"];
runtimeMode?: ProviderSession["runtimeMode"];
} = {};
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
overrides.resumeCursor = binding.resumeCursor;
}
if (binding.runtimeMode !== undefined) {
overrides.runtimeMode = binding.runtimeMode;
}
return Object.assign({}, session, overrides);
});
});
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.rollbackConversation",
schema: ProviderRollbackConversationInput,
payload: rawInput,
});
if (input.numTurns === 0) {
return;
const overrides: {
resumeCursor?: ProviderSession["resumeCursor"];
runtimeMode?: ProviderSession["runtimeMode"];
} = {};
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
overrides.resumeCursor = binding.resumeCursor;
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
if (binding.runtimeMode !== undefined) {
overrides.runtimeMode = binding.runtimeMode;
}
return Object.assign({}, session, overrides);
});
},
);
const runStopAll = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
);
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
"rollbackConversation",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.rollbackConversation",
schema: ProviderRollbackConversationInput,
payload: rawInput,
});
if (input.numTurns === 0) {
return;
}
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "rollback-conversation",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.rollback_turns": input.numTurns,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "rollback",
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
threadId,
provider,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
}),
),
),
).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
}),
);
return {
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderServiceShape["streamEvents"] {
return Stream.fromPubSub(runtimeEventPubSub);
},
} satisfies ProviderServiceShape;
});
const runStopAll = Effect.fn("runStopAll")(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
threadId,
provider,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
}),
),
),
).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
);
return {
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderServiceShape["streamEvents"] {
return Stream.fromPubSub(runtimeEventPubSub);
},
} satisfies ProviderServiceShape;
});
export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
+495 -2
View File
@@ -6,8 +6,10 @@ import {
DEFAULT_SERVER_SETTINGS,
GitCommandError,
KeybindingRule,
MessageId,
OpenError,
TerminalNotRunningError,
type OrchestrationCommand,
type OrchestrationEvent,
ORCHESTRATION_WS_METHODS,
ProjectId,
@@ -22,6 +24,7 @@ import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Path, Stream } from "effect";
import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import { vi } from "vitest";
import type { ServerConfigShape } from "./config.ts";
import { deriveServerPaths, ServerConfig } from "./config.ts";
@@ -39,6 +42,7 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import {
ProjectionSnapshotQuery,
type ProjectionSnapshotQueryShape,
@@ -53,6 +57,10 @@ import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRu
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
import {
ProjectSetupScriptRunner,
type ProjectSetupScriptRunnerShape,
} from "./project/Services/ProjectSetupScriptRunner.ts";
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
@@ -125,6 +133,7 @@ const buildAppUnderTest = (options?: {
open?: Partial<OpenShape>;
gitCore?: Partial<GitCoreShape>;
gitManager?: Partial<GitManagerShape>;
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
terminalManager?: Partial<TerminalManagerShape>;
orchestrationEngine?: Partial<OrchestrationEngineShape>;
projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>;
@@ -139,8 +148,17 @@ const buildAppUnderTest = (options?: {
const baseDir = options?.config?.baseDir ?? tempBaseDir;
const devUrl = options?.config?.devUrl;
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
const config = {
const config: ServerConfigShape = {
logLevel: "Info",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: 0,
host: "127.0.0.1",
@@ -154,7 +172,7 @@ const buildAppUnderTest = (options?: {
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
...options?.config,
} satisfies ServerConfigShape;
};
const layerConfig = Layer.succeed(ServerConfig, config);
const appLayer = HttpRouter.serve(makeRoutesLayer, {
@@ -200,6 +218,12 @@ const buildAppUnderTest = (options?: {
...options?.layers?.gitManager,
}),
),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
runForThread: () => Effect.succeed({ status: "no-script" as const }),
...options?.layers?.projectSetupScriptRunner,
}),
),
Layer.provide(
Layer.mock(TerminalManager)({
...options?.layers?.terminalManager,
@@ -533,6 +557,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
} as const;
yield* buildAppUnderTest({
config: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
layers: {
keybindings: {
loadConfigState: Effect.succeed({
@@ -561,6 +589,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.deepEqual(first.config.keybindings, []);
assert.deepEqual(first.config.issues, []);
assert.deepEqual(first.config.providers, providers);
assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true);
assert.equal(first.config.observability.localTracingEnabled, true);
assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces");
assert.equal(first.config.observability.otlpTracesEnabled, true);
assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics");
assert.equal(first.config.observability.otlpMetricsEnabled, true);
assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS);
}
assert.deepEqual(second, {
@@ -822,6 +856,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
gitManager: {
status: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
@@ -842,6 +879,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
push: { status: "skipped_not_requested" as const },
pr: { status: "skipped_not_requested" as const },
toast: {
title: "Committed abc123",
description: "feat: demo",
cta: {
kind: "run_action" as const,
label: "Push",
action: {
kind: "push" as const,
},
},
},
};
yield* (
@@ -911,6 +959,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
],
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
}),
createWorktree: () =>
Effect.succeed({
@@ -1177,6 +1227,448 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("closes thread terminals after a successful archive command", () =>
Effect.gen(function* () {
const threadId = ThreadId.makeUnsafe("thread-archive");
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
closeInputs.push(input);
}),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 8 }),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 8);
assert.deepEqual(closeInputs, [{ threadId }]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"bootstraps first-send worktree turns on the server before dispatching turn start",
() =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
Effect.succeed({
status: "started" as const,
scriptId: "setup",
scriptName: "Setup",
terminalId: "setup-setup",
cwd: "/tmp/bootstrap-worktree",
}),
);
yield* buildAppUnderTest({
layers: {
gitCore: {
createWorktree,
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
projectSetupScriptRunner: {
runForThread,
},
},
});
const createdAt = new Date().toISOString();
const wsUrl = yield* getWsServerUrl("/ws");
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start"),
threadId: ThreadId.makeUnsafe("thread-bootstrap"),
message: {
messageId: MessageId.makeUnsafe("msg-bootstrap"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
},
runSetupScript: true,
},
createdAt,
}),
),
);
assert.equal(response.sequence, 5);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
[
"thread.create",
"thread.meta.update",
"thread.activity.append",
"thread.activity.append",
"thread.turn.start",
],
);
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
cwd: "/tmp/project",
branch: "main",
newBranch: "t3code/bootstrap-branch",
path: null,
});
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
threadId: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: defaultProjectId,
projectCwd: "/tmp/project",
worktreePath: "/tmp/bootstrap-worktree",
});
const setupActivities = dispatchedCommands.filter(
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
command.type === "thread.activity.append",
);
assert.deepEqual(
setupActivities.map((command) => command.activity.kind),
["setup-script.requested", "setup-script.started"],
);
const finalCommand = dispatchedCommands[4];
assertTrue(finalCommand?.type === "thread.turn.start");
if (finalCommand?.type === "thread.turn.start") {
assert.equal(finalCommand.bootstrap, undefined);
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
Effect.fail(new Error("pty unavailable")),
);
yield* buildAppUnderTest({
layers: {
gitCore: {
createWorktree,
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
projectSetupScriptRunner: {
runForThread,
},
},
});
const createdAt = new Date().toISOString();
const wsUrl = yield* getWsServerUrl("/ws");
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-failure"),
threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-failure"),
message: {
messageId: MessageId.makeUnsafe("msg-bootstrap-setup-failure"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
},
runSetupScript: true,
},
createdAt,
}),
),
);
assert.equal(response.sequence, 4);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
);
const setupFailureActivity = dispatchedCommands.find(
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
command.type === "thread.activity.append",
);
assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed");
assert.deepEqual(setupFailureActivity?.activity.payload, {
detail: "pty unavailable",
worktreePath: "/tmp/bootstrap-worktree",
});
assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete"));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
Effect.succeed({
status: "started" as const,
scriptId: "setup",
scriptName: "Setup",
terminalId: "setup-setup",
cwd: "/tmp/bootstrap-worktree",
}),
);
let setupActivityAppendAttempt = 0;
yield* buildAppUnderTest({
layers: {
gitCore: {
createWorktree,
},
orchestrationEngine: {
dispatch: (command) => {
if (
command.type === "thread.activity.append" &&
command.activity.kind.startsWith("setup-script.")
) {
setupActivityAppendAttempt += 1;
if (setupActivityAppendAttempt === 2) {
return Effect.fail(
new OrchestrationListenerCallbackError({
listener: "domain-event",
detail: "failed to append setup-script.started activity",
}),
);
}
}
return Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
});
},
readEvents: () => Stream.empty,
},
projectSetupScriptRunner: {
runForThread,
},
},
});
const createdAt = new Date().toISOString();
const wsUrl = yield* getWsServerUrl("/ws");
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-activity-failure"),
threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-activity-failure"),
message: {
messageId: MessageId.makeUnsafe("msg-bootstrap-setup-activity-failure"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
},
runSetupScript: true,
},
createdAt,
}),
),
);
assert.equal(response.sequence, 4);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
);
const setupActivities = dispatchedCommands.filter(
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
command.type === "thread.activity.append",
);
assert.deepEqual(
setupActivities.map((command) => command.activity.kind),
["setup-script.requested"],
);
assertTrue(
setupActivities.every((command) => command.activity.kind !== "setup-script.failed"),
);
assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete"));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.die(new Error("worktree exploded")),
);
yield* buildAppUnderTest({
layers: {
gitCore: {
createWorktree,
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
},
});
const createdAt = new Date().toISOString();
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-defect"),
threadId: ThreadId.makeUnsafe("thread-bootstrap-defect"),
message: {
messageId: MessageId.makeUnsafe("msg-bootstrap-defect"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
},
runSetupScript: false,
},
createdAt,
}),
).pipe(Effect.result),
);
assertTrue(result._tag === "Failure");
assertTrue(result.failure._tag === "OrchestrationDispatchCommandError");
assert.include(result.failure.message, "worktree exploded");
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.create", "thread.delete"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
() =>
@@ -1272,6 +1764,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
threadId: "thread-1",
terminalId: "default",
cwd: "/tmp/project",
worktreePath: null,
status: "running" as const,
pid: 1234,
history: "",
+28 -13
View File
@@ -29,7 +29,6 @@ import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { GitManagerLive } from "./git/Layers/GitManager";
import { KeybindingsLive } from "./keybindings";
import { ServerLoggerLive } from "./serverLogger";
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup";
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor";
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
@@ -42,6 +41,8 @@ import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResol
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";
import { ObservabilityLive } from "./observability/Layers/Observability";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -99,12 +100,24 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const OrchestrationLayerLive = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(OrchestrationEngineLive),
Layer.provideMerge(OrchestrationProjectionPipelineLive),
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
OrchestrationCommandReceiptRepositoryLive,
);
const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(
Layer.provide(OrchestrationEventStoreLive),
);
const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),
);
const CheckpointingLayerLive = Layer.empty.pipe(
@@ -146,6 +159,7 @@ const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersisten
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(
GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
@@ -165,15 +179,12 @@ const WorkspaceLayerLive = Layer.mergeAll(
),
);
const RuntimeServicesLive = Layer.empty.pipe(
Layer.provideMerge(ServerRuntimeStartupLive),
Layer.provideMerge(ReactorLayerLive),
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
@@ -188,6 +199,10 @@ const RuntimeServicesLive = Layer.empty.pipe(
Layer.provideMerge(ServerLifecycleEventsLive),
);
const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
Layer.provideMerge(RuntimeDependenciesLive),
);
export const makeRoutesLayer = Layer.mergeAll(
attachmentsRouteLayer,
projectFaviconRouteLayer,
@@ -219,7 +234,7 @@ export const makeServerLayer = Layer.unwrap(
return serverApplicationLayer.pipe(
Layer.provideMerge(RuntimeServicesLive),
Layer.provideMerge(HttpServerLive),
Layer.provide(ServerLoggerLive),
Layer.provide(ObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(PlatformServicesLive),
);
+1 -4
View File
@@ -4,11 +4,8 @@ import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const config = yield* ServerConfig;
const { serverLogPath } = config;
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel);
const loggerLayer = Logger.layer([Logger.consolePretty(), fileLogger], {
const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], {
mergeWithExisting: false,
});
+37 -4
View File
@@ -1,8 +1,13 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Fiber, Ref } from "effect";
import { TestClock } from "effect/testing";
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
import { makeCommandGate, ServerRuntimeStartupError } from "./serverRuntimeStartup.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import {
launchStartupHeartbeat,
makeCommandGate,
ServerRuntimeStartupError,
} from "./serverRuntimeStartup.ts";
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
Effect.scoped(
@@ -14,7 +19,7 @@ it.effect("enqueueCommand waits for readiness and then drains queued work", () =
.enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1))
.pipe(Effect.forkScoped);
yield* TestClock.adjust("50 millis");
yield* Effect.yieldNow;
assert.equal(yield* Ref.get(executionCount), 0);
yield* commandGate.signalCommandReady;
@@ -47,3 +52,31 @@ it.effect("enqueueCommand fails queued work when readiness fails", () =>
}),
),
);
it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () =>
Effect.scoped(
Effect.gen(function* () {
const releaseCounts = yield* Deferred.make<void, never>();
yield* launchStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
Effect.as({
projectCount: 2,
threadCount: 3,
}),
),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
Effect.provideService(AnalyticsService, {
record: () => Effect.void,
flush: Effect.void,
}),
);
}),
),
);
+96 -51
View File
@@ -5,7 +5,19 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Data, Deferred, Effect, Exit, Layer, Path, Queue, Ref, Scope, ServiceMap } from "effect";
import {
Data,
Deferred,
Effect,
Exit,
Layer,
Option,
Path,
Queue,
Ref,
Scope,
ServiceMap,
} from "effect";
import { ServerConfig } from "./config";
import { Keybindings } from "./keybindings";
@@ -105,17 +117,15 @@ export const makeCommandGate = Effect.gen(function* () {
} satisfies CommandGate;
});
const recordStartupHeartbeat = Effect.gen(function* () {
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.logWarning("failed to gather startup projection counts for telemetry", {
cause,
}).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
@@ -130,6 +140,14 @@ const recordStartupHeartbeat = Effect.gen(function* () {
});
});
export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
Effect.withSpan("server.startup.heartbeat.record"),
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
Effect.asVoid,
);
const autoBootstrapWelcome = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
@@ -141,14 +159,13 @@ const autoBootstrapWelcome = Effect.gen(function* () {
if (serverConfig.autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null,
const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
serverConfig.cwd,
);
let nextProjectId: ProjectId;
let nextProjectDefaultModelSelection: ModelSelection;
if (!existingProject) {
if (Option.isNone(existingProject)) {
const createdAt = new Date().toISOString();
nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
@@ -166,17 +183,16 @@ const autoBootstrapWelcome = Effect.gen(function* () {
createdAt,
});
} else {
nextProjectId = existingProject.id;
nextProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
nextProjectId = existingProject.value.id;
nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
provider: "codex",
model: "gpt-5-codex",
};
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === nextProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const existingThreadId =
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
if (Option.isNone(existingThreadId)) {
const createdAt = new Date().toISOString();
const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
@@ -196,7 +212,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
bootstrapThreadId = createdThreadId;
} else {
bootstrapProjectId = nextProjectId;
bootstrapThreadId = existingThread.id;
bootstrapThreadId = existingThreadId.value;
}
});
}
@@ -234,7 +250,14 @@ const maybeOpenBrowser = Effect.gen(function* () {
);
});
const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.annotateSpans({ "startup.phase": phase }),
Effect.withSpan(`server.startup.${phase}`),
);
const makeServerRuntimeStartup = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const keybindings = yield* Keybindings;
const orchestrationReactor = yield* OrchestrationReactor;
const lifecycleEvents = yield* ServerLifecycleEvents;
@@ -248,46 +271,65 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
const startup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting keybindings runtime");
yield* keybindings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start keybindings runtime", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
yield* runStartupPhase(
"keybindings.start",
keybindings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start keybindings runtime", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
),
Effect.forkScoped,
),
Effect.forkScoped,
);
yield* Effect.logDebug("startup phase: starting server settings runtime");
yield* serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
detail: error.detail,
cause: error.cause,
}),
yield* runStartupPhase(
"settings.start",
serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
detail: error.detail,
cause: error.cause,
}),
),
Effect.forkScoped,
),
Effect.forkScoped,
);
yield* Effect.logDebug("startup phase: starting orchestration reactors");
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* runStartupPhase(
"reactors.start",
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
);
yield* Effect.logDebug("startup phase: preparing welcome payload");
const welcome = yield* autoBootstrapWelcome;
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
yield* Effect.logDebug("startup phase: publishing welcome event", {
cwd: welcome.cwd,
projectName: welcome.projectName,
bootstrapProjectId: welcome.bootstrapProjectId,
bootstrapThreadId: welcome.bootstrapThreadId,
});
yield* lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: welcome,
});
});
yield* runStartupPhase(
"welcome.publish",
lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: welcome,
}),
);
}).pipe(
Effect.annotateSpans({
"server.mode": serverConfig.mode,
"server.port": serverConfig.port,
"server.host": serverConfig.host ?? "default",
}),
Effect.withSpan("server.startup", { kind: "server", root: true }),
);
yield* Effect.forkScoped(
Effect.gen(function* () {
@@ -305,18 +347,21 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("Accepting commands");
yield* commandGate.signalCommandReady;
yield* Effect.logDebug("startup phase: waiting for http listener");
yield* Deferred.await(httpListening);
yield* runStartupPhase("http.wait", Deferred.await(httpListening));
yield* Effect.logDebug("startup phase: publishing ready event");
yield* lifecycleEvents.publish({
version: 1,
type: "ready",
payload: { at: new Date().toISOString() },
});
yield* runStartupPhase(
"ready.publish",
lifecycleEvents.publish({
version: 1,
type: "ready",
payload: { at: new Date().toISOString() },
}),
);
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* recordStartupHeartbeat;
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
yield* maybeOpenBrowser;
yield* runStartupPhase("browser.open", maybeOpenBrowser);
yield* Effect.logDebug("startup phase: complete");
}),
);
+26
View File
@@ -171,6 +171,24 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims observability settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const next = yield* serverSettings.updateSettings({
observability: {
otlpTracesUrl: " http://localhost:4318/v1/traces ",
otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
},
});
assert.deepEqual(next.observability, {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("defaults blank binary paths to provider executables", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -197,6 +215,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const next = yield* serverSettings.updateSettings({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
@@ -208,6 +230,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
@@ -125,17 +125,19 @@ const makeAnalyticsService = Effect.gen(function* () {
}
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const record: AnalyticsServiceShape["record"] = Effect.fn("record")(
function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
});
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
},
);
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
+123 -7
View File
@@ -189,6 +189,10 @@ function multiTerminalHistoryLogPath(
interface CreateManagerOptions {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
subprocessInspector?: (
terminalPid: number,
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
webPortInspector?: (port: number) => Effect.Effect<boolean>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -225,6 +229,12 @@ const createManager = (
...(options.subprocessChecker !== undefined
? { subprocessChecker: options.subprocessChecker }
: {}),
...(options.subprocessInspector !== undefined
? { subprocessInspector: options.subprocessInspector }
: {}),
...(options.webPortInspector !== undefined
? { webPortInspector: options.webPortInspector }
: {}),
...(options.subprocessPollIntervalMs !== undefined
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
@@ -428,6 +438,85 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
Effect.gen(function* () {
const { manager, getEvents, baseDir } = yield* createManager();
const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
yield* makeDirectory(firstWorktreePath);
yield* makeDirectory(secondWorktreePath);
const startedSnapshot = yield* manager.open(
openInput({
cwd: firstWorktreePath,
worktreePath: firstWorktreePath,
}),
);
const restartedSnapshot = yield* manager.restart(
restartInput({
cwd: secondWorktreePath,
worktreePath: secondWorktreePath,
}),
);
assert.equal(startedSnapshot.worktreePath, firstWorktreePath);
assert.equal(restartedSnapshot.worktreePath, secondWorktreePath);
const events = yield* getEvents;
const startedEvent = events.find(
(event): event is Extract<TerminalEvent, { type: "started" }> => event.type === "started",
);
const restartedEvent = events.find(
(event): event is Extract<TerminalEvent, { type: "restarted" }> =>
event.type === "restarted",
);
assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath);
assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath);
}),
);
it.effect("preserves worktree metadata when reopening an exited session", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
const worktreePath = path.join(baseDir, "worktrees", "feature-a");
yield* makeDirectory(worktreePath);
yield* manager.open(
openInput({
cwd: worktreePath,
worktreePath,
}),
);
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")),
);
const reopenedSnapshot = yield* manager.open(
openInput({
cwd: worktreePath,
worktreePath,
}),
);
assert.equal(reopenedSnapshot.worktreePath, worktreePath);
const events = yield* getEvents;
const reopenedEvent = events
.toReversed()
.find(
(event): event is Extract<TerminalEvent, { type: "started" }> => event.type === "started",
);
assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath);
}),
);
it.effect("emits exited event and reopens with clean transcript after exit", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
@@ -469,29 +558,56 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("emits subprocess activity events when child-process state changes", () =>
it.effect("emits subprocess activity events when child-process state or web ports change", () =>
Effect.gen(function* () {
let hasRunningSubprocess = false;
let activity = {
hasRunningSubprocess: false,
runningPorts: [] as number[],
};
const { manager, getEvents } = yield* createManager(5, {
subprocessChecker: () => Effect.succeed(hasRunningSubprocess),
subprocessInspector: () => Effect.succeed(activity),
webPortInspector: (port) => Effect.succeed(port === 3000),
subprocessPollIntervalMs: 20,
});
yield* manager.open(openInput());
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
hasRunningSubprocess = true;
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.join(",") === "3000",
),
),
"1200 millis",
);
hasRunningSubprocess = false;
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === false &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
+170 -146
View File
@@ -23,7 +23,17 @@ import {
} from "effect";
import { ServerConfig } from "../../config";
import { runProcess } from "../../processRunner";
import {
increment,
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics";
import {
arePortListsEqual,
defaultSubprocessInspector,
normalizeRunningPorts,
} from "../../terminalProcessInspector";
import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "../../webPortInspector";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -52,6 +62,14 @@ const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECT
type TerminalSubprocessChecker = (
terminalPid: number,
) => Effect.Effect<boolean, TerminalSubprocessCheckError>;
type TerminalSubprocessActivity = {
hasRunningSubprocess: boolean;
runningPorts: number[];
};
type TerminalSubprocessInspector = (
terminalPid: number,
) => Effect.Effect<TerminalSubprocessActivity, TerminalSubprocessCheckError>;
type TerminalWebPortInspector = (port: number) => Effect.Effect<boolean>;
class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{
readonly message: string;
@@ -75,6 +93,7 @@ interface TerminalStartInput {
threadId: string;
terminalId: string;
cwd: string;
worktreePath?: string | null;
cols: number;
rows: number;
env?: Record<string, string>;
@@ -84,6 +103,7 @@ interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
@@ -100,6 +120,7 @@ interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -138,6 +159,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
worktreePath: session.worktreePath,
status: session.status,
pid: session.pid,
history: session.history,
@@ -291,108 +313,6 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
);
}
function checkWindowsSubprocessActivity(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
}).pipe(Effect.map((result) => result.code === 0));
}
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
});
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
});
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
if (pgrepResult.value.code === 0) {
return pgrepResult.value.stdout.trim().length > 0;
}
if (pgrepResult.value.code === 1) {
return false;
}
}
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return false;
}
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
return true;
}
}
return false;
});
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (process.platform === "win32") {
return yield* checkWindowsSubprocessActivity(terminalPid);
}
return yield* checkPosixSubprocessActivity(terminalPid);
});
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
@@ -639,6 +559,9 @@ interface TerminalManagerOptions {
ptyAdapter: PtyAdapterShape;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessInspector?: TerminalSubprocessInspector;
webPortInspector?: TerminalWebPortInspector;
webPortProbeCacheTtlMs?: number;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -662,12 +585,39 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const shellResolver = options.shellResolver ?? defaultShellResolver;
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
const subprocessInspector =
options.subprocessInspector ??
(options.subprocessChecker
? (terminalPid: number) =>
Effect.map(options.subprocessChecker!(terminalPid), (hasRunningSubprocess) => ({
hasRunningSubprocess,
runningPorts: [],
}))
: (terminalPid: number) =>
Effect.tryPromise({
try: () => defaultSubprocessInspector(terminalPid),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocess activity",
cause,
terminalPid,
command: process.platform === "win32" ? "powershell" : "ps",
}),
}));
const webPortInspector =
options.webPortInspector ??
((port: number) =>
Effect.tryPromise({
try: () => defaultWebPortInspector(port),
catch: () => false,
}));
const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
const maxRetainedInactiveSessions =
options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
const webPortProbeCache = new Map<number, { isWeb: boolean; checkedAt: number }>();
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
@@ -687,6 +637,44 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
});
const inspectWebPortCached = (port: number) =>
Effect.gen(function* () {
const now = Date.now();
const cached = webPortProbeCache.get(port);
if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) {
return cached.isWeb;
}
const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false)));
webPortProbeCache.set(port, {
isWeb,
checkedAt: Date.now(),
});
return isWeb;
});
const detectWebPorts = (runningPorts: number[]) =>
Effect.gen(function* () {
if (runningPorts.length === 0) {
return [] as number[];
}
const checks = yield* Effect.forEach(
runningPorts,
(port) =>
Effect.map(inspectWebPortCached(port), (isWeb) => ({
port,
isWeb,
})),
{ concurrency: "unbounded" },
);
return checks
.filter((entry) => entry.isWeb)
.map((entry) => entry.port)
.toSorted((left, right) => left - right);
});
const historyPath = (threadId: string, terminalId: string) => {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
@@ -1150,6 +1138,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1217,6 +1206,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1294,15 +1284,23 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
eventType: "started" | "restarted",
) {
yield* stopProcess(session);
yield* Effect.annotateCurrentSpan({
"terminal.thread_id": session.threadId,
"terminal.id": session.terminalId,
"terminal.event_type": eventType,
"terminal.cwd": input.cwd,
});
yield* modifyManagerState((state) => {
session.status = "starting";
session.cwd = input.cwd;
session.worktreePath = input.worktreePath ?? null;
session.cols = input.cols;
session.rows = input.rows;
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1314,45 +1312,49 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
let startedShell: string | null = null;
const startResult = yield* Effect.result(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
Effect.andThen(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
const processPid = ptyProcess.pid;
const unsubscribeData = ptyProcess.onData((data) => {
if (!enqueueProcessEvent(session, processPid, { type: "output", data })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const unsubscribeExit = ptyProcess.onExit((event) => {
if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const processPid = ptyProcess.pid;
const unsubscribeData = ptyProcess.onData((data) => {
if (!enqueueProcessEvent(session, processPid, { type: "output", data })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const unsubscribeExit = ptyProcess.onExit((event) => {
if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: snapshot(session),
});
}),
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: snapshot(session),
});
}),
),
),
);
if (startResult._tag === "Success") {
@@ -1372,6 +1374,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.unsubscribeData = null;
session.unsubscribeExit = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1442,7 +1445,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session: TerminalSessionState & { pid: number },
) {
const terminalPid = session.pid;
const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe(
const activity = yield* subprocessInspector(terminalPid).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to check terminal subprocess activity", {
@@ -1450,14 +1453,21 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
terminalId: session.terminalId,
terminalPid,
error: error instanceof Error ? error.message : String(error),
}).pipe(Effect.as(Option.none<boolean>())),
}).pipe(Effect.as(Option.none<TerminalSubprocessActivity>())),
),
);
if (Option.isNone(hasRunningSubprocess)) {
if (Option.isNone(activity)) {
return;
}
const hasRunningSubprocess = activity.value.hasRunningSubprocess === true;
const runningPorts = hasRunningSubprocess
? normalizeRunningPorts(
yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)),
)
: [];
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1466,12 +1476,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
Option.isNone(liveSession) ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value
(liveSession.value.hasRunningSubprocess === hasRunningSubprocess &&
arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts))
) {
return [Option.none(), state] as const;
}
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
liveSession.value.hasRunningSubprocess = hasRunningSubprocess;
liveSession.value.runningSubprocessPorts = runningPorts;
liveSession.value.updatedAt = new Date().toISOString();
return [
@@ -1480,7 +1492,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
createdAt: new Date().toISOString(),
hasRunningSubprocess: hasRunningSubprocess.value,
hasRunningSubprocess,
runningPorts,
}),
state,
] as const;
@@ -1562,6 +1575,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history,
@@ -1578,6 +1592,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
@@ -1595,6 +1610,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
cols,
rows,
...(input.env ? { env: input.env } : {}),
@@ -1614,6 +1630,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
if (liveSession.cwd !== input.cwd || runtimeEnvChanged) {
yield* stopProcess(liveSession);
liveSession.cwd = input.cwd;
liveSession.worktreePath = input.worktreePath ?? null;
liveSession.runtimeEnv = nextRuntimeEnv;
liveSession.history = "";
liveSession.pendingHistoryControlSequence = "";
@@ -1627,6 +1644,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
);
} else if (liveSession.status === "exited" || liveSession.status === "error") {
liveSession.runtimeEnv = nextRuntimeEnv;
liveSession.worktreePath = input.worktreePath ?? null;
liveSession.history = "";
liveSession.pendingHistoryControlSequence = "";
liveSession.pendingProcessEvents = [];
@@ -1646,6 +1664,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: liveSession.worktreePath,
cols: targetCols,
rows: targetRows,
...(input.env ? { env: input.env } : {}),
@@ -1722,6 +1741,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
withThreadLock(
input.threadId,
Effect.gen(function* () {
yield* increment(terminalRestartsTotal, { scope: "thread" });
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
yield* assertValidCwd(input.cwd);
@@ -1735,6 +1755,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history: "",
@@ -1751,6 +1772,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
const createdSession = session;
@@ -1764,6 +1786,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session = existingSession.value;
yield* stopProcess(session);
session.cwd = input.cwd;
session.worktreePath = input.worktreePath ?? null;
session.runtimeEnv = normalizedRuntimeEnv(input.env);
}
@@ -1782,6 +1805,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
cols,
rows,
...(input.env ? { env: input.env } : {}),
@@ -37,6 +37,7 @@ export interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
@@ -50,6 +51,7 @@ export interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -0,0 +1,141 @@
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
import type { Readable } from "node:stream";
import { afterEach, describe, expect, it } from "vitest";
import { defaultSubprocessInspector } from "./index";
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
interface StartedProcess {
process: ListenerProcess;
port: number;
}
async function waitForPort(child: ListenerProcess): Promise<number> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
cleanup();
reject(new Error("Timed out waiting for listener port"));
}, 3_000);
let stdout = "";
let stderr = "";
const cleanup = () => {
clearTimeout(timeout);
child.stdout.off("data", onStdout);
child.stderr.off("data", onStderr);
child.off("exit", onExit);
};
const onStdout = (chunk: Buffer) => {
stdout += chunk.toString("utf8");
const match = stdout.match(/PORT:(\d+)/);
if (!match?.[1]) return;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0) return;
cleanup();
resolve(port);
};
const onStderr = (chunk: Buffer) => {
stderr += chunk.toString("utf8");
};
const onExit = (code: number | null) => {
cleanup();
reject(
new Error(
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
),
);
};
child.stdout.on("data", onStdout);
child.stderr.on("data", onStderr);
child.on("exit", onExit);
});
}
async function startListenerProcess(): Promise<StartedProcess> {
const script = [
"const { createServer } = require('node:http');",
"const server = createServer((_req, res) => {",
" res.statusCode = 200;",
" res.end('ok');",
"});",
"server.listen(0, '127.0.0.1', () => {",
" const address = server.address();",
" if (typeof address !== 'object' || !address) process.exit(1);",
" console.log(`PORT:${address.port}`);",
"});",
"const shutdown = () => server.close(() => process.exit(0));",
"process.on('SIGTERM', shutdown);",
"process.on('SIGINT', shutdown);",
"setInterval(() => {}, 10_000);",
].join("");
const process = spawn("node", ["-e", script], {
stdio: ["ignore", "pipe", "pipe"],
});
const port = await waitForPort(process);
return { process, port };
}
async function stopProcess(child: ChildProcess): Promise<void> {
if (child.exitCode !== null || child.signalCode !== null) {
return;
}
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 1_000);
child.once("exit", () => {
clearTimeout(timeout);
resolve();
});
});
}
describe("defaultSubprocessInspector", () => {
const spawned: ChildProcess[] = [];
afterEach(async () => {
await Promise.all(spawned.splice(0, spawned.length).map((child) => stopProcess(child)));
});
it("detects listening ports when the terminal root PID is the listener", async () => {
const listener = await startListenerProcess();
spawned.push(listener.process);
const listenerPid = listener.process.pid;
if (!listenerPid) {
throw new Error("Listener process pid missing");
}
const activity = await defaultSubprocessInspector(listenerPid);
expect(activity.hasRunningSubprocess).toBe(true);
expect(activity.runningPorts).toContain(listener.port);
});
it("returns idle activity when root process has no children and no listening ports", async () => {
const idle = spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
stdio: ["ignore", "ignore", "ignore"],
});
spawned.push(idle);
const idlePid = idle.pid;
if (!idlePid) {
throw new Error("Idle process pid missing");
}
const activity = await defaultSubprocessInspector(idlePid);
expect(activity.hasRunningSubprocess).toBe(false);
expect(activity.runningPorts).toEqual([]);
});
});
@@ -0,0 +1,46 @@
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "./posix";
import { type TerminalSubprocessActivity } from "./types";
import { checkWindowsListeningPorts, collectWindowsProcessFamilyPids } from "./win32";
export { arePortListsEqual, normalizeRunningPorts } from "./utils";
export type {
TerminalSubprocessActivity,
TerminalSubprocessChecker,
TerminalSubprocessInspector,
TerminalWebPortInspector,
} from "./types";
export async function defaultSubprocessInspector(
terminalPid: number,
): Promise<TerminalSubprocessActivity> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return { hasRunningSubprocess: false, runningPorts: [] };
}
if (process.platform === "win32") {
const processFamilyPids = await collectWindowsProcessFamilyPids(terminalPid);
if (processFamilyPids.length === 0) {
return { hasRunningSubprocess: false, runningPorts: [] };
}
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
const runningPorts = await checkWindowsListeningPorts(processFamilyPids);
return {
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
runningPorts,
};
}
const processFamilyPids = await collectPosixProcessFamilyPids(terminalPid);
if (processFamilyPids.length === 0) {
return { hasRunningSubprocess: false, runningPorts: [] };
}
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
const runningPorts = await checkPosixListeningPorts(processFamilyPids);
return {
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
runningPorts,
};
}
@@ -0,0 +1,119 @@
import { runProcess } from "../processRunner";
import { MAX_PORT_NUMBER, portFromAddress } from "./utils";
export async function collectPosixProcessFamilyPids(terminalPid: number): Promise<number[]> {
try {
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
});
if (psResult.code !== 0) {
return [];
}
const childrenByParentPid = new Map<number, number[]>();
for (const line of psResult.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParentPid.get(ppid);
if (children) {
children.push(pid);
} else {
childrenByParentPid.set(ppid, [pid]);
}
}
const processFamily = new Set<number>([terminalPid]);
const pendingParents = [terminalPid];
while (pendingParents.length > 0) {
const parentPid = pendingParents.shift();
if (!parentPid) continue;
const childPids = childrenByParentPid.get(parentPid);
if (!childPids || childPids.length === 0) continue;
for (const childPid of childPids) {
if (processFamily.has(childPid)) continue;
processFamily.add(childPid);
pendingParents.push(childPid);
}
}
return [...processFamily];
} catch {
return [];
}
}
export async function checkPosixListeningPorts(processIds: number[]): Promise<number[]> {
if (processIds.length === 0) return [];
const ports = new Set<number>();
const pidFilter = new Set(processIds);
try {
const result = await runProcess(
"lsof",
["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
{
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
},
);
if (result.code !== 0) {
// `lsof` returns 1 when there are no matching files/sockets.
// This is a valid "no results" outcome; avoid falling back to `ss`.
return [];
}
for (const line of result.stdout.split(/\r?\n/g)) {
const match = line.match(/:(\d+)\s+\(LISTEN\)$/);
if (!match?.[1]) continue;
const port = Number(match[1]);
if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
} catch {
// Fall back to ss if lsof is unavailable.
}
try {
const result = await runProcess("ss", ["-ltnp"], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 524_288,
outputMode: "truncate",
});
if (result.code !== 0) {
return [];
}
for (const line of result.stdout.split(/\r?\n/g)) {
if (!line.includes("pid=")) continue;
const localAddress = line.trim().split(/\s+/g)[3];
if (!localAddress) continue;
const port = portFromAddress(localAddress);
if (port === null) continue;
const pidMatches = [...line.matchAll(/pid=(\d+)/g)];
if (pidMatches.length === 0) continue;
if (
pidMatches.some((match) => {
const pid = Number(match[1]);
return Number.isInteger(pid) && pidFilter.has(pid);
})
) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
} catch {
return [];
}
}
@@ -0,0 +1,12 @@
export type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
export type TerminalWebPortInspector = (port: number) => Promise<boolean>;
export interface TerminalSubprocessActivity {
hasRunningSubprocess: boolean;
runningPorts: number[];
}
export type TerminalSubprocessInspector = (
terminalPid: number,
) => Promise<TerminalSubprocessActivity>;
@@ -0,0 +1,52 @@
export const MAX_PORT_NUMBER = 65_535;
export function normalizeRunningPorts(ports: number[]): number[] {
if (ports.length === 0) return [];
return [...new Set(ports)]
.filter((port) => Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER)
.toSorted((left, right) => left - right);
}
export function parsePidList(stdout: string): number[] {
const pids: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const pid = Number(line.trim());
if (!Number.isInteger(pid) || pid <= 0) {
continue;
}
pids.push(pid);
}
return [...new Set(pids)];
}
export function parsePortList(stdout: string): number[] {
const ports: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const port = Number(line.trim());
if (!Number.isInteger(port)) {
continue;
}
ports.push(port);
}
return normalizeRunningPorts(ports);
}
export function portFromAddress(address: string): number | null {
const match = address.match(/:(\d+)$/);
if (!match?.[1]) return null;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
return null;
}
return port;
}
export function arePortListsEqual(left: number[], right: number[]): boolean {
if (left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return false;
}
}
return true;
}
@@ -0,0 +1,87 @@
import { runProcess } from "../processRunner";
import { parsePortList } from "./utils";
export async function collectWindowsProcessFamilyPids(terminalPid: number): Promise<number[]> {
const command = [
"$procs = Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId -ErrorAction SilentlyContinue",
"if (-not $procs) { exit 0 }",
'$procs | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }',
].join("; ");
try {
const result = await runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", command],
{
timeoutMs: 2_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
},
);
if (result.code !== 0) {
return [];
}
const childrenByParentPid = new Map<number, number[]>();
for (const line of result.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParentPid.get(ppid);
if (children) {
children.push(pid);
} else {
childrenByParentPid.set(ppid, [pid]);
}
}
const processFamily = new Set<number>([terminalPid]);
const pendingParents = [terminalPid];
while (pendingParents.length > 0) {
const parentPid = pendingParents.shift();
if (!parentPid) continue;
const childPids = childrenByParentPid.get(parentPid);
if (!childPids || childPids.length === 0) continue;
for (const childPid of childPids) {
if (processFamily.has(childPid)) continue;
processFamily.add(childPid);
pendingParents.push(childPid);
}
}
return [...processFamily];
} catch {
return [];
}
}
export async function checkWindowsListeningPorts(processIds: number[]): Promise<number[]> {
if (processIds.length === 0) return [];
const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or ");
const command = [
"$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue",
`$matching = $connections | Where-Object { ${processFilter} }`,
"if (-not $matching) { exit 0 }",
"$matching | Select-Object -ExpandProperty LocalPort -Unique",
].join("; ");
try {
const result = await runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", command],
{
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 65_536,
outputMode: "truncate",
},
);
if (result.code !== 0) {
return [];
}
return parsePortList(result.stdout);
} catch {
return [];
}
}
+81
View File
@@ -0,0 +1,81 @@
import { createServer, type Server } from "node:http";
import { afterEach, describe, expect, it } from "vitest";
import { defaultWebPortInspector } from "./webPortInspector";
async function listenServer(server: Server): Promise<number> {
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const address = server.address();
if (!address || typeof address !== "object") {
throw new Error("Server did not provide a valid listening address.");
}
return address.port;
}
async function closeServer(server: Server): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
describe("defaultWebPortInspector", () => {
const servers: Server[] = [];
afterEach(async () => {
await Promise.all(servers.splice(0, servers.length).map((server) => closeServer(server)));
});
it("treats slow HTML responses as web ports", async () => {
const server = createServer((_req, res) => {
setTimeout(() => {
res.statusCode = 200;
res.setHeader("content-type", "text/html; charset=utf-8");
res.end("<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>");
}, 800);
});
servers.push(server);
const port = await listenServer(server);
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
});
it("treats HTML responses with large bodies as web ports", async () => {
const server = createServer((_req, res) => {
res.statusCode = 200;
res.setHeader("content-type", "text/html; charset=utf-8");
res.end(
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
);
});
servers.push(server);
const port = await listenServer(server);
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
});
it("ignores HTTP 404 responses", async () => {
const server = createServer((_req, res) => {
res.statusCode = 404;
res.end();
});
servers.push(server);
const port = await listenServer(server);
await expect(defaultWebPortInspector(port)).resolves.toBe(false);
});
});
+132
View File
@@ -0,0 +1,132 @@
import { request as httpRequest } from "node:http";
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
interface WebProbeResult {
status: number;
contentType: string;
body: string;
location: string;
}
function normalizeHeaderValue(value: string | string[] | undefined): string {
if (typeof value === "string") return value;
if (Array.isArray(value)) return value[0] ?? "";
return "";
}
function isLikelyWebProbe(result: WebProbeResult | null): boolean {
if (!result) return false;
if (result.status === 404) return false;
if (result.status >= 300 && result.status < 400 && result.location.length > 0) {
return true;
}
const contentType = result.contentType.toLowerCase();
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
return true;
}
const body = result.body.toLowerCase();
return body.includes("<!doctype") || body.includes("<html") || body.includes("<head");
}
async function probeWebPortOnHost(port: number, host: string): Promise<WebProbeResult | null> {
return new Promise((resolve) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let settled = false;
const settle = (result: WebProbeResult | null) => {
if (settled) return;
settled = true;
if (timer) {
clearTimeout(timer);
}
resolve(result);
};
const req = httpRequest(
{
host,
port,
method: "GET",
path: "/",
timeout: DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS,
},
(res) => {
const status = res.statusCode ?? 0;
const contentType = normalizeHeaderValue(res.headers["content-type"]);
const location = normalizeHeaderValue(res.headers.location);
const settleFromChunks = (chunks: string[]) => {
settle({
status,
contentType,
location,
body: chunks.join(""),
});
};
// Resolve immediately for clear web responses based on status/headers.
if (
(status >= 300 && status < 400 && location.length > 0) ||
contentType.toLowerCase().includes("text/html") ||
contentType.toLowerCase().includes("application/xhtml+xml")
) {
settle({
status,
contentType,
location,
body: "",
});
req.destroy();
return;
}
const chunks: string[] = [];
let received = 0;
res.setEncoding("utf8");
res.on("data", (chunk: string) => {
if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) return;
const remaining = WEB_PORT_PROBE_MAX_BODY_BYTES - received;
const fragment = chunk.slice(0, remaining);
received += fragment.length;
chunks.push(fragment);
if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
settleFromChunks(chunks);
res.destroy();
}
});
res.on("end", () => {
settleFromChunks(chunks);
});
res.on("error", () => {
settle(null);
});
},
);
req.on("timeout", () => {
req.destroy();
settle(null);
});
req.on("error", () => {
settle(null);
});
timer = setTimeout(() => {
req.destroy();
settle(null);
}, DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS + 50);
req.end();
});
}
export async function defaultWebPortInspector(port: number): Promise<boolean> {
const ipv4Result = await probeWebPortOnHost(port, "127.0.0.1");
if (isLikelyWebProbe(ipv4Result)) {
return true;
}
const ipv6Result = await probeWebPortOnHost(port, "::1");
return isLikelyWebProbe(ipv6Result);
}
+519 -118
View File
@@ -1,5 +1,8 @@
import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import {
CommandId,
EventId,
type OrchestrationCommand,
type GitActionProgressEvent,
type GitManagerServiceError,
OrchestrationDispatchCommandError,
@@ -11,6 +14,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
ThreadId,
type TerminalEvent,
WS_METHODS,
WsRpcGroup,
@@ -28,6 +32,11 @@ import { Open, resolveAvailableEditors } from "./open";
import { normalizeDispatchCommand } from "./orchestration/Normalizer";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./observability/RpcInstrumentation";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { ServerLifecycleEvents } from "./serverLifecycleEvents";
import { ServerRuntimeStartup } from "./serverRuntimeStartup";
@@ -36,6 +45,7 @@ import { TerminalManager } from "./terminal/Services/Manager";
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";
const WsRpcLayer = WsRpcGroup.toLayer(
Effect.gen(function* () {
@@ -54,6 +64,265 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const startup = yield* ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const serverCommandId = (tag: string) =>
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
const appendSetupScriptActivity = (input: {
readonly threadId: ThreadId;
readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
readonly summary: string;
readonly createdAt: string;
readonly payload: Record<string, unknown>;
readonly tone: "info" | "error";
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("setup-script-activity"),
threadId: input.threadId,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: input.tone,
kind: input.kind,
summary: input.summary,
payload: input.payload,
turnId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: cause instanceof Error ? cause.message : fallbackMessage,
cause,
});
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
const error = Cause.squash(cause);
return Schema.is(OrchestrationDispatchCommandError)(error)
? error
: new OrchestrationDispatchCommandError({
message:
error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
cause,
});
};
const dispatchBootstrapTurnStart = (
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
Effect.gen(function* () {
const bootstrap = command.bootstrap;
const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
let createdThread = false;
let targetProjectId = bootstrap?.createThread?.projectId;
let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
const cleanupCreatedThread = () =>
createdThread
? orchestrationEngine
.dispatch({
type: "thread.delete",
commandId: serverCommandId("bootstrap-thread-delete"),
threadId: command.threadId,
})
.pipe(Effect.ignoreCause({ log: true }))
: Effect.void;
const recordSetupScriptLaunchFailure = (input: {
readonly error: unknown;
readonly requestedAt: string;
readonly worktreePath: string;
}) => {
const detail =
input.error instanceof Error ? input.error.message : "Unknown setup failure.";
return appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.failed",
summary: "Setup script failed to start",
createdAt: input.requestedAt,
payload: {
detail,
worktreePath: input.worktreePath,
},
tone: "error",
}).pipe(
Effect.ignoreCause({ log: false }),
Effect.flatMap(() =>
Effect.logWarning("bootstrap turn start failed to launch setup script", {
threadId: command.threadId,
worktreePath: input.worktreePath,
detail,
}),
),
);
};
const recordSetupScriptStarted = (input: {
readonly requestedAt: string;
readonly worktreePath: string;
readonly scriptId: string;
readonly scriptName: string;
readonly terminalId: string;
}) => {
const payload = {
scriptId: input.scriptId,
scriptName: input.scriptName,
terminalId: input.terminalId,
worktreePath: input.worktreePath,
};
return Effect.all([
appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.requested",
summary: "Starting setup script",
createdAt: input.requestedAt,
payload,
tone: "info",
}),
appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.started",
summary: "Setup script started",
createdAt: new Date().toISOString(),
payload,
tone: "info",
}),
]).pipe(
Effect.asVoid,
Effect.catch((error) =>
Effect.logWarning(
"bootstrap turn start launched setup script but failed to record setup activity",
{
threadId: command.threadId,
worktreePath: input.worktreePath,
scriptId: input.scriptId,
terminalId: input.terminalId,
detail:
error instanceof Error
? error.message
: "Unknown setup activity dispatch failure.",
},
),
),
);
};
const runSetupProgram = () =>
bootstrap?.runSetupScript && targetWorktreePath
? (() => {
const worktreePath = targetWorktreePath;
const requestedAt = new Date().toISOString();
return projectSetupScriptRunner
.runForThread({
threadId: command.threadId,
...(targetProjectId ? { projectId: targetProjectId } : {}),
...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
worktreePath,
})
.pipe(
Effect.matchEffect({
onFailure: (error) =>
recordSetupScriptLaunchFailure({
error,
requestedAt,
worktreePath,
}),
onSuccess: (setupResult) => {
if (setupResult.status !== "started") {
return Effect.void;
}
return recordSetupScriptStarted({
requestedAt,
worktreePath,
scriptId: setupResult.scriptId,
scriptName: setupResult.scriptName,
terminalId: setupResult.terminalId,
});
},
}),
);
})()
: Effect.void;
const bootstrapProgram = Effect.gen(function* () {
if (bootstrap?.createThread) {
yield* orchestrationEngine.dispatch({
type: "thread.create",
commandId: serverCommandId("bootstrap-thread-create"),
threadId: command.threadId,
projectId: bootstrap.createThread.projectId,
title: bootstrap.createThread.title,
modelSelection: bootstrap.createThread.modelSelection,
runtimeMode: bootstrap.createThread.runtimeMode,
interactionMode: bootstrap.createThread.interactionMode,
branch: bootstrap.createThread.branch,
worktreePath: bootstrap.createThread.worktreePath,
createdAt: bootstrap.createThread.createdAt,
});
createdThread = true;
}
if (bootstrap?.prepareWorktree) {
const worktree = yield* git.createWorktree({
cwd: bootstrap.prepareWorktree.projectCwd,
branch: bootstrap.prepareWorktree.baseBranch,
newBranch: bootstrap.prepareWorktree.branch,
path: null,
});
targetWorktreePath = worktree.worktree.path;
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("bootstrap-thread-meta-update"),
threadId: command.threadId,
branch: worktree.worktree.branch,
worktreePath: targetWorktreePath,
});
}
yield* runSetupProgram();
return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
});
return yield* bootstrapProgram.pipe(
Effect.catchCause((cause) => {
const dispatchError = toBootstrapDispatchCommandCauseError(cause);
if (Cause.hasInterruptsOnly(cause)) {
return Effect.fail(dispatchError);
}
return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
}),
);
});
const dispatchNormalizedCommand = (
normalizedCommand: OrchestrationCommand,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
const dispatchEffect =
normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
? dispatchBootstrapTurnStart(normalizedCommand)
: orchestrationEngine
.dispatch(normalizedCommand)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
return startup
.enqueueCommand(dispatchEffect)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
};
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
@@ -67,72 +336,112 @@ const WsRpcLayer = WsRpcGroup.toLayer(
issues: keybindingsConfig.issues,
providers,
availableEditors: resolveAvailableEditors(),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
otlpTracesEnabled: config.otlpTracesUrl !== undefined,
...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}),
otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
},
settings,
};
});
return WsRpcGroup.of({
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
projectionSnapshotQuery.getSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot",
cause,
}),
),
),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand));
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getSnapshot,
projectionSnapshotQuery.getSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const result = yield* dispatchNormalizedCommand(normalizedCommand);
if (normalizedCommand.type === "thread.archive") {
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: normalizedCommand.threadId,
error: error.message,
}),
),
);
}
return result;
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
checkpointDiffQuery.getTurnDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetTurnDiffError({
message: "Failed to load turn diff",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getTurnDiff,
checkpointDiffQuery.getTurnDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetTurnDiffError({
message: "Failed to load turn diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
checkpointDiffQuery.getFullThreadDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetFullThreadDiffError({
message: "Failed to load full thread diff",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
checkpointDiffQuery.getFullThreadDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetFullThreadDiffError({
message: "Failed to load full thread diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
Stream.runCollect(
orchestrationEngine.readEvents(
clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
message: "Failed to replay orchestration events",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.replayEvents,
Stream.runCollect(
orchestrationEngine.readEvents(
clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
message: "Failed to replay orchestration events",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeOrchestrationDomainEvents,
Effect.gen(function* () {
const snapshot = yield* orchestrationEngine.getReadModel();
const fromSequenceExclusive = snapshot.snapshotSequence;
@@ -187,82 +496,167 @@ const WsRpcLayer = WsRpcGroup.toLayer(
Stream.flatMap((events) => Stream.fromIterable(events)),
);
}),
{ "rpc.aggregate": "orchestration" },
),
[WS_METHODS.serverGetConfig]: (_input) => loadServerConfig,
[WS_METHODS.serverRefreshProviders]: (_input) =>
providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
return { keybindings: keybindingsConfig, issues: [] };
[WS_METHODS.serverGetConfig]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverRefreshProviders]: (_input) =>
observeRpcEffect(
WS_METHODS.serverRefreshProviders,
providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
observeRpcEffect(
WS_METHODS.serverUpsertKeybinding,
Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
return { keybindings: keybindingsConfig, issues: [] };
}),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverGetSettings]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverUpdateSettings]: ({ patch }) =>
observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings,
[WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch),
[WS_METHODS.projectsSearchEntries]: (input) =>
workspaceEntries.search(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchEntriesError({
message: `Failed to search workspace entries: ${cause.detail}`,
cause,
}),
observeRpcEffect(
WS_METHODS.projectsSearchEntries,
workspaceEntries.search(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchEntriesError({
message: `Failed to search workspace entries: ${cause.detail}`,
cause,
}),
),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsWriteFile]: (input) =>
workspaceFileSystem.writeFile(input).pipe(
Effect.mapError((cause) => {
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
? "Workspace file path must stay within the project root."
: "Failed to write workspace file";
return new ProjectWriteFileError({
message,
cause,
});
}),
),
[WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input),
[WS_METHODS.gitStatus]: (input) => gitManager.status(input),
[WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd),
[WS_METHODS.gitRunStackedAction]: (input) =>
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
gitManager
.runStackedAction(input, {
actionId: input.actionId,
progressReporter: {
publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
},
})
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
}),
),
),
[WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input),
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
gitManager.preparePullRequestThread(input),
[WS_METHODS.gitListBranches]: (input) => git.listBranches(input),
[WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input),
[WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input),
[WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input),
[WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)),
[WS_METHODS.gitInit]: (input) => git.initRepo(input),
[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
[WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
[WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
[WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
terminalManager.subscribe((event) => Queue.offer(queue, event)),
(unsubscribe) => Effect.sync(unsubscribe),
observeRpcEffect(
WS_METHODS.projectsWriteFile,
workspaceFileSystem.writeFile(input).pipe(
Effect.mapError((cause) => {
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
? "Workspace file path must stay within the project root."
: "Failed to write workspace file";
return new ProjectWriteFileError({
message,
cause,
});
}),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.shellOpenInEditor]: (input) =>
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.gitStatus]: (input) =>
observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitPull]: (input) =>
observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRunStackedAction]: (input) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
gitManager
.runStackedAction(input, {
actionId: input.actionId,
progressReporter: {
publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
},
})
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
}),
),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitResolvePullRequest]: (input) =>
observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager.preparePullRequestThread(input),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRemoveWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateBranch]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCheckout]: (input) =>
observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitInit]: (input) =>
observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "rpc.aggregate": "git" }),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalWrite]: (input) =>
observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalResize]: (input) =>
observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalClear]: (input) =>
observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalRestart]: (input) =>
observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalClose]: (input) =>
observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
observeRpcStream(
WS_METHODS.subscribeTerminalEvents,
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
terminalManager.subscribe((event) => Queue.offer(queue, event)),
(unsubscribe) => Effect.sync(unsubscribe),
),
),
{ "rpc.aggregate": "terminal" },
),
[WS_METHODS.subscribeServerConfig]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeServerConfig,
Effect.gen(function* () {
const keybindingsUpdates = keybindings.streamChanges.pipe(
Stream.map((event) => ({
@@ -297,9 +691,11 @@ const WsRpcLayer = WsRpcGroup.toLayer(
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
);
}),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.subscribeServerLifecycle]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeServerLifecycle,
Effect.gen(function* () {
const snapshot = yield* lifecycleEvents.snapshot;
const snapshotEvents = Array.from(snapshot.events).toSorted(
@@ -310,6 +706,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
);
return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
}),
{ "rpc.aggregate": "server" },
),
});
}),
@@ -317,9 +714,13 @@ const WsRpcLayer = WsRpcGroup.toLayer(
export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe(
Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)),
);
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
spanPrefix: "ws.rpc",
spanAttributes: {
"rpc.transport": "websocket",
"rpc.system": "effect-rpc",
},
}).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)));
return HttpRouter.add(
"GET",
"/ws",
+4 -52
View File
@@ -1,5 +1,9 @@
import type { GitBranch } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "@t3tools/shared/git";
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
@@ -43,58 +47,6 @@ export function resolveBranchToolbarValue(input: {
return currentGitBranch ?? activeThreadBranch;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
if (branch.remoteName !== "origin") {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
@@ -1,5 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -15,7 +15,7 @@ import {
} from "react";
import {
gitBranchesQueryOptions,
gitBranchSearchInfiniteQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
@@ -23,7 +23,6 @@ import {
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveBranchSelectionTarget,
@@ -38,6 +37,7 @@ import {
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxStatus,
ComboboxTrigger,
} from "./ui/combobox";
import { toastManager } from "./ui/toast";
@@ -89,11 +89,33 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
useEffect(() => {
if (!branchCwd) return;
void queryClient.prefetchInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({ cwd: branchCwd, query: "" }),
);
}, [branchCwd, queryClient]);
const {
data: branchesSearchData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isPending: isBranchesSearchPending,
} = useInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
enabled: isBranchMenuOpen,
}),
);
const branches = useMemo(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
[branchesSearchData?.pages],
);
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
@@ -108,8 +130,6 @@ export function BranchToolbarBranchSelector({
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
[branches],
);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
const isSelectingWorktreeBase =
@@ -156,6 +176,14 @@ export function BranchToolbarBranchSelector({
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
? "Loading branches..."
: isFetchingNextPage
? "Loading more branches..."
: hasNextPage
? `Showing ${branches.length} of ${totalBranchCount} branches`
: null;
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
@@ -213,7 +241,7 @@ export function BranchToolbarBranchSelector({
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
const status = await api.git.status({ cwd: selectionTarget.checkoutCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
@@ -295,6 +323,24 @@ export function BranchToolbarBranchSelector({
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const maybeFetchNextBranchPage = useCallback(() => {
if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
return;
}
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement) {
return;
}
const distanceFromBottom =
scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
if (distanceFromBottom > 96) {
return;
}
void fetchNextPage().catch(() => undefined);
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: (index) =>
@@ -331,6 +377,35 @@ export function BranchToolbarBranchSelector({
shouldVirtualizeBranchList,
]);
useEffect(() => {
if (!isBranchMenuOpen) {
return;
}
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement || !isBranchMenuOpen) {
return;
}
const handleScroll = () => {
maybeFetchNextBranchPage();
};
scrollElement.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
return () => {
scrollElement.removeEventListener("scroll", handleScroll);
};
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
useEffect(() => {
maybeFetchNextBranchPage();
}, [branches.length, maybeFetchNextBranchPage]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
@@ -425,7 +500,7 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
>
<span className="max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon />
@@ -468,6 +543,7 @@ export function BranchToolbarBranchSelector({
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
)}
</ComboboxList>
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
);
+258 -93
View File
@@ -33,6 +33,7 @@ import { isMacPlatform } from "../lib/utils";
import { __resetNativeApiForTests } from "../nativeApi";
import { getRouter } from "../router";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
@@ -135,6 +136,12 @@ function createBaseServerConfig(): ServerConfig {
},
],
availableEditors: [],
observability: {
logsDirectoryPath: "/repo/project/.t3/logs",
localTracingEnabled: true,
otlpTracesEnabled: false,
otlpMetricsEnabled: false,
},
settings: {
...DEFAULT_SERVER_SETTINGS,
...DEFAULT_CLIENT_SETTINGS,
@@ -573,51 +580,6 @@ function createSnapshotWithPendingUserInput(): OrchestrationReadModel {
};
}
function createSnapshotWithPendingApproval(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-pending-approval-target" as MessageId,
targetText: "approval thread",
});
const approvalDetail = [
'"C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -Command',
'"ssh pipe-[REDACTED] \\"vdpkg -l localepurge 2>/dev/null || true; printf \\\\\\"\\\\n--- localepurge --\\\\n\\\\\\"; sed -n 1,80p /etc/locale.nopurge\\""',
].join(" ");
return {
...snapshot,
threads: snapshot.threads.map((thread) =>
thread.id === THREAD_ID
? Object.assign({}, thread, {
runtimeMode: "approval-required",
activities: [
{
id: EventId.makeUnsafe("activity-approval-requested"),
tone: "approval",
kind: "approval.requested",
summary: "Command approval requested",
payload: {
requestId: "req-browser-approval",
requestKind: "command",
detail: approvalDetail,
},
turnId: null,
sequence: 1,
createdAt: isoAt(1_000),
},
],
session: {
...thread.session,
runtimeMode: "approval-required",
status: "ready",
updatedAt: isoAt(1_000),
},
updatedAt: isoAt(1_000),
})
: thread,
),
};
}
function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-plan-follow-up-target" as MessageId,
@@ -677,6 +639,8 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [
{
name: "main",
@@ -689,6 +653,9 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: {
@@ -716,6 +683,12 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
terminalId: typeof body.terminalId === "string" ? body.terminalId : "default",
cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project",
worktreePath:
typeof body.worktreePath === "string"
? body.worktreePath
: body.worktreePath === null
? null
: null,
status: "running",
pid: 123,
history: "",
@@ -1183,6 +1156,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
threads: [],
bootstrapComplete: false,
});
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
});
afterEach(() => {
@@ -1406,6 +1386,75 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-launch-context-target" as MessageId,
targetText: "launch context worktree override",
});
const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID);
if (targetThread) {
Object.assign(targetThread, {
branch: "feature/branch",
worktreePath: "/repo/worktrees/feature-branch",
});
}
useTerminalStateStore.setState({
terminalStateByThreadId: {
[THREAD_ID]: {
terminalOpen: true,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
},
},
terminalLaunchContextByThreadId: {
[THREAD_ID]: {
cwd: "/repo/project",
worktreePath: null,
},
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot,
});
try {
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
) as
| {
_tag: string;
cwd?: string;
worktreePath?: string | null;
env?: Record<string, string>;
}
| undefined;
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
cwd: "/repo/project",
worktreePath: null,
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
},
});
expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
@@ -1747,7 +1796,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("runs setup scripts after preparing a pull request worktree thread", async () => {
it("lets the server own setup after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
@@ -1852,45 +1901,188 @@ describe("ChatView timeline estimator parity (full app)", () => {
cwd: "/repo/project",
reference: "1359",
mode: "worktree",
threadId: THREAD_ID,
});
},
{ timeout: 8_000, interval: 16 },
);
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
),
).toBe(false);
} finally {
await mounted.cleanup();
}
});
it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
expect(sendButton.disabled).toBe(false);
sendButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: expect.any(String),
cwd: "/repo/worktrees/pr-1359",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
const dispatchRequest = wsRequests.find(
(request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand,
) as
| {
_tag: string;
type?: string;
bootstrap?: {
createThread?: { projectId?: string };
prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string };
runSetupScript?: boolean;
};
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "thread.turn.start",
bootstrap: {
createThread: {
projectId: PROJECT_ID,
},
prepareWorktree: {
projectCwd: "/repo/project",
baseBranch: "main",
branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/),
},
runSetupScript: true,
},
});
},
{ timeout: 8_000, interval: 16 },
);
expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe(
false,
);
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.terminalWrite &&
request.threadId === THREAD_ID &&
request.data === "bun install\r",
),
).toBe(false);
} finally {
await mounted.cleanup();
}
});
it("shows the send state once bootstrap dispatch is in flight", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
let resolveDispatch!: (value: { sequence: number }) => void;
const dispatchPromise = new Promise<{ sequence: number }>((resolve) => {
resolveDispatch = resolve;
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return dispatchPromise;
}
return undefined;
},
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
expect(sendButton.disabled).toBe(false);
sendButton.click();
await vi.waitFor(
() => {
const writeRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
);
expect(writeRequest).toMatchObject({
_tag: WS_METHODS.terminalWrite,
threadId: expect.any(String),
data: "bun install\r",
});
expect(
wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand),
).toBe(true);
expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy();
expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull();
},
{ timeout: 8_000, interval: 16 },
);
} finally {
resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 });
await mounted.cleanup();
}
});
@@ -2647,33 +2839,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("renders pending approval commands in a readable wrapped block", async () => {
const mounted = await mountChatView({
viewport: COMPACT_FOOTER_VIEWPORT,
snapshot: createSnapshotWithPendingApproval(),
});
try {
await waitForButtonByText("Approve once");
const detail = await waitForElement(
() => document.querySelector<HTMLElement>('[data-testid="pending-approval-detail"]'),
"Unable to find pending approval detail block.",
);
const detailStyle = getComputedStyle(detail);
expect(detail.textContent).toContain("powershell.exe");
expect(detail.textContent).toContain("localepurge");
expect(detail.textContent).not.toContain("...");
expect(detailStyle.whiteSpace).toBe("pre-wrap");
expect(detailStyle.userSelect).toBe("text");
expect(detailStyle.color).not.toBe("rgba(0, 0, 0, 0)");
expect(detail.getBoundingClientRect().height).toBeGreaterThan(32);
expect(document.body.textContent).toContain("Resolve this approval request to continue");
} finally {
await mounted.cleanup();
}
});
it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
@@ -3,10 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
waitForStartedServerThread,
} from "./ChatView.logic";
@@ -75,6 +77,98 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
describe("reconcileMountedTerminalThreadIds", () => {
it("keeps previously mounted open threads and adds the active open thread", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-hidden"),
ThreadId.makeUnsafe("thread-stale"),
],
openThreadIds: [ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")],
activeThreadId: ThreadId.makeUnsafe("thread-active"),
activeThreadTerminalOpen: true,
}),
).toEqual([ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")]);
});
it("drops mounted threads once their terminal drawer is no longer open", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [ThreadId.makeUnsafe("thread-closed")],
openThreadIds: [],
activeThreadId: ThreadId.makeUnsafe("thread-closed"),
activeThreadTerminalOpen: false,
}),
).toEqual([]);
});
it("keeps only the most recently active hidden terminal threads", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
],
openThreadIds: [
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
],
activeThreadId: ThreadId.makeUnsafe("thread-4"),
activeThreadTerminalOpen: true,
maxHiddenThreadCount: 2,
}),
).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
]);
});
it("moves the active thread to the end so it is treated as most recently used", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-a"),
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
],
openThreadIds: [
ThreadId.makeUnsafe("thread-a"),
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
],
activeThreadId: ThreadId.makeUnsafe("thread-a"),
activeThreadTerminalOpen: true,
maxHiddenThreadCount: 2,
}),
).toEqual([
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
ThreadId.makeUnsafe("thread-a"),
]);
});
it("defaults to the hidden mounted terminal cap", () => {
const currentThreadIds = Array.from(
{ length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
(_, index) => ThreadId.makeUnsafe(`thread-${index + 1}`),
);
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: currentThreadIds,
activeThreadId: null,
activeThreadTerminalOpen: false,
}),
).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
+32
View File
@@ -11,6 +11,7 @@ import {
} from "../lib/terminalContext";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
const WORKTREE_BRANCH_PREFIX = "t3code";
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
@@ -43,6 +44,37 @@ export function buildLocalDraftThread(
};
}
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<ThreadId>;
openThreadIds: ReadonlyArray<ThreadId>;
activeThreadId: ThreadId | null;
activeThreadTerminalOpen: boolean;
maxHiddenThreadCount?: number;
}): ThreadId[] {
const openThreadIdSet = new Set(input.openThreadIds);
const hiddenThreadIds = input.currentThreadIds.filter(
(threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
);
const maxHiddenThreadCount = Math.max(
0,
input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
);
const nextThreadIds =
hiddenThreadIds.length > maxHiddenThreadCount
? hiddenThreadIds.slice(-maxHiddenThreadCount)
: hiddenThreadIds;
if (
input.activeThreadId &&
input.activeThreadTerminalOpen &&
!nextThreadIds.includes(input.activeThreadId)
) {
nextThreadIds.push(input.activeThreadId);
}
return nextThreadIds;
}
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
+362 -205
View File
@@ -21,12 +21,13 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -111,10 +112,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
} from "~/projectScripts";
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
@@ -173,6 +171,7 @@ import {
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildTemporaryWorktreeBranchName,
@@ -186,6 +185,7 @@ import {
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
reconcileMountedTerminalThreadIds,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
@@ -331,12 +331,14 @@ interface ChatViewProps {
threadId: ThreadId;
}
interface PendingPullRequestSetupRequest {
interface TerminalLaunchContext {
threadId: ThreadId;
worktreePath: string;
scriptId: string;
cwd: string;
worktreePath: string | null;
}
type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
@@ -404,10 +406,178 @@ function useLocalDispatchState(input: {
};
}
interface PersistentThreadTerminalDrawerProps {
threadId: ThreadId;
visible: boolean;
launchContext: PersistentTerminalLaunchContext | null;
focusRequestId: number;
splitShortcutLabel: string | undefined;
newShortcutLabel: string | undefined;
closeShortcutLabel: string | undefined;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
function PersistentThreadTerminalDrawer({
threadId,
visible,
launchContext,
focusRequestId,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const serverThread = useThreadById(threadId);
const draftThread = useComposerDraftStore(
(store) => store.draftThreadsByThreadId[threadId] ?? null,
);
const project = useProjectById(serverThread?.projectId ?? draftThread?.projectId);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, threadId),
);
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const effectiveWorktreePath = useMemo(() => {
if (launchContext !== null) {
return launchContext.worktreePath;
}
return worktreePath;
}, [launchContext, worktreePath]);
const cwd = useMemo(
() =>
launchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: null),
[effectiveWorktreePath, launchContext?.cwd, project],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: {},
[effectiveWorktreePath, project],
);
const bumpFocusRequestId = useCallback(() => {
if (!visible) {
return;
}
setLocalFocusRequestId((value) => value + 1);
}, [visible]);
const setTerminalHeight = useCallback(
(height: number) => {
storeSetTerminalHeight(threadId, height);
},
[storeSetTerminalHeight, threadId],
);
const splitTerminal = useCallback(() => {
storeSplitTerminal(threadId, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeSplitTerminal, threadId]);
const createNewTerminal = useCallback(() => {
storeNewTerminal(threadId, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeNewTerminal, threadId]);
const activateTerminal = useCallback(
(terminalId: string) => {
storeSetActiveTerminal(threadId, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeSetActiveTerminal, threadId],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
if (!api) return;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void (async () => {
if (isFinalTerminal) {
await api.terminal.clear({ threadId, terminalId }).catch(() => undefined);
}
await api.terminal.close({
threadId,
terminalId,
deleteHistory: true,
});
})().catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
storeCloseTerminal(threadId, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
if (!visible) {
return;
}
onAddTerminalContext(selection);
},
[onAddTerminalContext, visible],
);
if (!project || !terminalState.terminalOpen || !cwd) {
return null;
}
return (
<div className={visible ? undefined : "hidden"}>
<ThreadTerminalDrawer
threadId={threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible={visible}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
runningTerminalIds={terminalState.runningTerminalIds}
runningTerminalPorts={terminalState.runningTerminalPorts}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={visible ? splitShortcutLabel : undefined}
newShortcutLabel={visible ? newShortcutLabel : undefined}
closeShortcutLabel={visible ? closeShortcutLabel : undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={handleAddTerminalContext}
/>
</div>
);
}
export default function ChatView({ threadId }: ChatViewProps) {
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],
@@ -423,8 +593,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
select: (params) => parseDiffRouteSearch(params),
});
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const composerDraft = useComposerThreadDraft(threadId);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
@@ -515,8 +683,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
useState<PendingPullRequestSetupRequest | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -565,15 +734,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
setMessagesScrollElement(element);
}, []);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, threadId),
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
const terminalState = useMemo(
() => selectThreadTerminalState(terminalStateByThreadId, threadId),
[terminalStateByThreadId, threadId],
);
const openTerminalThreadIds = useMemo(
() =>
Object.entries(terminalStateByThreadId).flatMap(([nextThreadId, nextTerminalState]) =>
nextTerminalState.terminalOpen ? [nextThreadId as ThreadId] : [],
),
[terminalStateByThreadId],
);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSetTerminalHeight = useTerminalStateStore((s) => s.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadId[threadId] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const threads = useStore((state) => state.threads);
const serverThreadIds = useMemo(() => threads.map((thread) => thread.id), [threads]);
const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId);
const draftThreadIds = useMemo(
() => Object.keys(draftThreadsByThreadId) as ThreadId[],
[draftThreadsByThreadId],
);
const [mountedTerminalThreadIds, setMountedTerminalThreadIds] = useState<ThreadId[]>([]);
const setPrompt = useCallback(
(nextPrompt: string) => {
@@ -655,6 +846,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const existingOpenTerminalThreadIds = useMemo(() => {
const existingThreadIds = new Set<ThreadId>([...serverThreadIds, ...draftThreadIds]);
return openTerminalThreadIds.filter((nextThreadId) => existingThreadIds.has(nextThreadId));
}, [draftThreadIds, openTerminalThreadIds, serverThreadIds]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -673,6 +868,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
useEffect(() => {
setMountedTerminalThreadIds((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: existingOpenTerminalThreadIds,
activeThreadId,
activeThreadTerminalOpen: Boolean(activeThreadId && terminalState.terminalOpen),
maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
});
return currentThreadIds.length === nextThreadIds.length &&
currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])
? currentThreadIds
: nextThreadIds;
});
}, [activeThreadId, existingOpenTerminalThreadIds, terminalState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = useProjectById(activeThread?.projectId);
@@ -748,24 +958,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handlePreparedPullRequestThread = useCallback(
async (input: { branch: string; worktreePath: string | null }) => {
const targetThreadId = await openOrReuseProjectDraftThread({
await openOrReuseProjectDraftThread({
branch: input.branch,
worktreePath: input.worktreePath,
envMode: input.worktreePath ? "worktree" : "local",
});
const setupScript =
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
if (targetThreadId && input.worktreePath && setupScript) {
setPendingPullRequestSetupRequest({
threadId: targetThreadId,
worktreePath: input.worktreePath,
scriptId: setupScript.id,
});
} else {
setPendingPullRequestSetupRequest(null);
}
},
[activeProject, openOrReuseProjectDraftThread],
[openOrReuseProjectDraftThread],
);
useEffect(() => {
@@ -1201,7 +1400,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd));
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
@@ -1328,17 +1527,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const threadTerminalRuntimeEnv = useMemo(() => {
if (!activeProjectCwd) return {};
return projectScriptRuntimeEnv({
project: {
cwd: activeProjectCwd,
},
worktreePath: activeThreadWorktreePath,
});
}, [activeProjectCwd, activeThreadWorktreePath]);
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -1481,13 +1675,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[activeThreadId, storeSetTerminalOpen],
);
const setTerminalHeight = useCallback(
(height: number) => {
if (!activeThreadId) return;
storeSetTerminalHeight(activeThreadId, height);
},
[activeThreadId, storeSetTerminalHeight],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
setTerminalOpen(!terminalState.terminalOpen);
@@ -1504,14 +1691,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
storeNewTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeNewTerminal]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
storeSetActiveTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, storeSetActiveTerminal],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
@@ -1572,7 +1751,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${randomUUID()}`
: baseTerminalId;
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
setTerminalLaunchContext({
threadId: activeThreadId,
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
setTerminalOpen(true);
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadId, targetTerminalId);
@@ -1585,7 +1770,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
project: {
cwd: activeProject.cwd,
},
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
worktreePath: targetWorktreePath,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
@@ -1593,6 +1778,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
env: runtimeEnv,
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
@@ -1601,6 +1787,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
env: runtimeEnv,
};
@@ -1634,44 +1821,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
],
);
useEffect(() => {
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
return;
}
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
return;
}
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
return;
}
const setupScript =
activeProject.scripts.find(
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
) ?? null;
setPendingPullRequestSetupRequest(null);
if (!setupScript) {
return;
}
void runProjectScript(setupScript, {
cwd: pendingPullRequestSetupRequest.worktreePath,
worktreePath: pendingPullRequestSetupRequest.worktreePath,
rememberAsLastInvoked: false,
}).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to run setup script.",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, [
activeProject,
activeThread,
activeThreadId,
pendingPullRequestSetupRequest,
runProjectScript,
]);
const persistProjectScripts = useCallback(
async (input: {
projectId: ProjectId;
@@ -1993,13 +2142,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
} else if (shouldAutoScrollRef.current && !isNearBottom) {
@@ -2364,6 +2513,74 @@ export default function ChatView({ threadId }: ChatViewProps) {
? (draftThread?.envMode ?? "local")
: "local";
useEffect(() => {
if (!activeThreadId) {
setTerminalLaunchContext(null);
storeClearTerminalLaunchContext(threadId);
return;
}
setTerminalLaunchContext((current) => {
if (!current) return current;
if (current.threadId === activeThreadId) return current;
return null;
});
}, [activeThreadId, storeClearTerminalLaunchContext, threadId]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd) {
return;
}
setTerminalLaunchContext((current) => {
if (!current || current.threadId !== activeThreadId) {
return current;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === current.cwd &&
(activeThreadWorktreePath ?? null) === current.worktreePath
) {
storeClearTerminalLaunchContext(activeThreadId);
return null;
}
return current;
});
}, [activeProjectCwd, activeThreadId, activeThreadWorktreePath, storeClearTerminalLaunchContext]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) {
return;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === storeServerTerminalLaunchContext.cwd &&
(activeThreadWorktreePath ?? null) === storeServerTerminalLaunchContext.worktreePath
) {
storeClearTerminalLaunchContext(activeThreadId);
}
}, [
activeProjectCwd,
activeThreadId,
activeThreadWorktreePath,
storeClearTerminalLaunchContext,
storeServerTerminalLaunchContext,
]);
useEffect(() => {
if (terminalState.terminalOpen) {
return;
}
if (activeThreadId) {
storeClearTerminalLaunchContext(activeThreadId);
}
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [activeThreadId, storeClearTerminalLaunchContext, terminalState.terminalOpen]);
useEffect(() => {
if (phase !== "running") return;
const timer = window.setInterval(() => {
@@ -2778,36 +2995,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(0);
setComposerTrigger(null);
let createdServerThreadForLocalDraft = false;
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
branch: baseBranchForWorktree,
newBranch,
});
nextThreadBranch = result.worktree.branch;
nextThreadWorktreePath = result.worktree.path;
if (isServerThread) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
setStoreThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path);
}
}
let firstComposerImageName: string | null = null;
if (composerImagesSnapshot.length > 0) {
const firstComposerImage = composerImagesSnapshot[0];
@@ -2835,48 +3024,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}),
};
if (isLocalDraftThread) {
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: threadIdForSend,
projectId: activeProject.id,
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
branch: nextThreadBranch,
worktreePath: nextThreadWorktreePath,
createdAt: activeThread.createdAt,
});
createdServerThreadForLocalDraft = true;
}
let setupScript: ProjectScript | null = null;
if (baseBranchForWorktree) {
setupScript = setupProjectScript(activeProject.scripts);
}
if (setupScript) {
let shouldRunSetupScript = false;
if (isServerThread) {
shouldRunSetupScript = true;
} else {
if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
}
if (shouldRunSetupScript) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
worktreePath: nextThreadWorktreePath,
rememberAsLastInvoked: false,
};
if (nextThreadWorktreePath) {
setupScriptOptions.cwd = nextThreadWorktreePath;
}
await runProjectScript(setupScript, setupScriptOptions);
}
}
// Auto-title from first message
if (isFirstMessage && isServerThread) {
await api.orchestration.dispatchCommand({
@@ -2897,8 +3044,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginLocalDispatch({ preparingWorktree: false });
const turnAttachments = await turnAttachmentsPromise;
const bootstrap =
isLocalDraftThread || baseBranchForWorktree
? {
...(isLocalDraftThread
? {
createThread: {
projectId: activeProject.id,
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
createdAt: activeThread.createdAt,
},
}
: {}),
...(baseBranchForWorktree
? {
prepareWorktree: {
projectCwd: activeProject.cwd,
baseBranch: baseBranchForWorktree,
branch: buildTemporaryWorktreeBranchName(),
},
runSetupScript: true,
}
: {}),
}
: undefined;
beginLocalDispatch({ preparingWorktree: false });
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
@@ -2913,19 +3089,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
titleSeed: title,
runtimeMode,
interactionMode,
...(bootstrap ? { bootstrap } : {}),
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
})().catch(async (err: unknown) => {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: threadIdForSend,
})
.catch(() => undefined);
}
if (
!turnStartSucceeded &&
promptRef.current.length === 0 &&
@@ -4016,7 +4184,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
onPaste={onComposerPaste}
placeholder={
isComposerApprovalState
? "Resolve this approval request to continue"
? (activePendingApproval?.detail ??
"Resolve this approval request to continue")
: activePendingProgress
? "Type your own answer, or leave this blank to use the selected option"
: showPlanFollowUpPrompt && activeProposedPlan
@@ -4249,6 +4418,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
<PullRequestThreadDialog
key={pullRequestDialogState.key}
open
threadId={activeThread.id}
cwd={activeProject?.cwd ?? null}
initialReference={pullRequestDialogState.initialReference}
onOpenChange={(open) => {
@@ -4283,34 +4453,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
</div>
{/* end horizontal flex container */}
{(() => {
if (!terminalState.terminalOpen || !activeProject) {
return null;
}
return (
<ThreadTerminalDrawer
key={activeThread.id}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={addTerminalContextToDraft}
/>
);
})()}
{mountedTerminalThreadIds.map((mountedThreadId) => (
<PersistentThreadTerminalDrawer
key={mountedThreadId}
threadId={mountedThreadId}
visible={mountedThreadId === activeThreadId && terminalState.terminalOpen}
launchContext={
mountedThreadId === activeThreadId ? (activeTerminalLaunchContext ?? null) : null
}
focusRequestId={mountedThreadId === activeThreadId ? terminalFocusRequestId : 0}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
{expandedImage && expandedImageItem && (
<div
+3 -3
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -189,8 +189,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
const gitStatusQuery = useQuery(gitStatusQueryOptions(activeCwd ?? null));
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -0,0 +1,238 @@
import { ThreadId } from "@t3tools/contracts";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const THREAD_A = ThreadId.makeUnsafe("thread-a");
const THREAD_B = ThreadId.makeUnsafe("thread-b");
const GIT_CWD = "/repo/project";
const BRANCH_NAME = "feature/toast-scope";
const {
invalidateGitQueriesSpy,
invalidateGitStatusQuerySpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
toastCloseSpy,
toastPromiseSpy,
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
invalidateGitStatusQuerySpy: vi.fn(() => Promise.resolve()),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
toastCloseSpy: vi.fn(),
toastPromiseSpy: vi.fn(),
toastUpdateSpy: vi.fn(),
}));
vi.mock("@tanstack/react-query", async () => {
const actual =
await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
return {
...actual,
useIsMutating: vi.fn(() => 0),
useMutation: vi.fn((options: { __kind?: string }) => {
if (options.__kind === "run-stacked-action") {
return {
mutateAsync: runStackedActionMutateAsyncSpy,
isPending: false,
};
}
if (options.__kind === "pull") {
return {
mutateAsync: vi.fn(),
isPending: false,
};
}
return {
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
};
}),
useQuery: vi.fn((options: { queryKey?: string[] }) => {
if (options.queryKey?.[0] === "git-status") {
return {
data: {
branch: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
};
}
if (options.queryKey?.[0] === "git-branches") {
return {
data: {
isRepo: true,
hasOriginRemote: true,
branches: [
{
name: BRANCH_NAME,
current: true,
isDefault: false,
worktreePath: null,
},
],
},
error: null,
};
}
return { data: null, error: null };
}),
useQueryClient: vi.fn(() => ({})),
};
});
vi.mock("~/components/ui/toast", () => ({
toastManager: {
add: toastAddSpy,
close: toastCloseSpy,
promise: toastPromiseSpy,
update: toastUpdateSpy,
},
}));
vi.mock("~/editorPreferences", () => ({
openInPreferredEditor: vi.fn(),
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitBranchesQueryOptions: vi.fn(() => ({ queryKey: ["git-branches"] })),
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
runStackedAction: vi.fn(() => ["run-stacked-action"]),
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
gitStatusQueryOptions: vi.fn(() => ({ queryKey: ["git-status"] })),
invalidateGitQueries: invalidateGitQueriesSpy,
invalidateGitStatusQuery: invalidateGitStatusQuerySpy,
}));
vi.mock("~/lib/utils", async () => {
const actual = await vi.importActual<typeof import("~/lib/utils")>("~/lib/utils");
return {
...actual,
newCommandId: vi.fn(() => "command-1"),
randomUUID: vi.fn(() => "action-1"),
};
});
vi.mock("~/nativeApi", () => ({
readNativeApi: vi.fn(() => null),
}));
vi.mock("~/store", () => ({
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
threads: [
{ id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
{ id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
],
}),
}));
vi.mock("~/terminal-links", () => ({
resolvePathLinkTarget: vi.fn(),
}));
import GitActionsControl from "./GitActionsControl";
function findButtonByText(text: string): HTMLButtonElement | null {
return (Array.from(document.querySelectorAll("button")).find((button) =>
button.textContent?.includes(text),
) ?? null) as HTMLButtonElement | null;
}
function Harness() {
const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
return (
<>
<button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
Switch thread
</button>
<GitActionsControl gitCwd={GIT_CWD} activeThreadId={activeThreadId} />
</>
);
}
describe("GitActionsControl thread-scoped progress toast", () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
document.body.innerHTML = "";
});
it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
vi.useFakeTimers();
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<Harness />, { container: host });
try {
const quickActionButton = findButtonByText("Push & create PR");
expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy();
if (!(quickActionButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Push & create PR"');
}
quickActionButton.click();
expect(toastAddSpy).toHaveBeenCalledWith(
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
const switchThreadButton = findButtonByText("Switch thread");
expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
if (!(switchThreadButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Switch thread"');
}
switchThreadButton.click();
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
} finally {
await screen.unmount();
host.remove();
}
});
});
@@ -6,12 +6,16 @@ import {
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveLiveThreadBranchUpdate,
resolveQuickAction,
summarizeGitResult,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasWorkingTreeChanges: false,
workingTree: {
@@ -162,7 +166,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
}),
false,
);
assert.deepInclude(quick, { kind: "run_action", action: "commit_push", label: "Push" });
assert.deepInclude(quick, { kind: "run_action", action: "push", label: "Push" });
});
it("buildMenuItems enables push and keeps open PR available", () => {
@@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
label: "Push & create PR",
});
});
@@ -585,7 +589,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
action: "push",
label: "Push",
disabled: false,
});
@@ -632,7 +636,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
label: "Push & create PR",
disabled: false,
});
@@ -801,9 +805,12 @@ describe("when: branch has no upstream configured", () => {
describe("requiresDefaultBranchConfirmation", () => {
it("requires confirmation for push actions on default branch", () => {
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
assert.isTrue(requiresDefaultBranchConfirmation("push", true));
assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
assert.isFalse(requiresDefaultBranchConfirmation("commit_push", false));
assert.isFalse(requiresDefaultBranchConfirmation("push", false));
});
});
@@ -855,26 +862,44 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
it("shows only push progress for explicit push actions", () => {
const stages = buildGitActionProgressStages({
action: "commit_push",
action: "push",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
hasWorkingTreeChanges: false,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
});
it("skips commit stages for create-pr flow when push-only is forced", () => {
it("shows push and PR progress for create-pr actions that still need a push", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
action: "create_pr",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
hasWorkingTreeChanges: false,
pushTarget: "origin/feature/test",
shouldPushBeforePr: true,
});
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
assert.deepEqual(stages, [
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("shows only PR progress when create-pr can skip the push", () => {
const stages = buildGitActionProgressStages({
action: "create_pr",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: false,
shouldPushBeforePr: false,
});
assert.deepEqual(stages, [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("includes commit stages for commit+push when working tree is dirty", () => {
@@ -890,99 +915,110 @@ describe("buildGitActionProgressStages", () => {
"Pushing to origin/feature/test...",
]);
});
it("includes granular PR stages for commit+push+PR actions", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
hasCustomCommitMessage: true,
hasWorkingTreeChanges: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, [
"Committing...",
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
});
describe("summarizeGitResult", () => {
it("returns commit-focused toast for commit action", () => {
const result = summarizeGitResult({
action: "commit",
branch: { status: "skipped_not_requested" },
describe("resolveThreadBranchUpdate", () => {
it("returns a branch update when the action created a new branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push_pr",
branch: {
status: "created",
name: "feature/fix-toast-copy",
},
commit: {
status: "created",
commitSha: "0123456789abcdef",
subject: "feat: add optimistic UI for git action button",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "skipped_not_requested" },
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
toast: {
title: "Pushed 89abcde to origin/feature/fix-toast-copy",
cta: { kind: "none" },
},
});
assert.deepEqual(result, {
title: "Committed 0123456",
description: "feat: add optimistic UI for git action button",
assert.deepEqual(update, {
branch: "feature/fix-toast-copy",
});
});
it("returns push-focused toast for push action", () => {
const result = summarizeGitResult({
it("returns null when the action stayed on the existing branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push",
branch: { status: "skipped_not_requested" },
branch: {
status: "skipped_not_requested",
},
commit: {
status: "created",
commitSha: "abcdef0123456789",
subject: "fix: tighten quick action tooltip hover handling",
},
push: {
status: "pushed",
branch: "foo",
upstreamBranch: "origin/foo",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
toast: {
title: "Pushed 89abcde to origin/feature/fix-toast-copy",
cta: { kind: "none" },
},
});
assert.deepEqual(result, {
title: "Pushed abcdef0 to origin/foo",
description: "fix: tighten quick action tooltip hover handling",
assert.equal(update, null);
});
});
describe("resolveLiveThreadBranchUpdate", () => {
it("returns a branch update when live git status differs from stored thread metadata", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
gitStatus: status({ branch: "effect-atom" }),
});
assert.deepEqual(update, {
branch: "effect-atom",
});
});
it("returns PR-focused toast for created PR action", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: ship github shortcuts",
},
push: {
status: "pushed",
branch: "foo",
},
pr: {
status: "created",
number: 42,
title: "feat: ship github shortcuts and improve PR CTA in success toast",
},
it("returns null when live git status is unavailable", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
gitStatus: null,
});
assert.deepEqual(result, {
title: "Created PR #42",
description: "feat: ship github shortcuts and improve PR CTA in success toast",
});
assert.equal(update, null);
});
it("truncates long description text", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "short subject",
},
push: { status: "pushed", branch: "foo" },
pr: {
status: "created",
number: 99,
title:
"feat: this title is intentionally extremely long so we can validate that toast descriptions are truncated with an ellipsis suffix",
},
it("returns null when the stored thread branch already matches git status", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: "effect-atom" }),
});
assert.deepEqual(result, {
title: "Created PR #99",
description: "feat: this title is intentionally extremely long so we can validate t...",
assert.equal(update, null);
});
it("returns null when git status is detached HEAD but the thread already has a branch", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: null }),
});
assert.equal(update, null);
});
});
@@ -31,83 +31,48 @@ export interface DefaultBranchActionDialogCopy {
continueLabel: string;
}
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
return sha.slice(0, SHORT_SHA_LENGTH);
}
function truncateText(
value: string | undefined,
maxLength = TOAST_DESCRIPTION_MAX,
): string | undefined {
if (!value) return undefined;
if (value.length <= maxLength) return value;
if (maxLength <= 3) return "...".slice(0, maxLength);
return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
}
export type DefaultBranchConfirmableAction =
| "push"
| "create_pr"
| "commit_push"
| "commit_push_pr";
export function buildGitActionProgressStages(input: {
action: GitStackedAction;
hasCustomCommitMessage: boolean;
hasWorkingTreeChanges: boolean;
forcePushOnly?: boolean;
pushTarget?: string;
featureBranch?: boolean;
shouldPushBeforePr?: boolean;
}): string[] {
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
const shouldIncludeCommitStages =
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
const prStages = [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
];
if (input.action === "push") {
return [pushStage];
}
if (input.action === "create_pr") {
return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages;
}
const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges;
const commitStages = !shouldIncludeCommitStages
? []
: input.hasCustomCommitMessage
? ["Committing..."]
: ["Generating commit message...", "Committing..."];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
if (input.action === "commit") {
return [...branchStages, ...commitStages];
}
if (input.action === "commit_push") {
return [...branchStages, ...commitStages, pushStage];
}
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
}
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
export function summarizeGitResult(result: GitRunStackedActionResult): {
title: string;
description?: string;
} {
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
return withDescription(title, truncateText(result.pr.title));
}
if (result.push.status === "pushed") {
const shortSha = shortenSha(result.commit.commitSha);
const branch = result.push.upstreamBranch ?? result.push.branch;
const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
const branchPart = branch ? ` to ${branch}` : "";
return withDescription(
`Pushed${pushedCommitPart}${branchPart}`,
truncateText(result.commit.subject),
);
}
if (result.commit.status === "created") {
const shortSha = shortenSha(result.commit.commitSha);
const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
return withDescription(title, truncateText(result.commit.subject));
}
return { title: "Done" };
return [...branchStages, ...commitStages, pushStage, ...prStages];
}
export function buildMenuItems(
@@ -250,13 +215,18 @@ export function resolveQuickAction(
};
}
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
};
}
@@ -279,13 +249,18 @@ export function resolveQuickAction(
if (isAhead) {
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
};
}
@@ -306,7 +281,12 @@ export function requiresDefaultBranchConfirmation(
isDefaultBranch: boolean,
): boolean {
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
return (
action === "push" ||
action === "create_pr" ||
action === "commit_push" ||
action === "commit_push_pr"
);
}
export function resolveDefaultBranchActionDialogCopy(input: {
@@ -317,7 +297,7 @@ export function resolveDefaultBranchActionDialogCopy(input: {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
if (input.action === "commit_push") {
if (input.action === "push" || input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
@@ -346,5 +326,38 @@ export function resolveDefaultBranchActionDialogCopy(input: {
};
}
export function resolveThreadBranchUpdate(
result: GitRunStackedActionResult,
): { branch: string } | null {
if (result.branch.status !== "created" || !result.branch.name) {
return null;
}
return {
branch: result.branch.name,
};
}
export function resolveLiveThreadBranchUpdate(input: {
threadBranch: string | null;
gitStatus: GitStatusResult | null;
}): { branch: string | null } | null {
if (!input.gitStatus) {
return null;
}
if (input.gitStatus.branch === null && input.threadBranch !== null) {
return null;
}
if (input.threadBranch === input.gitStatus.branch) {
return null;
}
return {
branch: input.gitStatus.branch,
};
}
// Re-export from shared for backwards compatibility in this module's exports
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
+175 -157
View File
@@ -1,5 +1,6 @@
import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
ThreadId,
@@ -17,8 +18,9 @@ import {
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveDefaultBranchActionDialogCopy,
resolveLiveThreadBranchUpdate,
resolveQuickAction,
summarizeGitResult,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
@@ -36,20 +38,20 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import { toastManager, type ThreadToastData } from "~/components/ui/toast";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
invalidateGitStatusQuery,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
import { useStore } from "~/store";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -61,7 +63,6 @@ interface PendingDefaultBranchAction {
branchName: string;
includesCommit: boolean;
commitMessage?: string;
forcePushOnlyProgress: boolean;
onConfirmed?: () => void;
filePaths?: string[];
}
@@ -70,6 +71,7 @@ type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
toastId: GitActionToastId;
toastData: ThreadToastData | undefined;
actionId: string;
title: string;
phaseStartedAtMs: number | null;
@@ -82,12 +84,10 @@ interface ActiveGitActionProgress {
interface RunGitActionWithToastInput {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}
@@ -196,7 +196,9 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
if (quickAction.action === "push" || quickAction.action === "commit_push") {
return <CloudUploadIcon className={iconClassName} />;
}
return <GitHubIcon className={iconClassName} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
@@ -208,6 +210,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const activeServerThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -216,6 +222,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
const updateActiveProgressToast = useCallback(() => {
const progress = activeGitActionProgressRef.current;
@@ -227,26 +234,52 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progress.title,
description: resolveProgressDescription(progress),
timeout: 0,
data: threadToastData,
data: progress.toastData,
});
}, [threadToastData]);
}, []);
const persistThreadBranchSync = useCallback(
(branch: string | null) => {
if (!activeThreadId || !activeServerThread || activeServerThread.branch === branch) {
return;
}
const worktreePath = activeServerThread.worktreePath;
const api = readNativeApi();
if (api) {
void api.orchestration
.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch,
worktreePath,
})
.catch(() => undefined);
}
setThreadBranch(activeThreadId, branch, worktreePath);
},
[activeServerThread, activeThreadId, setThreadBranch],
);
const syncThreadBranchAfterGitAction = useCallback(
(result: GitRunStackedActionResult) => {
const branchUpdate = resolveThreadBranchUpdate(result);
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch);
},
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
const gitStatusForActions = gitStatus;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
@@ -267,12 +300,31 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
useEffect(() => {
if (isGitActionRunning) {
return;
}
const branchUpdate = resolveLiveThreadBranchUpdate({
threadBranch: activeServerThread?.branch ?? null,
gitStatus: gitStatusForActions,
});
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch);
}, [
activeServerThread?.branch,
gitStatusForActions,
isGitActionRunning,
persistThreadBranchSync,
]);
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
return gitStatusForActions?.isDefaultBranch ?? false;
}, [gitStatusForActions?.isDefaultBranch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
@@ -336,31 +388,36 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}, [gitStatusForActions, threadToastData]);
const runGitActionWithToast = useEffectEvent(
runGitActionWithToast = useEffectEvent(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
featureBranch = false,
isDefaultBranchOverride,
progressToastId,
filePaths,
}: RunGitActionWithToastInput) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch =
isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
const actionCanCommit =
action === "commit" || action === "commit_push" || action === "commit_push_pr";
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
actionCanCommit &&
(action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (action !== "commit_push" && action !== "commit_push_pr") {
if (
action !== "push" &&
action !== "create_pr" &&
action !== "commit_push" &&
action !== "commit_push_pr"
) {
return;
}
setPendingDefaultBranchAction({
@@ -368,7 +425,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
});
@@ -380,9 +436,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
featureBranch,
shouldPushBeforePr:
action === "create_pr" &&
(!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
});
const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
const actionId = randomUUID();
const resolvedProgressToastId =
progressToastId ??
@@ -391,11 +450,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
activeGitActionProgressRef.current = {
toastId: resolvedProgressToastId,
toastData: scopedToastData,
actionId,
title: progressStages[0] ?? "Running git action...",
phaseStartedAtMs: null,
@@ -411,7 +471,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
}
@@ -483,124 +543,97 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
try {
const result = await promise;
activeGitActionProgressRef.current = null;
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =
actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
(!actionIsDefaultBranch ||
result.pr.status === "created" ||
result.pr.status === "opened_existing");
const shouldOfferCreatePrCta =
action === "commit_push" &&
!prUrl &&
result.push.status === "pushed" &&
!actionIsDefaultBranch;
syncThreadBranchAfterGitAction(result);
const closeResultToast = () => {
toastManager.close(resolvedProgressToastId);
};
toastManager.update(resolvedProgressToastId, {
const toastCta = result.toast.cta;
let toastActionProps: {
children: string;
onClick: () => void;
} | null = null;
if (toastCta.kind === "run_action") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: toastCta.action.kind,
});
},
};
} else if (toastCta.kind === "open_pr") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(toastCta.url);
},
};
}
const successToastBase = {
type: "success",
title: resultToast.title,
description: resultToast.description,
title: result.toast.title,
description: result.toast.description,
timeout: 0,
data: {
...threadToastData,
...scopedToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta
? {
actionProps: {
children: "Push",
onClick: () => {
void runGitActionWithToast({
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "View PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(prUrl);
},
},
}
: shouldOfferCreatePrCta
? {
actionProps: {
children: "Create PR",
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: "commit_push_pr",
forcePushOnlyProgress: true,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
}
: {}),
});
} as const;
if (toastActionProps) {
toastManager.update(resolvedProgressToastId, {
...successToastBase,
actionProps: toastActionProps,
});
} else {
toastManager.update(resolvedProgressToastId, successToastBase);
}
} catch (err) {
activeGitActionProgressRef.current = null;
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
data: scopedToastData,
});
}
},
);
const continuePendingDefaultBranchAction = useCallback(() => {
const continuePendingDefaultBranchAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
const checkoutFeatureBranchAndContinuePendingAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const runDialogActionOnNewBranch = useCallback(() => {
const runDialogActionOnNewBranch = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
@@ -616,9 +649,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
};
const runQuickAction = useCallback(() => {
const runQuickAction = () => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
return;
@@ -656,31 +689,28 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
};
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "commit_push_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
},
[openExistingPr, setIsCommitDialogOpen],
);
const openDialogForMenuItem = (item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "create_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
};
const runDialogAction = useCallback(() => {
const runDialogAction = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
@@ -692,14 +722,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
});
}, [
allSelected,
dialogCommitMessage,
isCommitDialogOpen,
selectedFiles,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
};
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -778,7 +801,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
if (open) void invalidateGitStatusQuery(queryClient, gitCwd);
}}
>
<MenuTrigger
@@ -842,11 +865,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
+101
View File
@@ -310,6 +310,107 @@ export const AntigravityIcon: Icon = (props) => (
</svg>
);
export const IntelliJIdeaIcon: Icon = (props) => {
const id = useId();
const gradientAId = `${id}-idea-a`;
const gradientBId = `${id}-idea-b`;
const gradientCId = `${id}-idea-c`;
const gradientDId = `${id}-idea-d`;
return (
<svg {...props} viewBox="0 0 70 70" fill="none">
<defs>
<linearGradient
id={gradientAId}
x1="0.7898"
y1="40.0893"
x2="33.3172"
y2="40.0893"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.2581" stopColor="#F97A12" />
<stop offset="0.4591" stopColor="#B07B58" />
<stop offset="0.7241" stopColor="#577BAE" />
<stop offset="0.9105" stopColor="#1E7CE5" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientBId}
x1="25.7674"
y1="24.88"
x2="79.424"
y2="54.57"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#F97A12" />
<stop offset="0.07179946" stopColor="#CB7A3E" />
<stop offset="0.1541" stopColor="#9E7B6A" />
<stop offset="0.242" stopColor="#757B91" />
<stop offset="0.3344" stopColor="#537BB1" />
<stop offset="0.4324" stopColor="#387CCC" />
<stop offset="0.5381" stopColor="#237CE0" />
<stop offset="0.6552" stopColor="#147CEF" />
<stop offset="0.7925" stopColor="#0B7CF7" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientCId}
x1="63.2277"
y1="42.9153"
x2="48.2903"
y2="-1.7191"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FE315D" />
<stop offset="0.07840246" stopColor="#CB417E" />
<stop offset="0.1601" stopColor="#9E4E9B" />
<stop offset="0.2474" stopColor="#755BB4" />
<stop offset="0.3392" stopColor="#5365CA" />
<stop offset="0.4365" stopColor="#386DDB" />
<stop offset="0.5414" stopColor="#2374E9" />
<stop offset="0.6576" stopColor="#1478F3" />
<stop offset="0.794" stopColor="#0B7BF8" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientDId}
x1="10.7204"
y1="16.473"
x2="55.5237"
y2="90.58"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FE315D" />
<stop offset="0.04023279" stopColor="#F63462" />
<stop offset="0.1037" stopColor="#DF3A71" />
<stop offset="0.1667" stopColor="#C24383" />
<stop offset="0.2912" stopColor="#AD4A91" />
<stop offset="0.5498" stopColor="#755BB4" />
<stop offset="0.9175" stopColor="#1D76ED" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
</defs>
<polygon points="17.7,54.6 0.8,41.2 9.2,25.6 33.3,35" fill={`url(#${gradientAId})`} />
<path
d="M70 18.7 68.7 59.2 41.8 70 25.6 59.6 49.3 35 38.9 12.3 48.2 1.1Z"
fill={`url(#${gradientBId})`}
/>
<polygon points="70,18.7 48.7,43.9 38.9,12.3 48.2,1.1" fill={`url(#${gradientCId})`} />
<path
d="M33.7 58.1 5.6 68.3 10.1 52.5 16 33.1 0 27.7 10.1 0 32.1 2.7 53.7 27.4Z"
fill={`url(#${gradientDId})`}
/>
<rect x="13.7" y="13.5" width="43.2" height="43.2" fill="#000" />
<rect x="17.7" y="48.6" width="16.2" height="2.7" fill="#fff" />
<path d="M29.4 22.4v-3.3h-9v3.3h2.6v11.3h-2.6V37h9v-3.3h-2.5V22.4h2.5Z" fill="#fff" />
<path
d="M38 37.3c-1.4 0-2.6-.3-3.5-.8-.9-.5-1.7-1.2-2.3-1.9l2.5-2.8c.5.6 1 1 1.5 1.3.5.3 1.1.5 1.7.5.7 0 1.3-.2 1.8-.7.4-.5.6-1.2.6-2.3V19.1h4v11.7c0 1.1-.1 2-.4 2.8-.3.8-.7 1.4-1.3 2-.5.5-1.2 1-2 1.2-.8.3-1.6.5-2.6.5Z"
fill="#fff"
/>
</svg>
);
};
export const OpenCodeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clipPath="url(#opencode__clip0_1311_94969)">
@@ -1,6 +1,7 @@
import "../index.css";
import {
DEFAULT_SERVER_SETTINGS,
ORCHESTRATION_WS_METHODS,
type MessageId,
type OrchestrationReadModel,
@@ -56,7 +57,14 @@ function createBaseServerConfig(): ServerConfig {
},
],
availableEditors: [],
observability: {
logsDirectoryPath: "/repo/project/.t3/logs",
localTracingEnabled: true,
otlpTracesEnabled: false,
otlpMetricsEnabled: false,
},
settings: {
...DEFAULT_SERVER_SETTINGS,
enableAssistantStreaming: false,
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
@@ -157,11 +165,16 @@ function resolveWsRpc(tag: string): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
@@ -1,4 +1,4 @@
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
import type { GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,6 +24,7 @@ import { Spinner } from "./ui/spinner";
interface PullRequestThreadDialogProps {
open: boolean;
threadId: ThreadId;
cwd: string | null;
initialReference: string | null;
onOpenChange: (open: boolean) => void;
@@ -32,6 +33,7 @@ interface PullRequestThreadDialogProps {
export function PullRequestThreadDialog({
open,
threadId,
cwd,
initialReference,
onOpenChange,
@@ -130,6 +132,7 @@ export function PullRequestThreadDialog({
const result = await preparePullRequestThreadMutation.mutateAsync({
reference: parsedReference,
mode,
...(mode === "worktree" ? { threadId } : {}),
});
await onPrepared({
branch: result.branch,
@@ -147,6 +150,7 @@ export function PullRequestThreadDialog({
parsedReference,
preparePullRequestThreadMutation,
resolvedPullRequest,
threadId,
],
);
+88 -53
View File
@@ -11,6 +11,7 @@ import {
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
@@ -45,10 +46,12 @@ describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
@@ -164,6 +167,68 @@ describe("resolveSidebarNewThreadEnvMode", () => {
});
});
describe("resolveSidebarNewThreadSeedContext", () => {
it("inherits the active server thread context when creating a new thread in the same project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
branch: "effect-atom",
worktreePath: null,
envMode: "local",
});
});
it("prefers the active draft thread context when it matches the target project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: {
projectId: "project-1",
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
},
}),
).toEqual({
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
});
});
it("falls back to the default env mode when there is no matching active thread context", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-2",
defaultEnvMode: "worktree",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
envMode: "worktree",
});
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
@@ -259,17 +324,14 @@ describe("getVisibleSidebarThreadIds", () => {
expect(
getVisibleSidebarThreadIds([
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
{ id: ThreadId.makeUnsafe("thread-10") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-12"),
ThreadId.makeUnsafe("thread-11"),
ThreadId.makeUnsafe("thread-10"),
],
},
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-8") },
{ id: ThreadId.makeUnsafe("thread-6") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-8"), ThreadId.makeUnsafe("thread-6")],
},
]),
).toEqual([
@@ -286,17 +348,14 @@ describe("getVisibleSidebarThreadIds", () => {
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-hidden-2"),
ThreadId.makeUnsafe("thread-hidden-1"),
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
@@ -337,10 +396,12 @@ describe("isContextMenuPointerDown", () => {
describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
@@ -353,9 +414,11 @@ describe("resolveThreadStatusPill", () => {
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
@@ -363,9 +426,10 @@ describe("resolveThreadStatusPill", () => {
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
@@ -374,8 +438,6 @@ describe("resolveThreadStatusPill", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
@@ -385,26 +447,14 @@ describe("resolveThreadStatusPill", () => {
resolveThreadStatusPill({
thread: {
...baseThread,
hasActionableProposedPlan: true,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: null,
implementationThreadId: null,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
@@ -415,25 +465,12 @@ describe("resolveThreadStatusPill", () => {
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: "2026-03-09T10:06:00.000Z",
implementationThreadId: "thread-implement" as never,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
@@ -452,8 +489,6 @@ describe("resolveThreadStatusPill", () => {
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
+56 -23
View File
@@ -1,12 +1,8 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import type { SidebarThreadSummary, Thread } from "../types";
import { cn } from "../lib/utils";
import {
findLatestProposedPlan,
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
import { isLatestTurnSettled } 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;
@@ -47,8 +43,13 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
};
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
SidebarThreadSummary,
| "hasActionableProposedPlan"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "interactionMode"
| "latestTurn"
| "session"
> & {
lastVisitedAt?: string | undefined;
};
@@ -161,6 +162,46 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function resolveSidebarNewThreadSeedContext(input: {
projectId: string;
defaultEnvMode: SidebarNewThreadEnvMode;
activeThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
} | null;
activeDraftThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
envMode: SidebarNewThreadEnvMode;
} | null;
}): {
branch?: string | null;
worktreePath?: string | null;
envMode: SidebarNewThreadEnvMode;
} {
if (input.activeDraftThread?.projectId === input.projectId) {
return {
branch: input.activeDraftThread.branch,
worktreePath: input.activeDraftThread.worktreePath,
envMode: input.activeDraftThread.envMode,
};
}
if (input.activeThread?.projectId === input.projectId) {
return {
branch: input.activeThread.branch,
worktreePath: input.activeThread.worktreePath,
envMode: input.activeThread.worktreePath ? "worktree" : "local",
};
}
return {
envMode: input.defaultEnvMode,
};
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
@@ -192,15 +233,11 @@ export function orderItemsByPreferredIds<TItem, TId>(input: {
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
renderedThreadIds: readonly TThreadId[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
);
}
@@ -273,12 +310,10 @@ export function resolveThreadRowClassName(input: {
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
const { thread } = input;
if (hasPendingApprovals) {
if (thread.hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
@@ -287,7 +322,7 @@ export function resolveThreadStatusPill(input: {
};
}
if (hasPendingUserInput) {
if (thread.hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
@@ -315,12 +350,10 @@ export function resolveThreadStatusPill(input: {
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
!thread.hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
hasActionableProposedPlan(
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
);
thread.hasActionableProposedPlan;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
File diff suppressed because it is too large. Load diff
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import {
resolveTerminalSelectionActionPosition,
selectPendingTerminalEventEntries,
selectTerminalEventEntriesAfterSnapshot,
shouldHandleTerminalSelectionMouseUp,
terminalSelectionActionDelayForClickCount,
} from "./ThreadTerminalDrawer";
@@ -72,4 +74,64 @@ describe("resolveTerminalSelectionActionPosition", () => {
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
});
it("replays only terminal events newer than the open snapshot", () => {
expect(
selectTerminalEventEntriesAfterSnapshot(
[
{
id: 1,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:00.000Z",
type: "output",
data: "before",
},
},
{
id: 2,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:01.000Z",
type: "output",
data: "after",
},
},
],
"2026-04-02T20:00:00.500Z",
).map((entry) => entry.id),
).toEqual([2]);
});
it("applies only terminal events that have not already been consumed", () => {
expect(
selectPendingTerminalEventEntries(
[
{
id: 1,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:00.000Z",
type: "output",
data: "one",
},
},
{
id: 2,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:01.000Z",
type: "output",
data: "two",
},
},
],
1,
).map((entry) => entry.id),
).toEqual([2]);
});
});
+255 -80
View File
@@ -1,12 +1,18 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type ThreadId } from "@t3tools/contracts";
import { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import {
type TerminalEvent,
type TerminalSessionSnapshot,
type ThreadId,
} from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
@@ -27,6 +33,11 @@ import {
type ThreadTerminalGroup,
} from "../types";
import { readNativeApi } from "~/nativeApi";
import {
normalizeRunningPorts,
selectTerminalEventEntries,
useTerminalStateStore,
} from "../terminalStateStore";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -47,6 +58,59 @@ function writeSystemMessage(terminal: Terminal, message: string): void {
terminal.write(`\r\n[terminal] ${message}\r\n`);
}
function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void {
terminal.write("\u001bc");
if (snapshot.history.length > 0) {
terminal.write(snapshot.history);
}
}
export function selectTerminalEventEntriesAfterSnapshot(
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
snapshotUpdatedAt: string,
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
return entries.filter((entry) => entry.event.createdAt > snapshotUpdatedAt);
}
export function selectPendingTerminalEventEntries(
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
lastAppliedTerminalEventId: number,
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
}
interface TerminalRuntimeStatus {
label: string;
primaryWebPort: number | null;
extraWebPortCount: number;
}
function terminalRuntimeStatus(
terminalId: string,
runningTerminalIds: Set<string>,
runningTerminalPorts: Record<string, number[]>,
): TerminalRuntimeStatus | null {
if (!runningTerminalIds.has(terminalId)) {
return null;
}
const runningPorts = normalizeRunningPorts(runningTerminalPorts[terminalId]);
const primaryWebPort = runningPorts[0] ?? null;
const extraWebPortCount = runningPorts.length > 1 ? runningPorts.length - 1 : 0;
const label =
runningPorts.length === 0
? "Terminal process running"
: runningPorts.length === 1
? `Open web server: http://localhost:${primaryWebPort}`
: `Open web server: http://localhost:${primaryWebPort} (detected web ports: ${runningPorts.join(", ")})`;
return {
label,
primaryWebPort,
extraWebPortCount,
};
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
@@ -185,6 +249,7 @@ interface TerminalViewportProps {
terminalId: string;
terminalLabel: string;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
onSessionExited: () => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
@@ -199,6 +264,7 @@ function TerminalViewport({
terminalId,
terminalLabel,
cwd,
worktreePath,
runtimeEnv,
onSessionExited,
onAddTerminalContext,
@@ -210,27 +276,21 @@ function TerminalViewport({
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const onSessionExitedRef = useRef(onSessionExited);
const onAddTerminalContextRef = useRef(onAddTerminalContext);
const terminalLabelRef = useRef(terminalLabel);
const hasHandledExitRef = useRef(false);
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
const selectionGestureActiveRef = useRef(false);
const selectionActionRequestIdRef = useRef(0);
const selectionActionOpenRef = useRef(false);
const selectionActionTimerRef = useRef<number | null>(null);
useEffect(() => {
onSessionExitedRef.current = onSessionExited;
}, [onSessionExited]);
useEffect(() => {
onAddTerminalContextRef.current = onAddTerminalContext;
}, [onAddTerminalContext]);
useEffect(() => {
terminalLabelRef.current = terminalLabel;
}, [terminalLabel]);
const lastAppliedTerminalEventIdRef = useRef(0);
const terminalHydratedRef = useRef(false);
const handleSessionExited = useEffectEvent(() => {
onSessionExited();
});
const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
useEffect(() => {
const mount = containerRef.current;
@@ -297,7 +357,7 @@ function TerminalViewport({
position,
selection: {
terminalId,
terminalLabel: terminalLabelRef.current,
terminalLabel: readTerminalLabel(),
lineStart,
lineEnd,
text: normalizedText,
@@ -324,7 +384,7 @@ function TerminalViewport({
if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
return;
}
onAddTerminalContextRef.current(nextAction.selection);
handleAddTerminalContext(nextAction.selection);
terminalRef.current?.clearSelection();
terminalRef.current?.focus();
} finally {
@@ -469,43 +529,15 @@ function TerminalViewport({
attributeFilter: ["class", "style"],
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const unsubscribe = api?.terminal.onEvent((event) => {
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const applyTerminalEvent = (event: TerminalEvent) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (!activeTerminal) {
return;
}
if (event.type === "activity") {
return;
}
if (event.type === "output") {
activeTerminal.write(event.data);
@@ -516,10 +548,7 @@ function TerminalViewport({
if (event.type === "started" || event.type === "restarted") {
hasHandledExitRef.current = false;
clearSelectionAction();
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
}
writeTerminalSnapshot(activeTerminal, event.snapshot);
return;
}
@@ -535,30 +564,113 @@ function TerminalViewport({
return;
}
if (event.type === "exited") {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
if (hasHandledExitRef.current) {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
if (hasHandledExitRef.current) {
return;
}
hasHandledExitRef.current = true;
window.setTimeout(() => {
if (!hasHandledExitRef.current) {
return;
}
hasHandledExitRef.current = true;
window.setTimeout(() => {
if (!hasHandledExitRef.current) {
return;
}
onSessionExitedRef.current();
}, 0);
handleSessionExited();
}, 0);
};
const applyPendingTerminalEvents = (
terminalEventEntries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
) => {
const pendingEntries = selectPendingTerminalEventEntries(
terminalEventEntries,
lastAppliedTerminalEventIdRef.current,
);
if (pendingEntries.length === 0) {
return;
}
for (const entry of pendingEntries) {
applyTerminalEvent(entry.event);
}
lastAppliedTerminalEventIdRef.current =
pendingEntries.at(-1)?.id ?? lastAppliedTerminalEventIdRef.current;
};
const unsubscribeTerminalEvents = useTerminalStateStore.subscribe((state, previousState) => {
if (!terminalHydratedRef.current) {
return;
}
const previousLastEntryId =
selectTerminalEventEntries(
previousState.terminalEventEntriesByKey,
threadId,
terminalId,
).at(-1)?.id ?? 0;
const nextEntries = selectTerminalEventEntries(
state.terminalEventEntriesByKey,
threadId,
terminalId,
);
const nextLastEntryId = nextEntries.at(-1)?.id ?? 0;
if (nextLastEntryId === previousLastEntryId) {
return;
}
applyPendingTerminalEvents(nextEntries);
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
...(worktreePath !== undefined ? { worktreePath } : {}),
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
writeTerminalSnapshot(activeTerminal, snapshot);
const bufferedEntries = selectTerminalEventEntries(
useTerminalStateStore.getState().terminalEventEntriesByKey,
threadId,
terminalId,
);
const replayEntries = selectTerminalEventEntriesAfterSnapshot(
bufferedEntries,
snapshot.updatedAt,
);
for (const entry of replayEntries) {
applyTerminalEvent(entry.event);
}
lastAppliedTerminalEventIdRef.current = bufferedEntries.at(-1)?.id ?? 0;
terminalHydratedRef.current = true;
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const fitTimer = window.setTimeout(() => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
@@ -582,8 +694,10 @@ function TerminalViewport({
return () => {
disposed = true;
terminalHydratedRef.current = false;
lastAppliedTerminalEventIdRef.current = 0;
unsubscribeTerminalEvents();
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
selectionDisposable.dispose();
terminalLinksDisposable.dispose();
@@ -646,12 +760,16 @@ function TerminalViewport({
interface ThreadTerminalDrawerProps {
threadId: ThreadId;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
visible?: boolean;
height: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
runningTerminalIds: string[];
runningTerminalPorts: Record<string, number[]>;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
@@ -696,12 +814,16 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
export default function ThreadTerminalDrawer({
threadId,
cwd,
worktreePath,
runtimeEnv,
visible = true,
height,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
runningTerminalIds,
runningTerminalPorts,
focusRequestId,
onSplitTerminal,
onNewTerminal,
@@ -825,6 +947,10 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const runningTerminalIdSet = useMemo(
() => new Set(runningTerminalIds.map((terminalId) => terminalId.trim())),
[runningTerminalIds],
);
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
@@ -911,6 +1037,10 @@ export default function ThreadTerminalDrawer({
);
useEffect(() => {
if (!visible) {
return;
}
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
@@ -927,7 +1057,14 @@ export default function ThreadTerminalDrawer({
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
}, [syncHeight, visible]);
useEffect(() => {
if (!visible) {
return;
}
setResizeEpoch((value) => value + 1);
}, [visible]);
useEffect(() => {
return () => {
@@ -935,6 +1072,14 @@ export default function ThreadTerminalDrawer({
};
}, [syncHeight]);
const openWebPort = useCallback((event: ReactMouseEvent<HTMLButtonElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) return;
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
}, []);
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
@@ -1010,6 +1155,7 @@ export default function ThreadTerminalDrawer({
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -1030,6 +1176,7 @@ export default function ThreadTerminalDrawer({
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -1105,6 +1252,11 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const runtimeStatus = terminalRuntimeStatus(
terminalId,
runningTerminalIdSet,
runningTerminalPorts,
);
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
@@ -1130,6 +1282,29 @@ export default function ThreadTerminalDrawer({
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{runtimeStatus &&
(runtimeStatus.primaryWebPort === null ? (
<span
role="img"
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
className="inline-flex items-center justify-center text-teal-600 dark:text-teal-300/90"
>
<TerminalSquare className="size-2.5 animate-pulse" />
</span>
) : (
<button
type="button"
className="inline-flex items-center justify-center rounded p-0.5 text-sky-600 transition-colors hover:bg-accent hover:text-sky-700 dark:text-sky-300/90 dark:hover:text-sky-200"
onClick={(event) =>
openWebPort(event, runtimeStatus.primaryWebPort!)
}
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
>
<Globe className="size-2.5 shrink-0" />
</button>
))}
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
@@ -0,0 +1,116 @@
import { TurnId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { ChangedFilesTree } from "./ChangedFilesTree";
describe("ChangedFilesTree", () => {
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src"],
hiddenLabels: ["index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: ["apps/server/src"],
hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: ["README.md", "packages"],
hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"],
},
])(
"renders $name collapsed on the first render when collapse-all is active",
({ files, visibleLabels, hiddenLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded={false}
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
for (const label of hiddenLabels) {
expect(markup).not.toContain(label);
}
},
);
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src", "index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: [
"apps/server/src",
"git/Layers",
"provider/Layers",
"GitCore.ts",
"CodexAdapter.ts",
],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: [
"README.md",
"packages",
"shared/src",
"contracts/src",
"git.ts",
"orchestration.ts",
],
},
])(
"renders $name expanded on the first render when expand-all is active",
({ files, visibleLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
},
);
});
@@ -1,5 +1,5 @@
import { type TurnId } from "@t3tools/contracts";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useMemo, useState } from "react";
import { type TurnDiffFileChange } from "../../types";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
@@ -7,6 +7,8 @@ import { cn } from "~/lib/utils";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
@@ -20,32 +22,39 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
() => collectDirectoryPaths(treeNodes).join("\u0000"),
[treeNodes],
);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(() =>
buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
const [directoryExpansionState, setDirectoryExpansionState] = useState<{
key: string;
overrides: Record<string, boolean>;
}>(() => ({
key: expansionStateKey,
overrides: {},
}));
const expandedDirectories =
directoryExpansionState.key === expansionStateKey
? directoryExpansionState.overrides
: EMPTY_DIRECTORY_OVERRIDES;
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const toggleDirectory = useCallback(
(pathValue: string) => {
setDirectoryExpansionState((current) => {
const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
return {
key: expansionStateKey,
overrides: {
...nextOverrides,
[pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
},
};
});
},
[allDirectoriesExpanded, expansionStateKey],
);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
return (
<div key={`dir:${node.path}`}>
<button
@@ -53,7 +62,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
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)}
onClick={() => toggleDirectory(node.path)}
>
<ChevronRightIcon
aria-hidden="true"
@@ -124,14 +133,3 @@ function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[]
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
@@ -16,12 +16,6 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
: approval.requestKind === "file-read"
? "File-read approval requested"
: "File-change approval requested";
const detailLabel =
approval.requestKind === "command"
? "Command"
: approval.requestKind === "file-read"
? "Requested path"
: "Requested changes";
return (
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
@@ -32,19 +26,6 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
<span className="text-xs text-muted-foreground">1/{pendingCount}</span>
) : null}
</div>
{approval.detail ? (
<div className="mt-3 rounded-xl border border-border/70 bg-background/80 px-3 py-2.5 shadow-xs/5">
<p className="mb-1.5 text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground/80">
{detailLabel}
</p>
<pre
data-testid="pending-approval-detail"
className="max-h-48 overflow-auto whitespace-pre-wrap break-all select-text font-mono text-[12px] leading-relaxed text-foreground"
>
{approval.detail}
</pre>
</div>
) : null}
</div>
);
});
@@ -1,3 +1,11 @@
import { type MessageId } from "@t3tools/contracts";
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { estimateTimelineMessageHeight } from "../timelineHeight";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -5,6 +13,29 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
export type MessagesTimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: ChatMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: ProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
export function computeMessageDurationStart(
messages: ReadonlyArray<TimelineDurationMessage>,
): Map<string, string> {
@@ -27,3 +58,142 @@ export function computeMessageDurationStart(
export function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
isWorking: boolean;
activeTurnStartedAt: string | null;
}): MessagesTimelineRow[] {
const nextRows: MessagesTimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < input.timelineEntries.length; index += 1) {
const timelineEntry = input.timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < input.timelineEntries.length) {
const nextEntry = input.timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
input.completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (input.isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt,
});
}
return nextRows;
}
export function estimateMessagesTimelineRowHeight(
row: MessagesTimelineRow,
input: {
timelineWidthPx: number | null;
expandedWorkGroups?: Readonly<Record<string, boolean>>;
turnDiffSummaryByAssistantMessageId?: ReadonlyMap<MessageId, TurnDiffSummary>;
},
): number {
switch (row.kind) {
case "work":
return estimateWorkRowHeight(row, input);
case "proposed-plan":
return estimateTimelineProposedPlanHeight(row.proposedPlan);
case "working":
return 40;
case "message": {
let estimate = estimateTimelineMessageHeight(row.message, {
timelineWidthPx: input.timelineWidthPx,
});
const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id);
if (turnDiffSummary && turnDiffSummary.files.length > 0) {
estimate += estimateChangedFilesCardHeight(turnDiffSummary);
}
return estimate;
}
}
}
function estimateWorkRowHeight(
row: Extract<MessagesTimelineRow, { kind: "work" }>,
input: {
expandedWorkGroups?: Readonly<Record<string, boolean>>;
},
): number {
const isExpanded = input.expandedWorkGroups?.[row.id] ?? false;
const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length;
const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
// Card chrome, optional header, and one compact work-entry row per visible entry.
return 28 + (showHeader ? 26 : 0) + visibleEntries * 32;
}
function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number {
const treeNodes = buildTurnDiffTree(turnDiffSummary.files);
const visibleNodeCount = countTurnDiffTreeNodes(treeNodes);
// Card chrome: top/bottom padding, header row, and tree spacing.
return 60 + visibleNodeCount * 25;
}
function countTurnDiffTreeNodes(nodes: ReadonlyArray<TurnDiffTreeNode>): number {
let count = 0;
for (const node of nodes) {
count += 1;
if (node.kind === "directory") {
count += countTurnDiffTreeNodes(node.children);
}
}
return count;
}
+75 -102
View File
@@ -35,13 +35,18 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { clamp } from "effect/Number";
import { estimateTimelineMessageHeight } from "../timelineHeight";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
import {
MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
estimateMessagesTimelineRowHeight,
normalizeCompactToolLabel,
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import {
deriveDisplayedUserMessageState,
@@ -56,7 +61,6 @@ import {
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
interface MessagesTimelineProps {
@@ -81,6 +85,17 @@ interface MessagesTimelineProps {
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
onVirtualizerSnapshot?: (snapshot: {
totalSize: number;
measurements: ReadonlyArray<{
id: string;
kind: MessagesTimelineRow["kind"];
index: number;
size: number;
start: number;
end: number;
}>;
}) => void;
}
export const MessagesTimeline = memo(function MessagesTimeline({
@@ -105,6 +120,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
timestampFormat,
workspaceRoot,
onVirtualizerSnapshot,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
@@ -134,70 +150,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [hasMessages, isWorking]);
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < timelineEntries.length; index += 1) {
const timelineEntry = timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: activeTurnStartedAt,
});
}
return nextRows;
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
const rows = useMemo(
() =>
deriveMessagesTimelineRows({
timelineEntries,
completionDividerBeforeEntryId,
isWorking,
activeTurnStartedAt,
}),
[timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt],
);
const firstUnvirtualizedRowIndex = useMemo(() => {
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
@@ -241,19 +203,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
minimum: 0,
maximum: rows.length,
});
const virtualMeasurementScopeKey =
timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`;
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainer,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
// Scope cached row measurements to the current timeline width so offscreen
// rows do not keep stale heights after wrapping changes.
getItemKey: (index: number) => {
const rowId = rows[index]?.id ?? String(index);
return `${virtualMeasurementScopeKey}:${rowId}`;
},
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
if (row.kind === "working") return 40;
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
return estimateMessagesTimelineRowHeight(row, {
expandedWorkGroups,
timelineWidthPx,
turnDiffSummaryByAssistantMessageId,
});
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
@@ -295,6 +264,32 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
};
}, []);
useLayoutEffect(() => {
if (!onVirtualizerSnapshot) {
return;
}
onVirtualizerSnapshot({
totalSize: rowVirtualizer.getTotalSize(),
measurements: rowVirtualizer.measurementsCache
.slice(0, virtualizedRowCount)
.flatMap((measurement) => {
const row = rows[measurement.index];
if (!row) {
return [];
}
return [
{
id: row.id,
kind: row.kind,
index: measurement.index,
size: measurement.size,
start: measurement.start,
end: measurement.end,
},
];
}),
});
}, [onVirtualizerSnapshot, rowVirtualizer, rows, virtualizedRowCount]);
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -311,6 +306,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const renderRowContent = (row: TimelineRow) => (
<div
className="pb-4"
data-timeline-row-id={row.id}
data-timeline-row-kind={row.kind}
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
@@ -585,6 +581,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div
key={`virtual-row:${row.id}`}
data-index={virtualRow.index}
data-virtual-row-id={row.id}
data-virtual-row-kind={row.kind}
data-virtual-row-size={virtualRow.size}
data-virtual-row-start={virtualRow.start}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
@@ -605,35 +605,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
type TimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: TimelineWorkEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: TimelineMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: TimelineProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
type TimelineRow = MessagesTimelineRow;
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more