Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03c098d248 | ||
|
|
e9fa2b75dc | ||
|
|
885a825bdb | ||
|
|
0ea58f2dbf | ||
|
|
1f83f781d7 | ||
|
|
ad4eb99e22 | ||
|
|
4bf8d7b74c | ||
|
|
971df8206d | ||
|
|
eecc2bc28d | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b |
No files matched your search
@@ -22,3 +22,4 @@ apps/web/src/components/__screenshots__
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
artifacts/
|
||||
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -47,6 +47,10 @@ We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
@@ -36,6 +36,57 @@ describe("resolveDesktopBackendPort", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
@@ -46,7 +97,9 @@ describe("resolveDesktopBackendPort", () => {
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -21,10 +22,37 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
@@ -39,15 +67,17 @@ export async function resolveDesktopBackendPort({
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnHost(port, host)) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
@@ -100,7 +101,7 @@ const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -117,6 +118,16 @@ const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -1648,6 +1659,46 @@ function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
@@ -1659,8 +1710,7 @@ function createWindow(): BrowserWindow {
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
@@ -1695,6 +1745,14 @@ function createWindow(): BrowserWindow {
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1773,6 +1831,7 @@ async function bootstrap(): Promise<void> {
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
|
||||
@@ -488,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState } from "./seedPerfState.ts";
|
||||
|
||||
describe("seedPerfState", () => {
|
||||
const runParentDirsToCleanup: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
runParentDirsToCleanup
|
||||
.splice(0)
|
||||
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
|
||||
const seeded = await seedPerfState("large_threads");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
const scenario = getPerfSeedScenario("large_threads");
|
||||
|
||||
expect(seeded.snapshot.projects).toHaveLength(5);
|
||||
expect(seeded.snapshot.threads).toHaveLength(30);
|
||||
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
|
||||
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
|
||||
|
||||
const heavyThread = seeded.snapshot.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyThreadScenario = scenario.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
expect(heavyThread?.messages).toHaveLength(2_000);
|
||||
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
|
||||
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
|
||||
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
|
||||
});
|
||||
|
||||
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
|
||||
const seeded = await seedPerfState("burst_base");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
|
||||
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
|
||||
expect(JSON.parse(rawSettings)).toMatchObject({
|
||||
enableAssistantStreaming: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
|
||||
import {
|
||||
buildPerfAssistantMessageCountPlan,
|
||||
getPerfSeedScenario,
|
||||
perfEventId,
|
||||
perfMessageIdForThread,
|
||||
perfTurnIdForThread,
|
||||
type PerfProjectScenario,
|
||||
type PerfSeedScenario,
|
||||
type PerfSeedScenarioId,
|
||||
type PerfSeedThreadScenario,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { ServerConfig } from "../../src/config.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts";
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
}
|
||||
|
||||
const templateDirPromises = new Map<PerfSeedScenarioId, Promise<string>>();
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
async function initializeGitWorkspace(workspaceRoot: string): Promise<void> {
|
||||
await mkdir(workspaceRoot, { recursive: true });
|
||||
runGit(workspaceRoot, ["init", "--initial-branch=main"]);
|
||||
runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
|
||||
runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]);
|
||||
await writeFile(
|
||||
join(workspaceRoot, "README.md"),
|
||||
"# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n",
|
||||
"utf8",
|
||||
);
|
||||
runGit(workspaceRoot, ["add", "."]);
|
||||
runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]);
|
||||
}
|
||||
|
||||
function plusMs(baseTimeMs: number, offsetMs: number): string {
|
||||
return new Date(baseTimeMs + offsetMs).toISOString();
|
||||
}
|
||||
|
||||
function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId {
|
||||
return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`);
|
||||
}
|
||||
|
||||
function buildProjectEvent(
|
||||
project: PerfProjectScenario,
|
||||
workspaceRoot: string,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
|
||||
aggregateKind: "project",
|
||||
aggregateId: project.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadCreatedEvent(
|
||||
thread: PerfSeedThreadScenario,
|
||||
project: PerfProjectScenario,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: project.defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`;
|
||||
if (turnIndex % 11 === 0) {
|
||||
return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`;
|
||||
}
|
||||
if (turnIndex % 7 === 0) {
|
||||
return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function buildAssistantMessageText(
|
||||
thread: PerfSeedThreadScenario,
|
||||
turnIndex: number,
|
||||
assistantMessageIndex: number,
|
||||
assistantMessageCount: number,
|
||||
): string {
|
||||
const phaseLabel =
|
||||
assistantMessageIndex === 1
|
||||
? "Opening"
|
||||
: assistantMessageIndex === assistantMessageCount
|
||||
? "Settled"
|
||||
: assistantMessageIndex % 5 === 0
|
||||
? "Checkpoint"
|
||||
: "Loop";
|
||||
const focusTopics = [
|
||||
"checked the visible timeline window and sidebar ordering",
|
||||
"trimmed redundant projection work before the next render pass",
|
||||
"reviewed websocket fan-out and message grouping pressure",
|
||||
"verified checkpoint rows stay bounded while hidden threads move",
|
||||
"kept the active route stable while background threads kept streaming",
|
||||
];
|
||||
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
|
||||
const threadBias =
|
||||
thread.category === "heavy"
|
||||
? "The thread is still dense enough to stress virtualization."
|
||||
: thread.category === "burst"
|
||||
? "This pass is still carrying live burst pressure."
|
||||
: "Background churn is staying active without stealing focus.";
|
||||
|
||||
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
|
||||
}
|
||||
|
||||
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
return [
|
||||
`## ${thread.title} plan ${turnIndex}`,
|
||||
"",
|
||||
"1. Measure the current thread switch path against a stable local budget.",
|
||||
"2. Reduce avoidable render churn in the visible timeline window.",
|
||||
"3. Validate websocket burst handling with real runtime events before tightening thresholds.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildCheckpointFiles(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
turnIndex: number,
|
||||
): ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}> {
|
||||
const nestedPathTemplates = [
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
|
||||
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
|
||||
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
|
||||
[
|
||||
"apps",
|
||||
"server",
|
||||
"src",
|
||||
"orchestration",
|
||||
`thread-${threadOrdinal + 1}`,
|
||||
"projectionPipeline.ts",
|
||||
],
|
||||
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
|
||||
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
|
||||
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
|
||||
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
|
||||
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
|
||||
] as const;
|
||||
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
|
||||
|
||||
return Array.from({ length: fileCount }, (_, fileIndex) => {
|
||||
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
|
||||
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
|
||||
const baseSegments = [...template];
|
||||
const fileName = baseSegments.pop()!;
|
||||
const variantFileName =
|
||||
variant === 0
|
||||
? fileName
|
||||
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
|
||||
const path = [...baseSegments, variantFileName].join("/");
|
||||
const kind =
|
||||
fileIndex % 9 === 0
|
||||
? "deleted"
|
||||
: fileIndex % 5 === 0
|
||||
? "added"
|
||||
: fileIndex % 4 === 0
|
||||
? "renamed"
|
||||
: "modified";
|
||||
|
||||
return {
|
||||
path,
|
||||
kind,
|
||||
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
|
||||
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildThreadTurnEvents(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
projectStartMs: number,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
|
||||
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
|
||||
|
||||
for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) {
|
||||
const turnId = perfTurnIdForThread(thread, turnIndex);
|
||||
const userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
|
||||
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
|
||||
const turnBaseMs = threadStartMs + turnIndex * 1_000;
|
||||
const userOccurredAt = plusMs(turnBaseMs, 0);
|
||||
const activityAssistantIndex =
|
||||
thread.activityStride !== null && turnIndex % thread.activityStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
|
||||
: null;
|
||||
const planAssistantIndex =
|
||||
thread.planStride !== null && turnIndex % thread.planStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
|
||||
: null;
|
||||
let lastAssistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageCount,
|
||||
);
|
||||
let turnEventOffset = 0;
|
||||
const nextEventId = (prefix: string) =>
|
||||
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-user-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: userOccurredAt,
|
||||
commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: userMessageId,
|
||||
role: "user",
|
||||
text: buildUserMessageText(thread, turnIndex),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: userOccurredAt,
|
||||
updatedAt: userOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
for (
|
||||
let assistantMessageIndex = 1;
|
||||
assistantMessageIndex <= assistantMessageCount;
|
||||
assistantMessageIndex += 1
|
||||
) {
|
||||
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
|
||||
const assistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
);
|
||||
lastAssistantMessageId = assistantMessageId;
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-assistant-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: assistantOccurredAt,
|
||||
commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: buildAssistantMessageText(
|
||||
thread,
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
assistantMessageCount,
|
||||
),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: assistantOccurredAt,
|
||||
updatedAt: assistantOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (activityAssistantIndex === assistantMessageIndex) {
|
||||
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.activity-appended",
|
||||
eventId: nextEventId("perf-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: activityOccurredAt,
|
||||
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: perfEventId("perf-activity-row", thread.id, turnIndex),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `Synthetic command batch ${turnIndex}.${assistantMessageIndex}`,
|
||||
payload: {
|
||||
command: "perf-simulated",
|
||||
batch: turnIndex,
|
||||
loop: assistantMessageIndex,
|
||||
threadCategory: thread.category,
|
||||
},
|
||||
turnId,
|
||||
createdAt: activityOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (planAssistantIndex === assistantMessageIndex) {
|
||||
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.proposed-plan-upserted",
|
||||
eventId: nextEventId("perf-plan"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: planOccurredAt,
|
||||
commandId: makeCommandId("perf-plan", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
proposedPlan: {
|
||||
id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`,
|
||||
turnId,
|
||||
planMarkdown: buildProposedPlanMarkdown(thread, turnIndex),
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: planOccurredAt,
|
||||
updatedAt: planOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) {
|
||||
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
|
||||
events.push({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: nextEventId("perf-diff"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: diffOccurredAt,
|
||||
commandId: makeCommandId("perf-diff", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
checkpointTurnCount: turnIndex,
|
||||
checkpointRef: CheckpointRef.makeUnsafe(
|
||||
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
|
||||
),
|
||||
status: "ready",
|
||||
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
|
||||
assistantMessageId: lastAssistantMessageId,
|
||||
completedAt: diffOccurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
function buildScenarioEvents(
|
||||
scenario: PerfSeedScenario,
|
||||
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z");
|
||||
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
|
||||
for (const thread of scenario.threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
let globalThreadOrdinal = 0;
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
|
||||
for (const [projectOrdinal, project] of scenario.projects.entries()) {
|
||||
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
|
||||
if (!projectWorkspaceRoot) {
|
||||
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
|
||||
}
|
||||
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
|
||||
const projectCreatedAt = plusMs(projectBaseMs, 0);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
|
||||
|
||||
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
|
||||
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
|
||||
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
|
||||
globalThreadOrdinal += 1;
|
||||
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`));
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
const workspaceRootsByProjectId = new Map<ProjectId, string>(
|
||||
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
scenario.projects.map((project) =>
|
||||
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
|
||||
),
|
||||
);
|
||||
|
||||
const seedLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(seedLayer);
|
||||
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
enableAssistantStreaming: scenario.id === "burst_base",
|
||||
});
|
||||
|
||||
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
|
||||
const storedEvent = yield* eventStore.append(event);
|
||||
yield* projectionPipeline.projectEvent(storedEvent);
|
||||
}
|
||||
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
|
||||
const manifestPath = join(baseDir, "perf-seed-manifest.json");
|
||||
await writeFile(
|
||||
manifestPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
scenarioId,
|
||||
workspaceRoot,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projectCount: snapshot.projects.length,
|
||||
threadCount: snapshot.threads.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await runtime.dispose();
|
||||
return baseDir;
|
||||
}
|
||||
|
||||
async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const existing = templateDirPromises.get(scenarioId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const created = createTemplateDir(scenarioId);
|
||||
templateDirPromises.set(scenarioId, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const templateDir = await getTemplateDir(scenarioId);
|
||||
const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`));
|
||||
const baseDir = join(runParentDir, "base");
|
||||
await cp(templateDir, baseDir, { recursive: true, force: true });
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
|
||||
const snapshotLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(snapshotLayer);
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
await runtime.dispose();
|
||||
|
||||
return {
|
||||
scenarioId,
|
||||
runParentDir,
|
||||
baseDir,
|
||||
workspaceRoot,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationEvent,
|
||||
type ProjectId,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
type ThreadId as ThreadIdType,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type ServerCommandLatencyMeasurement,
|
||||
startServerPerfHarness,
|
||||
summarizeCommandLatencyMeasurements,
|
||||
summarizeRpcLatencySeries,
|
||||
type ServerPerfHarness,
|
||||
type ServerRpcLatencySeries,
|
||||
} from "./serverPerfHarness.ts";
|
||||
import type { PerfLatencySample } from "@t3tools/shared/perf/artifact";
|
||||
|
||||
const CONTROL_PLANE_SAMPLE_COUNT = 4;
|
||||
const GIT_RPC_SAMPLE_COUNT = 6;
|
||||
const STREAM_THREAD_COUNT = 5;
|
||||
const SPAM_THREAD_COUNT = 8;
|
||||
const TERMINAL_SESSION_COUNT = 3;
|
||||
const TERMINAL_OUTPUT_LINE_COUNT = 260;
|
||||
const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04;
|
||||
const GIT_BRANCH_COUNT = 240;
|
||||
const GIT_UNTRACKED_FILE_COUNT = 160;
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 45_000;
|
||||
|
||||
interface SubscriptionCleanup {
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
interface EventWaiter<TValue, TResult> {
|
||||
readonly description: string;
|
||||
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
|
||||
readonly resolve: (value: TResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
|
||||
private readonly values: TValue[] = [];
|
||||
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
|
||||
|
||||
push(value: TValue) {
|
||||
this.values.push(value);
|
||||
for (const waiter of this.waiters) {
|
||||
const match = waiter.select(this.values);
|
||||
if (match === null) {
|
||||
continue;
|
||||
}
|
||||
clearTimeout(waiter.timer);
|
||||
this.waiters.delete(waiter);
|
||||
waiter.resolve(match);
|
||||
}
|
||||
}
|
||||
|
||||
waitFor<TResult>(
|
||||
description: string,
|
||||
select: (values: ReadonlyArray<TValue>) => TResult | null,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TResult> {
|
||||
const immediateMatch = select(this.values);
|
||||
if (immediateMatch !== null) {
|
||||
return Promise.resolve(immediateMatch);
|
||||
}
|
||||
|
||||
return new Promise<TResult>((resolve, reject) => {
|
||||
const waiter: EventWaiter<TValue, TResult> = {
|
||||
description,
|
||||
select,
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
|
||||
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
|
||||
});
|
||||
}
|
||||
|
||||
waitForEvent(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TValue> {
|
||||
return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs);
|
||||
}
|
||||
|
||||
waitForCount(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const matches = values.filter(predicate);
|
||||
return matches.length >= count ? matches.slice(0, count) : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
waitForDistinct<TKey extends string | number>(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
selectKey: (value: TValue) => TKey,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const distinctMatches = new Map<TKey, TValue>();
|
||||
for (const value of values) {
|
||||
if (!predicate(value)) {
|
||||
continue;
|
||||
}
|
||||
const key = selectKey(value);
|
||||
if (!distinctMatches.has(key)) {
|
||||
distinctMatches.set(key, value);
|
||||
}
|
||||
}
|
||||
const matches = [...distinctMatches.values()];
|
||||
return matches.length >= count ? matches : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`));
|
||||
}
|
||||
this.waiters.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(delayMs: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function makeControlThreadId(label: string): ThreadIdType {
|
||||
return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeCommandId(label: string) {
|
||||
return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeMessageId(label: string) {
|
||||
return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) {
|
||||
return await harness.rpc.request((client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand](command),
|
||||
);
|
||||
}
|
||||
|
||||
async function measureCommandLatency(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
readonly expectedEventType: OrchestrationEvent["type"];
|
||||
readonly loadProfile: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}): Promise<ServerCommandLatencyMeasurement> {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
const result = await dispatchCommand(input.harness, input.command);
|
||||
const ackAtMs = performance.now();
|
||||
const event = await input.orchestrationEvents.waitForEvent(
|
||||
`${input.expectedEventType} for ${input.command.type}`,
|
||||
(candidate) =>
|
||||
candidate.type === input.expectedEventType &&
|
||||
String(candidate.commandId) === String(input.command.commandId),
|
||||
input.timeoutMs,
|
||||
);
|
||||
const eventAtMs = performance.now();
|
||||
|
||||
return {
|
||||
commandType: input.command.type,
|
||||
loadProfile: input.loadProfile,
|
||||
startedAt,
|
||||
dispatchToAckMs: ackAtMs - startedAtMs,
|
||||
dispatchToEventMs: eventAtMs - startedAtMs,
|
||||
ackToEventMs: eventAtMs - ackAtMs,
|
||||
resultSequence: result.sequence,
|
||||
eventSequence: event.sequence,
|
||||
...(input.metadata ? { metadata: input.metadata } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function createSupportThread(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly label: string;
|
||||
}): Promise<ThreadIdType> {
|
||||
const threadId = makeControlThreadId(`load-${input.label}`);
|
||||
const command = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`load-thread-create-${input.label}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Load ${input.label}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
await dispatchCommand(input.harness, command);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for load support thread ${input.label}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
return threadId;
|
||||
}
|
||||
|
||||
async function captureCreateArchiveSamples(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly loadProfile: string;
|
||||
readonly sampleCount: number;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
|
||||
const samples: ServerCommandLatencyMeasurement[] = [];
|
||||
|
||||
for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) {
|
||||
const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`);
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf ${input.loadProfile} ${sampleIndex + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: createCommand,
|
||||
expectedEventType: "thread.created",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const archiveCommand = {
|
||||
type: "thread.archive",
|
||||
commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: archiveCommand,
|
||||
expectedEventType: "thread.archived",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
async function ensureStreamingThreads(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
}): Promise<ReadonlyArray<ThreadIdType>> {
|
||||
const threadIds: ThreadIdType[] = [
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
];
|
||||
|
||||
while (threadIds.length < input.count) {
|
||||
threadIds.push(
|
||||
await createSupportThread({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
projectId: input.projectId,
|
||||
modelSelection: input.modelSelection,
|
||||
label: `stream-${threadIds.length + 1}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return threadIds;
|
||||
}
|
||||
|
||||
async function startAssistantStreamingLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly label: string;
|
||||
}): Promise<void> {
|
||||
await Promise.all(
|
||||
input.threadIds.map((threadId, index) =>
|
||||
dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf load ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand),
|
||||
),
|
||||
);
|
||||
|
||||
const threadIds = new Set(input.threadIds.map(String));
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant streaming output for ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIds.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
input.threadIds.length,
|
||||
);
|
||||
}
|
||||
|
||||
async function startCreateTurnSpamLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
readonly label: string;
|
||||
}): Promise<{
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
|
||||
}> {
|
||||
const threadIds = Array.from({ length: input.count }, (_, index) =>
|
||||
makeControlThreadId(`${input.label}-${index + 1}`),
|
||||
);
|
||||
const threadIdStrings = new Set(threadIds.map(String));
|
||||
|
||||
const done = Promise.all(
|
||||
threadIds.map(async (threadId, index) => {
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`${input.label}-create-${index + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Spam ${index + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
await dispatchCommand(input.harness, createCommand);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for ${input.label}-${index + 1}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
await dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf spam ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand);
|
||||
return threadId;
|
||||
}),
|
||||
);
|
||||
|
||||
await input.orchestrationEvents.waitForCount(
|
||||
`thread.create spam ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant spam output ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIdStrings.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
|
||||
return {
|
||||
threadIds,
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
async function startTerminalLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly terminalEvents: BufferedEventFeed<TerminalEvent>;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
|
||||
const sessions = await Promise.all(
|
||||
input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => {
|
||||
const terminalId = `perf-${index + 1}`;
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalOpen]({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd: input.workspaceRoot,
|
||||
cols: 120,
|
||||
rows: 32,
|
||||
}),
|
||||
);
|
||||
|
||||
const command = [
|
||||
"i=1",
|
||||
`while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`,
|
||||
"do",
|
||||
` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`,
|
||||
" i=$((i + 1))",
|
||||
` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`,
|
||||
"done",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalWrite]({
|
||||
threadId,
|
||||
terminalId,
|
||||
data: command,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId,
|
||||
terminalId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalIds = new Set(sessions.map((session) => session.terminalId));
|
||||
await input.terminalEvents.waitForDistinct(
|
||||
"terminal output load",
|
||||
(event) => event.type === "output" && terminalIds.has(event.terminalId),
|
||||
(event) => event.terminalId,
|
||||
sessions.length,
|
||||
30_000,
|
||||
);
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async function closeTerminalLoad(
|
||||
harness: ServerPerfHarness,
|
||||
sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
sessions.map((session) =>
|
||||
harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalClose]({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
deleteHistory: true,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedGitPressure(workspaceRoot: string): Promise<void> {
|
||||
const untrackedDir = join(workspaceRoot, "perf-git-pressure");
|
||||
await mkdir(untrackedDir, { recursive: true });
|
||||
await Promise.all(
|
||||
Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) =>
|
||||
writeFile(
|
||||
join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`),
|
||||
`export const perfFile${index + 1} = ${index + 1};\n`,
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) {
|
||||
runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]);
|
||||
}
|
||||
}
|
||||
|
||||
async function measureRpcLatencySeries<TResult>(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly iterations: number;
|
||||
readonly execute: () => Promise<TResult>;
|
||||
}): Promise<ServerRpcLatencySeries> {
|
||||
const samples: PerfLatencySample[] = [];
|
||||
|
||||
for (let iteration = 0; iteration < input.iterations; iteration += 1) {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
await input.execute();
|
||||
const endedAtMs = performance.now();
|
||||
samples.push({
|
||||
name: `${input.name}-${iteration + 1}`,
|
||||
durationMs: endedAtMs - startedAtMs,
|
||||
startedAt,
|
||||
endedAt: nowIso(),
|
||||
metadata: {
|
||||
iteration: iteration + 1,
|
||||
loadProfile: input.loadProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: input.name,
|
||||
loadProfile: input.loadProfile,
|
||||
summary: summarizeRpcLatencySeries(samples),
|
||||
samples,
|
||||
};
|
||||
}
|
||||
|
||||
function groupCommandSeries(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
loadProfile: string,
|
||||
) {
|
||||
const createSamples = samples.filter((sample) => sample.commandType === "thread.create");
|
||||
const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive");
|
||||
|
||||
return [
|
||||
{
|
||||
name: "thread.create",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(createSamples),
|
||||
samples: createSamples,
|
||||
},
|
||||
{
|
||||
name: "thread.archive",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(archiveSamples),
|
||||
samples: archiveSamples,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
describe("server perf latency", () => {
|
||||
const disposables: Array<SubscriptionCleanup> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const disposable of disposables.splice(0)) {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("records idle and assistant-stream command latency at the websocket boundary", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
disposables.push(orchestrationEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
|
||||
const idleSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "idle",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "stream-control-plane",
|
||||
});
|
||||
|
||||
const streamingSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "assistant-stream-5x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
const spamLoad = await startCreateTurnSpamLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: SPAM_THREAD_COUNT,
|
||||
label: "create-turn-spam-8x",
|
||||
});
|
||||
const spamSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "create-turn-spam-8x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
await spamLoad.done;
|
||||
|
||||
const commandLatency = [
|
||||
...groupCommandSeries(idleSamples, "idle"),
|
||||
...groupCommandSeries(streamingSamples, "assistant-stream-5x"),
|
||||
...groupCommandSeries(spamSamples, "create-turn-spam-8x"),
|
||||
];
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "control-plane-stream-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_control_plane_stream_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency,
|
||||
rpcLatency: [],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
streamingThreadCount: STREAM_THREAD_COUNT,
|
||||
spamThreadCount: SPAM_THREAD_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(6);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull();
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
it("records command and git rpc latency under terminal and mixed server load", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
let terminalSessions: ReadonlyArray<{
|
||||
readonly threadId: ThreadIdType;
|
||||
readonly terminalId: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
|
||||
disposables.push(orchestrationEvents, terminalEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(event) => terminalEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
await seedGitPressure(harness.seededState.workspaceRoot);
|
||||
|
||||
const gitLatencyIdle = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
|
||||
terminalSessions = await startTerminalLoad({
|
||||
harness,
|
||||
terminalEvents,
|
||||
workspaceRoot: harness.seededState.workspaceRoot,
|
||||
threadIds: streamingThreadIds,
|
||||
});
|
||||
|
||||
const terminalSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "terminal-output-3x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
await sleep(6_500);
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "mixed-load",
|
||||
});
|
||||
await terminalEvents.waitForCount(
|
||||
"continued terminal output during mixed load",
|
||||
(event) =>
|
||||
event.type === "output" &&
|
||||
terminalSessions.some((session) => session.terminalId === event.terminalId),
|
||||
TERMINAL_SESSION_COUNT,
|
||||
30_000,
|
||||
);
|
||||
|
||||
const mixedSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const gitLatencyMixed = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
await closeTerminalLoad(harness, terminalSessions);
|
||||
terminalSessions = [];
|
||||
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "terminal-mixed-git-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_terminal_mixed_git_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency: [
|
||||
...groupCommandSeries(terminalSamples, "terminal-output-3x"),
|
||||
...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"),
|
||||
],
|
||||
rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT,
|
||||
branchCount: GIT_BRANCH_COUNT,
|
||||
untrackedFileCount: GIT_UNTRACKED_FILE_COUNT,
|
||||
terminalSessionCount: TERMINAL_SESSION_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(4);
|
||||
expect(result.artifact.rpcLatency).toHaveLength(4);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
for (const series of result.artifact.rpcLatency) {
|
||||
expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT);
|
||||
expect(series.summary.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
if (harness && terminalSessions.length > 0) {
|
||||
await closeTerminalLoad(harness, terminalSessions).catch(() => undefined);
|
||||
}
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import {
|
||||
type OrchestrationEvent,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Scope,
|
||||
Stream,
|
||||
type Scope as ScopeService,
|
||||
} from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import {
|
||||
summarizeLatencySamples,
|
||||
summarizeLatencyValues,
|
||||
type PerfLatencySample,
|
||||
type PerfLatencySummary,
|
||||
writeJsonArtifact,
|
||||
} from "@t3tools/shared/perf/artifact";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
|
||||
type WsRpcClient =
|
||||
typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
|
||||
|
||||
export interface ServerCommandLatencyMeasurement {
|
||||
readonly commandType: string;
|
||||
readonly loadProfile: string;
|
||||
readonly startedAt: string;
|
||||
readonly dispatchToAckMs: number;
|
||||
readonly dispatchToEventMs: number;
|
||||
readonly ackToEventMs: number;
|
||||
readonly resultSequence: number;
|
||||
readonly eventSequence: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySummary {
|
||||
readonly count: number;
|
||||
readonly dispatchToAckMs: PerfLatencySummary;
|
||||
readonly dispatchToEventMs: PerfLatencySummary;
|
||||
readonly ackToEventMs: PerfLatencySummary;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: ServerCommandLatencySummary;
|
||||
readonly samples: ReadonlyArray<ServerCommandLatencyMeasurement>;
|
||||
}
|
||||
|
||||
export interface ServerRpcLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: PerfLatencySummary;
|
||||
readonly samples: ReadonlyArray<PerfLatencySample>;
|
||||
}
|
||||
|
||||
export interface ServerPerfRunArtifact {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly startedAt: string;
|
||||
readonly completedAt: string;
|
||||
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
|
||||
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface StartServerPerfHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
}
|
||||
|
||||
interface FinishServerPerfRunOptions {
|
||||
readonly artifactBasename?: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}
|
||||
|
||||
export interface ServerPerfHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly wsUrl: string;
|
||||
readonly artifactDir: string;
|
||||
readonly rpc: PerfWsRpcClient;
|
||||
readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}>;
|
||||
readonly dispose: () => Promise<void>;
|
||||
}
|
||||
|
||||
const wsRpcProtocolLayer = (wsUrl: string) =>
|
||||
RpcClient.layerProtocolSocket().pipe(
|
||||
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
);
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/server"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
|
||||
export class PerfWsRpcClient {
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcClient>;
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly wsUrl: string) {
|
||||
this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient));
|
||||
}
|
||||
|
||||
async request<TSuccess, TError>(
|
||||
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
if (this.disposed) {
|
||||
throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`);
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
subscribe<TValue>(
|
||||
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
): () => void {
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
listener(value);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancel();
|
||||
};
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise<void> {
|
||||
const startedAtMs = performance.now();
|
||||
const timeoutMs = 45_000;
|
||||
|
||||
while (performance.now() - startedAtMs < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
|
||||
const client = new PerfWsRpcClient(wsUrl);
|
||||
try {
|
||||
await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({}));
|
||||
await client.dispose();
|
||||
return;
|
||||
} catch {
|
||||
await client.dispose().catch(() => undefined);
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`);
|
||||
}
|
||||
|
||||
export function summarizeCommandLatencyMeasurements(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
): ServerCommandLatencySummary {
|
||||
return {
|
||||
count: samples.length,
|
||||
dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)),
|
||||
dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)),
|
||||
ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)),
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeRpcLatencySeries(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencySamples(samples);
|
||||
}
|
||||
|
||||
export async function startServerPerfHarness(
|
||||
options: StartServerPerfHarnessOptions,
|
||||
): Promise<ServerPerfHarness> {
|
||||
const seededState = await seedPerfState(options.seedScenarioId);
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const wsUrl = `ws://127.0.0.1:${port}/ws`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
let finished = false;
|
||||
const serverProcess = spawn(
|
||||
"bun",
|
||||
[
|
||||
"run",
|
||||
"apps/server/src/bin.ts",
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
|
||||
const cleanup = async () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
await stopChildProcess(serverProcess);
|
||||
await rm(seededState.runParentDir, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
try {
|
||||
await waitForRpcReady(wsUrl, serverProcess);
|
||||
const rpc = new PerfWsRpcClient(wsUrl);
|
||||
|
||||
return {
|
||||
seededState,
|
||||
wsUrl,
|
||||
artifactDir,
|
||||
rpc,
|
||||
finishRun: async ({ artifactBasename, artifact }) => {
|
||||
const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`;
|
||||
await rpc.dispose();
|
||||
await cleanup();
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writeJsonArtifact(artifactPath, artifact);
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
};
|
||||
},
|
||||
dispose: async () => {
|
||||
await rpc.dispose().catch(() => undefined);
|
||||
await cleanup();
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient };
|
||||
@@ -20,7 +20,8 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:perf": "vitest run integration/perf"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
const scenarioId = process.argv[2];
|
||||
|
||||
if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
|
||||
console.error(`Expected a perf seed scenario id, received '${scenarioId ?? "<missing>"}'.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const seeded = await seedPerfState(scenarioId);
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
|
||||
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
|
||||
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
scenarioId: seeded.scenarioId,
|
||||
runParentDir: seeded.runParentDir,
|
||||
baseDir: seeded.baseDir,
|
||||
workspaceRoot: seeded.workspaceRoot,
|
||||
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
|
||||
projectSummaries: seeded.snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot:
|
||||
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
|
||||
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
|
||||
: project.workspaceRoot,
|
||||
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
|
||||
.length,
|
||||
})),
|
||||
threadSummaries: seeded.snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
projectTitle: projectById.get(thread.projectId)?.title ?? null,
|
||||
title: thread.title,
|
||||
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
|
||||
messageCount: thread.messages.length,
|
||||
activityCount: thread.activities.length,
|
||||
proposedPlanCount: thread.proposedPlans.length,
|
||||
checkpointCount: thread.checkpoints.length,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`);
|
||||
@@ -20,7 +20,10 @@ import {
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
@@ -65,6 +68,13 @@ export const makeServerAuth = Effect.gen(function* () {
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
|
||||
@@ -33,10 +33,12 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -66,6 +68,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
@@ -30,7 +30,10 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: SESSION_COOKIE_NAME,
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
@@ -81,11 +82,16 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
@@ -472,7 +478,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName: SESSION_COOKIE_NAME,
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
|
||||
@@ -2,7 +2,18 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
export const SESSION_COOKIE_NAME = "t3_session";
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
|
||||
@@ -82,10 +82,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -136,10 +141,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -40,6 +40,24 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
function git(
|
||||
cwd: string,
|
||||
@@ -299,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
|
||||
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.hasOriginRemote).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -793,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -812,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
@@ -823,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
@@ -853,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
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,
|
||||
});
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
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;
|
||||
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(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "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",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# 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: "simulated fetch timeout",
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
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.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
@@ -1014,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -1626,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
const core = yield* GitCore;
|
||||
|
||||
const status = yield* core.statusDetails(deletedDir);
|
||||
const localStatus = yield* core.statusDetailsLocal(deletedDir);
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
expect(localStatus).toEqual(status);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type GitStatusDetails,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
@@ -59,17 +60,27 @@ 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;
|
||||
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -359,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function isMissingGitCwdError(error: GitCommandError): boolean {
|
||||
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
|
||||
return (
|
||||
normalized.includes("no such file or directory") ||
|
||||
normalized.includes("notfound: filesystem.access") ||
|
||||
normalized.includes("enoent") ||
|
||||
normalized.includes("not a directory")
|
||||
);
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
@@ -896,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
});
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
remoteName: 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",
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -922,18 +942,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith(refreshStatusUpstreamCacheEntry, {
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
@@ -949,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1190,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (statusResult === null) {
|
||||
return NON_REPOSITORY_STATUS_DETAILS;
|
||||
}
|
||||
|
||||
if (statusResult.code !== 0) {
|
||||
const stderr = statusResult.stderr.trim();
|
||||
@@ -1322,7 +1340,10 @@ 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 }));
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
@@ -1719,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
|
||||
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-list",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Layer, Schema, SchemaIssue } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const mergedAt = input.mergedAt;
|
||||
const state = input.state;
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
return "merged";
|
||||
}
|
||||
if (state === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
const RawGitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
function normalizePullRequestSummary(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
|
||||
): GitHubPullRequestSummary {
|
||||
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
|
||||
const headRepositoryOwnerLogin =
|
||||
raw.headRepositoryOwner?.login ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizePullRequestState(raw),
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
@@ -194,14 +134,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: decodeGitHubJson(
|
||||
raw,
|
||||
Schema.Array(RawGitHubPullRequestSchema),
|
||||
"listOpenPullRequests",
|
||||
"GitHub CLI returned invalid PR list JSON.",
|
||||
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubPullRequestSchema,
|
||||
"getPullRequest",
|
||||
"GitHub CLI returned invalid pull request JSON.",
|
||||
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizePullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
|
||||
@@ -186,6 +186,24 @@ function makeTempDir(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
@@ -694,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 14,
|
||||
title: " Existing PR title \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-trimmed-pr\t",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 15,
|
||||
title: " Valid PR title ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-valid-pr-entry\t",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 16,
|
||||
title: "Closed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/16",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "closed",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
|
||||
@@ -720,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
|
||||
const cwd = path.join(rootDir, "deleted-repo");
|
||||
yield* makeDirectory(cwd);
|
||||
yield* removePath(cwd);
|
||||
const { manager } = yield* makeManager();
|
||||
|
||||
const status = yield* manager.status({ cwd });
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
} from "effect";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitActionProgressPhase,
|
||||
@@ -34,6 +45,10 @@ import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScr
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import {
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -240,85 +255,6 @@ function matchesBranchHeadContext(
|
||||
return true;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
const isCrossRepository = record.isCrossRepository;
|
||||
const headRepositoryRecord =
|
||||
typeof record.headRepository === "object" && record.headRepository !== null
|
||||
? (record.headRepository as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryOwnerRecord =
|
||||
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
|
||||
? (record.headRepositoryOwner as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryNameWithOwner =
|
||||
typeof record.headRepositoryNameWithOwner === "string"
|
||||
? record.headRepositoryNameWithOwner
|
||||
: typeof headRepositoryRecord?.nameWithOwner === "string"
|
||||
? headRepositoryRecord.nameWithOwner
|
||||
: null;
|
||||
const headRepositoryOwnerLogin =
|
||||
typeof record.headRepositoryOwnerLogin === "string"
|
||||
? record.headRepositoryOwnerLogin
|
||||
: typeof headRepositoryOwnerRecord?.login === "string"
|
||||
? headRepositoryOwnerRecord.login
|
||||
: null;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if (
|
||||
(typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
|
||||
state === "MERGED" ||
|
||||
state === "merged"
|
||||
) {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED" || state === "closed") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||
return {
|
||||
number: summary.number,
|
||||
@@ -947,13 +883,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
gitManagerError(
|
||||
"findLatestPr",
|
||||
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
decoded.failure,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const pr of parsePullRequestList(parsedJson)) {
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const pr of pullRequests) {
|
||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const normalizedState = input.state?.trim().toUpperCase();
|
||||
if (
|
||||
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
|
||||
normalizedState === "MERGED"
|
||||
) {
|
||||
return "merged";
|
||||
}
|
||||
if (normalizedState === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
export const formatGitHubJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitHubPullRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -61,6 +61,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
|
||||
+10
-5
@@ -293,11 +293,16 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
|
||||
@@ -144,10 +144,20 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -89,6 +90,77 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
const openRequestIds = new Set<string>();
|
||||
const ordered = [...activities].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const requestId = extractActivityRequestId(activity.payload);
|
||||
if (requestId === null) {
|
||||
continue;
|
||||
}
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
|
||||
if (activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
}): boolean {
|
||||
const sorted = [...input.proposedPlans].toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
|
||||
);
|
||||
|
||||
let latestForTurn: ProjectionThreadProposedPlan | null = null;
|
||||
if (input.latestTurnId !== null) {
|
||||
for (let index = sorted.length - 1; index >= 0; index -= 1) {
|
||||
const plan = sorted[index];
|
||||
if (plan?.turnId === input.latestTurnId) {
|
||||
latestForTurn = plan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (latestForTurn !== null) {
|
||||
return latestForTurn.implementedAt === null;
|
||||
}
|
||||
|
||||
const latestPlan = sorted.at(-1) ?? null;
|
||||
return latestPlan !== null && latestPlan.implementedAt === null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
@@ -432,6 +504,48 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const refreshThreadShellSummary = Effect.fn("refreshThreadShellSummary")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
|
||||
projectionThreadMessageRepository.listByThreadId({ threadId }),
|
||||
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
|
||||
projectionThreadActivityRepository.listByThreadId({ threadId }),
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
).length;
|
||||
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
|
||||
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
|
||||
latestTurnId: existingRow.value.latestTurnId,
|
||||
proposedPlans,
|
||||
});
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
pendingApprovalCount,
|
||||
pendingUserInputCount,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
@@ -450,6 +564,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
@@ -554,7 +672,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -565,6 +685,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -580,6 +701,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -595,6 +717,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,6 +733,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,9 +62,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
@@ -74,9 +80,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
'2026-02-24T00:00:02.000Z',
|
||||
'2026-02-24T00:00:03.000Z',
|
||||
NULL
|
||||
@@ -341,6 +353,81 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.snapshotSequence, 5);
|
||||
assert.deepEqual(shellSnapshot.projects, [
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(shellSnapshot.threads, [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -629,4 +716,309 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps thread detail activity ordering consistent with shell snapshot ordering", () =>
|
||||
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_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
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-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-01T00:00:00.000Z',
|
||||
'2026-04-01T00: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,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-01T00:00:02.000Z',
|
||||
'2026-04-01T00:00:03.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-unsequenced',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'unsequenced first',
|
||||
'{"source":"unsequenced"}',
|
||||
NULL,
|
||||
'2026-04-01T00:00:06.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-2',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence two',
|
||||
'{"source":"sequence-2"}',
|
||||
2,
|
||||
'2026-04-01T00:00:04.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-1',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence one',
|
||||
'{"source":"sequence-1"}',
|
||||
1,
|
||||
'2026-04-01T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const snapshot = yield* snapshotQuery.getSnapshot();
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
|
||||
}
|
||||
|
||||
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
|
||||
{
|
||||
id: asEventId("activity-unsequenced"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "unsequenced first",
|
||||
payload: { source: "unsequenced" },
|
||||
turnId: null,
|
||||
createdAt: "2026-04-01T00:00:06.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence one",
|
||||
payload: { source: "sequence-1" },
|
||||
turnId: null,
|
||||
sequence: 1,
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-2"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence two",
|
||||
payload: { source: "sequence-2" },
|
||||
turnId: null,
|
||||
sequence: 2,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for targeted thread latest turn queries", () =>
|
||||
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-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-02T00:00:00.000Z',
|
||||
'2026-04-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,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-02T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-02T00:00:02.000Z',
|
||||
'2026-04-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-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-02T00:00:05.000Z',
|
||||
'2026-04-02T00:00:06.000Z',
|
||||
'2026-04-02T00:00:20.000Z',
|
||||
5,
|
||||
'checkpoint-5',
|
||||
'ready',
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
if (threadShell._tag === "Some") {
|
||||
assert.equal(threadShell.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadShell.value.latestTurn?.state, "running");
|
||||
assert.equal(threadShell.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadDetail.value.latestTurn?.state, "running");
|
||||
assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,16 +6,19 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadShell,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -48,6 +51,8 @@ import {
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
|
||||
const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
@@ -155,6 +160,64 @@ function computeSnapshotSequence(
|
||||
return Number.isFinite(minSequence) ? minSequence : 0;
|
||||
}
|
||||
|
||||
function mapLatestTurn(
|
||||
row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,
|
||||
): OrchestrationLatestTurn {
|
||||
return {
|
||||
turnId: row.turnId,
|
||||
state:
|
||||
row.state === "error"
|
||||
? "error"
|
||||
: row.state === "interrupted"
|
||||
? "interrupted"
|
||||
: row.state === "completed"
|
||||
? "completed"
|
||||
: "running",
|
||||
requestedAt: row.requestedAt,
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,
|
||||
): OrchestrationSession {
|
||||
return {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
runtimeMode: row.runtimeMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function mapProjectShellRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,
|
||||
repositoryIdentity: OrchestrationProject["repositoryIdentity"],
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -204,6 +267,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -381,6 +448,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveProjectRowById = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionProjectLookupRowSchema,
|
||||
execute: ({ projectId }) =>
|
||||
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 project_id = ${projectId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionThreadIdLookupRowSchema,
|
||||
@@ -415,6 +503,146 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadMessageRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
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 thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadSessionRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_sessions
|
||||
WHERE thread_id = ${threadId}
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getLatestTurnRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.thread_id = ${threadId}
|
||||
AND threads.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
@@ -724,6 +952,145 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.gen(function* () {
|
||||
let updatedAt: string | null = null;
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of threadRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of latestTurnRows) {
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (const row of stateRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
const sessionByThread = new Map(
|
||||
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeShellSnapshot(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -770,6 +1137,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getProjectShellById: ProjectionSnapshotQueryShape["getProjectShellById"] = (projectId) =>
|
||||
getActiveProjectRowById({ projectId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getProjectShellById:query",
|
||||
"ProjectionSnapshotQuery.getProjectShellById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((option) =>
|
||||
Option.isNone(option)
|
||||
? Effect.succeed(Option.none<OrchestrationProjectShell>())
|
||||
: repositoryIdentityResolver
|
||||
.resolve(option.value.workspaceRoot)
|
||||
.pipe(
|
||||
Effect.map((repositoryIdentity) =>
|
||||
Option.some(mapProjectShellRow(option.value, repositoryIdentity)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
|
||||
(projectId) =>
|
||||
getFirstActiveThreadIdByProject({ projectId }).pipe(
|
||||
@@ -826,12 +1214,217 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
});
|
||||
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadMessageRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
if (row.attachments !== null) {
|
||||
return Object.assign(message, { attachments: row.attachments });
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
checkpointRef: row.checkpointRef,
|
||||
status: row.status,
|
||||
files: row.files,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
};
|
||||
|
||||
return Option.some(
|
||||
yield* decodeThread(thread).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getThreadDetailById:decodeThread"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getThreadCheckpointContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
import type {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -44,6 +48,17 @@ export interface ProjectionSnapshotQueryShape {
|
||||
*/
|
||||
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration shell snapshot.
|
||||
*
|
||||
* Returns only projects and thread shell summaries so clients can bootstrap
|
||||
* lightweight navigation state without hydrating every thread body.
|
||||
*/
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationShellSnapshot,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
@@ -56,6 +71,13 @@ export interface ProjectionSnapshotQueryShape {
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active project shell row by id.
|
||||
*/
|
||||
readonly getProjectShellById: (
|
||||
projectId: ProjectId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the earliest active thread for a project.
|
||||
*/
|
||||
@@ -69,6 +91,20 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadCheckpointContext: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread shell row by id.
|
||||
*/
|
||||
readonly getThreadShellById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread detail snapshot by id.
|
||||
*/
|
||||
readonly getThreadDetailById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const STREAM_SAMPLE_EVENT_COUNT = 96;
|
||||
|
||||
describe("PerfProviderAdapter", () => {
|
||||
const previousScenarioEnv = process.env[PERF_SCENARIO_ENV];
|
||||
|
||||
afterEach(() => {
|
||||
if (previousScenarioEnv === undefined) {
|
||||
delete process.env[PERF_SCENARIO_ENV];
|
||||
return;
|
||||
}
|
||||
process.env[PERF_SCENARIO_ENV] = previousScenarioEnv;
|
||||
});
|
||||
|
||||
it("emits canonical runtime events for the dense assistant stream scenario", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise the dense perf scenario",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
expect(firstEvents.filter((event) => event.type === "turn.started")).toHaveLength(3);
|
||||
expect(new Set(firstEvents.slice(0, 18).map((event) => String(event.threadId)))).toEqual(
|
||||
new Set([
|
||||
String(threadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.navigationThreadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.fillerThreadId),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.delta.includes("Navigation lane"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.fillerThreadId &&
|
||||
event.type === "item.updated" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const firstBurstFollowupCompletionIndex = firstEvents.findIndex(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message" &&
|
||||
String(event.itemId ?? "").includes("followup"),
|
||||
);
|
||||
const burstWorklogIdsBeforeFollowup = new Set(
|
||||
firstEvents
|
||||
.slice(0, firstBurstFollowupCompletionIndex)
|
||||
.filter(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.started" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
)
|
||||
.map((event) => String(event.itemId)),
|
||||
);
|
||||
const burstAssistantMessageLengths = firstEvents
|
||||
.flatMap((event) => {
|
||||
if (
|
||||
event.threadId !== threadId ||
|
||||
event.type !== "item.completed" ||
|
||||
event.payload.itemType !== "assistant_message" ||
|
||||
event.payload.detail === undefined
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [event.payload.detail.length];
|
||||
})
|
||||
.slice(0, 4);
|
||||
|
||||
expect(firstBurstFollowupCompletionIndex).toBeGreaterThan(0);
|
||||
expect(burstWorklogIdsBeforeFollowup.size).toBeGreaterThanOrEqual(3);
|
||||
expect(new Set(burstAssistantMessageLengths).size).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("assigns fresh runtime ids when the same burst thread is sent twice", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
|
||||
const secondEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "second dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const secondEvents = Array.from(await secondEventsPromise);
|
||||
|
||||
const firstNavigationTurnStarted = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const secondNavigationTurnStarted = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const firstBurstAssistantCompletion = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondBurstAssistantCompletion = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondRunNamespaceSuffix = `--perf-run-${String(threadId)}-0002`;
|
||||
|
||||
expect(firstNavigationTurnStarted?.turnId).toBe(PERF_CATALOG_IDS.provider.navigationLiveTurnId);
|
||||
expect(firstBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).toBeDefined();
|
||||
expect(secondBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).not.toBe(firstNavigationTurnStarted?.turnId);
|
||||
expect(secondBurstAssistantCompletion?.itemId).not.toBe(firstBurstAssistantCompletion?.itemId);
|
||||
expect(String(secondNavigationTurnStarted?.turnId)).toContain(secondRunNamespaceSuffix);
|
||||
expect(String(secondBurstAssistantCompletion?.itemId)).toContain(secondRunNamespaceSuffix);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,456 @@
|
||||
import {
|
||||
EventId,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
TurnId,
|
||||
type ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
type ProviderUserInputAnswers,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
import {
|
||||
getPerfProviderScenario,
|
||||
type PerfProviderScenario,
|
||||
type TimedFixtureProviderRuntimeEvent,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../provider/Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterShape,
|
||||
ProviderThreadSnapshot,
|
||||
ProviderThreadTurnSnapshot,
|
||||
} from "../provider/Services/ProviderAdapter.ts";
|
||||
import { getPerfProviderScenarioId } from "./config.ts";
|
||||
|
||||
interface PerfSessionState {
|
||||
session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
pendingTimers: Set<ReturnType<typeof setTimeout>>;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(threadId: ThreadId): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: "codex",
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePerfScenario(inputText: string | undefined): PerfProviderScenario {
|
||||
const scenarioId = getPerfProviderScenarioId();
|
||||
if (scenarioId) {
|
||||
return getPerfProviderScenario(scenarioId);
|
||||
}
|
||||
|
||||
const trimmedInput = inputText?.trim() || "perf request";
|
||||
return {
|
||||
id: "dense_assistant_stream",
|
||||
provider: "codex",
|
||||
sentinelText: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
totalDurationMs: 48,
|
||||
events: [
|
||||
{
|
||||
delayMs: 0,
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 16,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `Perf fallback response for: ${trimmedInput}. `,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 32,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 48,
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSession {
|
||||
const { activeTurnId: _activeTurnId, ...rest } = session;
|
||||
return {
|
||||
...rest,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function namespacePerfFixtureId(
|
||||
baseId: string,
|
||||
sourceThreadId: ThreadId,
|
||||
runIndex: number,
|
||||
): string {
|
||||
return `${baseId}--perf-run-${String(sourceThreadId)}-${runIndex.toString().padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
function buildRuntimeEvent(input: {
|
||||
readonly template: TimedFixtureProviderRuntimeEvent;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId;
|
||||
readonly startedAtMs: number;
|
||||
readonly index: number;
|
||||
readonly runIndex: number;
|
||||
}): ProviderRuntimeEvent {
|
||||
const eventThreadId = input.template.threadId ?? input.threadId;
|
||||
const eventTurnId =
|
||||
input.template.turnId === undefined
|
||||
? input.turnId
|
||||
: input.runIndex === 1
|
||||
? input.template.turnId
|
||||
: TurnId.makeUnsafe(
|
||||
namespacePerfFixtureId(String(input.template.turnId), input.threadId, input.runIndex),
|
||||
);
|
||||
const createdAt = new Date(input.startedAtMs + (input.template.delayMs ?? 0)).toISOString();
|
||||
return {
|
||||
type: input.template.type,
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(eventThreadId)}:${String(eventTurnId)}:${input.index.toString().padStart(4, "0")}`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId: eventThreadId,
|
||||
turnId: eventTurnId,
|
||||
createdAt,
|
||||
...(input.template.itemId
|
||||
? {
|
||||
itemId: RuntimeItemId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.itemId
|
||||
: namespacePerfFixtureId(input.template.itemId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(input.template.requestId
|
||||
? {
|
||||
requestId: RuntimeRequestId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.requestId
|
||||
: namespacePerfFixtureId(input.template.requestId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
payload: input.template.payload,
|
||||
} as ProviderRuntimeEvent;
|
||||
}
|
||||
|
||||
export const makePerfProviderAdapter = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, PerfSessionState>();
|
||||
|
||||
const clearPendingTimers = (threadId: ThreadId) =>
|
||||
Effect.sync(() => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
for (const timer of state.pendingTimers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
state.pendingTimers.clear();
|
||||
});
|
||||
|
||||
const scheduleRuntimeEvent = (input: {
|
||||
readonly state: PerfSessionState;
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
readonly delayMs: number;
|
||||
readonly onAfterEmit?: () => void;
|
||||
}) =>
|
||||
Effect.sync(() => {
|
||||
const timer = setTimeout(() => {
|
||||
input.state.pendingTimers.delete(timer);
|
||||
Effect.runFork(
|
||||
Queue.offer(runtimeEvents, input.event).pipe(
|
||||
Effect.tap(() => Effect.sync(() => input.onAfterEmit?.())),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
}, input.delayMs);
|
||||
input.state.pendingTimers.add(timer);
|
||||
});
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (
|
||||
input: ProviderSessionStartInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== "codex") {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: `Perf provider only supports codex sessions, received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const createdAt = nowIso();
|
||||
const session: ProviderSession = {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}),
|
||||
resumeCursor:
|
||||
input.resumeCursor ??
|
||||
RuntimeSessionId.makeUnsafe(`perf-resume:${String(input.threadId)}:${Date.now()}`),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(input.threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId: input.threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
pendingTimers: new Set(),
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (
|
||||
input: ProviderSendTurnInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(input.threadId));
|
||||
}
|
||||
|
||||
yield* clearPendingTimers(input.threadId);
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnId = TurnId.makeUnsafe(
|
||||
`perf-turn:${String(input.threadId)}:${state.turnCount.toString().padStart(4, "0")}`,
|
||||
);
|
||||
const scenario = resolvePerfScenario(input.input);
|
||||
const startedAtMs = Date.now();
|
||||
const sentAt = new Date(startedAtMs).toISOString();
|
||||
|
||||
state.session = {
|
||||
...state.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: sentAt,
|
||||
};
|
||||
|
||||
const userTurnItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input ?? "" }],
|
||||
} as const;
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: [userTurnItem],
|
||||
};
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
let assistantText = "";
|
||||
const updateAssistantSnapshot = (completedAt: string) => {
|
||||
state.session = toIdleSession(state.session, completedAt);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? {
|
||||
...turn,
|
||||
items:
|
||||
assistantText.length > 0
|
||||
? [...turn.items, { type: "agentMessage", text: assistantText }]
|
||||
: turn.items,
|
||||
}
|
||||
: turn,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
yield* Effect.forEach(
|
||||
scenario.events,
|
||||
(template, index) => {
|
||||
const event = buildRuntimeEvent({
|
||||
template,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
startedAtMs,
|
||||
index,
|
||||
runIndex: state.turnCount,
|
||||
});
|
||||
const delayMs = template.delayMs ?? 0;
|
||||
return scheduleRuntimeEvent({
|
||||
state,
|
||||
event,
|
||||
delayMs,
|
||||
onAfterEmit: () => {
|
||||
if (
|
||||
event.threadId === input.threadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.streamKind === "assistant_text"
|
||||
) {
|
||||
assistantText += event.payload.delta;
|
||||
}
|
||||
if (event.threadId === input.threadId && event.type === "turn.completed") {
|
||||
updateAssistantSnapshot(event.createdAt);
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
const interruptedTurnId = turnId ?? state.session.activeTurnId;
|
||||
state.session = toIdleSession(state.session, nowIso());
|
||||
if (interruptedTurnId) {
|
||||
yield* Queue.offer(runtimeEvents, {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(threadId)}:${String(interruptedTurnId)}:interrupted`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId,
|
||||
turnId: interruptedTurnId,
|
||||
createdAt: nowIso(),
|
||||
payload: {
|
||||
state: "interrupted",
|
||||
},
|
||||
} satisfies ProviderRuntimeEvent);
|
||||
}
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
_requestId: ApprovalRequestId,
|
||||
_decision: ProviderApprovalDecision,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers: ProviderUserInputAnswers,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
if (!sessions.has(threadId)) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.succeed(sessions.get(threadId)!.snapshot)
|
||||
: Effect.fail(sessionNotFound(threadId));
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and the current turn count.",
|
||||
});
|
||||
}
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
Array.from(sessions.keys()),
|
||||
(threadId) => clearPendingTimers(threadId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
} satisfies ProviderAdapterShape<ProviderAdapterError>;
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderUnsupportedError } from "../provider/Errors.ts";
|
||||
import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
export const PerfProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const adapter = yield* makePerfProviderAdapter;
|
||||
const adapterRegistryLayer = Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (provider) =>
|
||||
provider === adapter.provider
|
||||
? Effect.succeed(adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed([adapter.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service);
|
||||
|
||||
return makeProviderServiceLive().pipe(
|
||||
Layer.provide(adapterRegistryLayer),
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,160 @@
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { getClaudeModelCapabilities } from "../provider/Layers/ClaudeProvider.ts";
|
||||
import { getCodexModelCapabilities } from "../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "../provider/Services/ProviderRegistry.ts";
|
||||
|
||||
const makeProviderModel = (input: {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ServerProviderModel["capabilities"];
|
||||
}): ServerProviderModel => ({
|
||||
slug: input.slug,
|
||||
name: input.name,
|
||||
isCustom: false,
|
||||
capabilities: input.capabilities,
|
||||
});
|
||||
|
||||
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
name: "GPT-5.4",
|
||||
capabilities: getCodexModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.codex),
|
||||
}),
|
||||
];
|
||||
|
||||
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
name: "Claude Sonnet 4.6",
|
||||
capabilities: getClaudeModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.claudeAgent),
|
||||
}),
|
||||
];
|
||||
|
||||
const makeProviderSnapshot = (input: {
|
||||
readonly provider: ServerProvider["provider"];
|
||||
readonly enabled: boolean;
|
||||
readonly checkedAt: string;
|
||||
}): ServerProvider => {
|
||||
if (input.provider === "codex") {
|
||||
return {
|
||||
provider: "codex",
|
||||
enabled: input.enabled,
|
||||
installed: true,
|
||||
version: "perf-fixture",
|
||||
status: input.enabled ? "ready" : "disabled",
|
||||
auth: input.enabled
|
||||
? {
|
||||
status: "authenticated",
|
||||
type: "perf",
|
||||
label: "Local perf harness",
|
||||
}
|
||||
: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled ? "Perf fixture provider active." : "Disabled in T3 Code settings.",
|
||||
models: CODEX_MODELS,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
enabled: input.enabled,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: input.enabled ? "warning" : "disabled",
|
||||
auth: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled
|
||||
? "Perf harness only stubs Codex runtime sessions."
|
||||
: "Disabled in T3 Code settings.",
|
||||
models: CLAUDE_MODELS,
|
||||
};
|
||||
};
|
||||
|
||||
const loadPerfProviderSnapshots = Effect.fn("loadPerfProviderSnapshots")(function* (input: {
|
||||
readonly serverSettings: ServerSettingsService["Service"];
|
||||
}) {
|
||||
const settings = yield* input.serverSettings.getSettings;
|
||||
const checkedAt = new Date().toISOString();
|
||||
return [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: settings.providers.codex.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: settings.providers.claudeAgent.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
const loadPerfProviderSnapshotsSafely = (
|
||||
serverSettings: ServerSettingsService["Service"],
|
||||
fallback: ReadonlyArray<ServerProvider>,
|
||||
) =>
|
||||
loadPerfProviderSnapshots({ serverSettings }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => fallback),
|
||||
);
|
||||
|
||||
export const PerfProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadPerfProviderSnapshotsSafely(serverSettings, [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: false,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const refreshProviders = Effect.fn("refreshPerfProviders")(function* () {
|
||||
const previous = yield* Ref.get(providersRef);
|
||||
const next = yield* loadPerfProviderSnapshotsSafely(serverSettings, previous);
|
||||
yield* Ref.set(providersRef, next);
|
||||
if (!Equal.equals(previous, next)) {
|
||||
yield* PubSub.publish(changesPubSub, next);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(serverSettings.streamChanges, () => refreshProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (_provider) => refreshProviders(),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
export const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
export const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
|
||||
export function isPerfProviderEnabled(): boolean {
|
||||
return process.env[PERF_PROVIDER_ENV] === "1";
|
||||
}
|
||||
|
||||
export function getPerfProviderScenarioId(): PerfProviderScenarioId | null {
|
||||
const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim();
|
||||
if (rawScenarioId === "dense_assistant_stream" || rawScenarioId === "parallel_assistant_stream") {
|
||||
return rawScenarioId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -88,6 +88,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -55,6 +59,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
${row.hasActionableProposedPlan},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -70,6 +78,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
@@ -92,6 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -116,6 +132,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -35,6 +35,7 @@ import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
|
||||
import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
|
||||
import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
|
||||
import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -69,6 +70,7 @@ export const migrationEntries = [
|
||||
[20, "AuthAccessManagement", Migration0020],
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN latest_user_message_at TEXT
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
});
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -33,6 +34,10 @@ export const ProjectionThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
hasActionableProposedPlan: NonNegativeInt,
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThread = typeof ProjectionThread.Type;
|
||||
|
||||
@@ -1408,6 +1408,150 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("clamps oversized Claude usage to the reported context window", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 200000,
|
||||
lastUsedTokens: 200000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"preserves oversized Claude result totals after task progress snapshots are recorded",
|
||||
() => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-clamped",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 190000,
|
||||
},
|
||||
session_id: "sdk-session-task-usage-clamped",
|
||||
uuid: "task-usage-progress-clamped",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage-clamped-after-progress",
|
||||
usage: {
|
||||
total_tokens: 535000,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvents = runtimeEvents.filter(
|
||||
(event) => event.type === "thread.token-usage.updated",
|
||||
);
|
||||
const finalUsageEvent = usageEvents.at(-1);
|
||||
assert.equal(finalUsageEvent?.type, "thread.token-usage.updated");
|
||||
if (finalUsageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(finalUsageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 190000,
|
||||
lastUsedTokens: 190000,
|
||||
totalProcessedTokens: 535000,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
ModelUsage,
|
||||
NonNullableUsage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -272,24 +274,14 @@ function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.make(value);
|
||||
}
|
||||
|
||||
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
|
||||
if (!modelUsage || typeof modelUsage !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
function maxClaudeContextWindowFromModelUsage(
|
||||
modelUsage: Record<string, ModelUsage> | undefined,
|
||||
): number | undefined {
|
||||
if (!modelUsage) return undefined;
|
||||
|
||||
let maxContextWindow: number | undefined;
|
||||
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") {
|
||||
continue;
|
||||
}
|
||||
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
|
||||
if (
|
||||
typeof contextWindow !== "number" ||
|
||||
!Number.isFinite(contextWindow) ||
|
||||
contextWindow <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for (const value of Object.values(modelUsage)) {
|
||||
const contextWindow = value.contextWindow;
|
||||
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
|
||||
}
|
||||
|
||||
@@ -297,53 +289,58 @@ function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | und
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
usage: unknown,
|
||||
value: NonNullableUsage | undefined,
|
||||
contextWindow?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!usage || typeof usage !== "object") {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = usage as Record<string, unknown>;
|
||||
const directUsedTokens =
|
||||
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
|
||||
? record.total_tokens
|
||||
: undefined;
|
||||
const usage = value as Record<string, unknown>;
|
||||
const inputTokens =
|
||||
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
|
||||
? record.input_tokens
|
||||
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
|
||||
? usage.input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_creation_input_tokens)
|
||||
? record.cache_creation_input_tokens
|
||||
(typeof usage.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_creation_input_tokens)
|
||||
? usage.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_read_input_tokens)
|
||||
? record.cache_read_input_tokens
|
||||
(typeof usage.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_read_input_tokens)
|
||||
? usage.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
|
||||
? record.output_tokens
|
||||
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
|
||||
? usage.output_tokens
|
||||
: 0;
|
||||
const derivedUsedTokens = inputTokens + outputTokens;
|
||||
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
const derivedTotalProcessedTokens = inputTokens + outputTokens;
|
||||
const totalProcessedTokens =
|
||||
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
|
||||
? usage.total_tokens
|
||||
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
|
||||
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens =
|
||||
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? contextWindow
|
||||
: undefined;
|
||||
const usedTokens =
|
||||
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? { maxTokens: contextWindow }
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
|
||||
? { toolUses: usage.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
|
||||
? { toolUses: record.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
|
||||
? { durationMs: record.duration_ms }
|
||||
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
|
||||
? { durationMs: usage.duration_ms }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1328,8 +1325,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
errorMessage?: string,
|
||||
result?: SDKResultMessage,
|
||||
) {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
@@ -1341,9 +1336,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
result?.usage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const accumulatedTotalProcessedTokens =
|
||||
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
@@ -1352,8 +1349,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
|
||||
@@ -4,12 +4,16 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSlashCommand,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -276,18 +280,6 @@ function extractClaudeAuthMethodFromOutput(result: CommandResult): string | unde
|
||||
return Option.getOrUndefined(findAuthMethod(parsed.success));
|
||||
}
|
||||
|
||||
// ── Dynamic model capability adjustment ─────────────────────────────
|
||||
|
||||
/** Subscription types where the 1M context window is included in the plan. */
|
||||
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
|
||||
"max",
|
||||
"maxplan",
|
||||
"max5",
|
||||
"max20",
|
||||
"enterprise",
|
||||
"team",
|
||||
]);
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
@@ -348,53 +340,78 @@ function claudeAuthMetadata(input: {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Models where 1M context is included in premium Claude Code subscriptions
|
||||
* without needing extra usage enabled.
|
||||
*/
|
||||
const MODELS_WITH_INCLUDED_1M_CONTEXT = new Set(["claude-opus-4-6"]);
|
||||
|
||||
/**
|
||||
* Adjust the built-in model list based on the user's detected subscription.
|
||||
*
|
||||
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default
|
||||
* for models that include it in the plan (currently only Opus).
|
||||
* - Other tiers (Pro, free, unknown): 200k context stays the default;
|
||||
* 1M remains available as a manual option so users can still enable it.
|
||||
*/
|
||||
export function adjustModelsForSubscription(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
subscriptionType: string | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
// Flip 1M to be the default only for models that include it in the plan
|
||||
return baseModels.map((model) => {
|
||||
const caps = model.capabilities;
|
||||
if (!caps || caps.contextWindowOptions.length === 0) return model;
|
||||
if (!MODELS_WITH_INCLUDED_1M_CONTEXT.has(model.slug)) return model;
|
||||
|
||||
return {
|
||||
...model,
|
||||
capabilities: {
|
||||
...caps,
|
||||
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
|
||||
opt.value === "1m"
|
||||
? { value: opt.value, label: opt.label, isDefault: true as const }
|
||||
: { value: opt.value, label: opt.label },
|
||||
),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── SDK capability probe ────────────────────────────────────────────
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
function nonEmptyProbeString(value: string): string | undefined {
|
||||
const candidate = value.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
}
|
||||
|
||||
function parseClaudeInitializationCommands(
|
||||
commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
|
||||
): ReadonlyArray<ServerProviderSlashCommand> {
|
||||
return dedupeSlashCommands(
|
||||
(commands ?? []).flatMap((command) => {
|
||||
const name = nonEmptyProbeString(command.name);
|
||||
if (!name) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const description = nonEmptyProbeString(command.description);
|
||||
const argumentHint = nonEmptyProbeString(command.argumentHint);
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
...(description ? { description } : {}),
|
||||
...(argumentHint ? { input: { hint: argumentHint } } : {}),
|
||||
} satisfies ServerProviderSlashCommand,
|
||||
];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function dedupeSlashCommands(
|
||||
commands: ReadonlyArray<ServerProviderSlashCommand>,
|
||||
): ReadonlyArray<ServerProviderSlashCommand> {
|
||||
const commandsByName = new Map<string, ServerProviderSlashCommand>();
|
||||
|
||||
for (const command of commands) {
|
||||
const name = nonEmptyProbeString(command.name);
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
const existing = commandsByName.get(key);
|
||||
if (!existing) {
|
||||
commandsByName.set(key, {
|
||||
...command,
|
||||
name,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
commandsByName.set(key, {
|
||||
...existing,
|
||||
...(existing.description
|
||||
? {}
|
||||
: command.description
|
||||
? { description: command.description }
|
||||
: {}),
|
||||
...(existing.input?.hint
|
||||
? {}
|
||||
: command.input?.hint
|
||||
? { input: { hint: command.input.hint } }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
return [...commandsByName.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
@@ -416,13 +433,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: [],
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
},
|
||||
});
|
||||
const init = await q.initializationResult();
|
||||
return { subscriptionType: init.account?.subscriptionType };
|
||||
return {
|
||||
subscriptionType: init.account?.subscriptionType,
|
||||
slashCommands: parseClaudeInitializationCommands(init.commands),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
@@ -451,6 +471,9 @@ const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: Readonly
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
resolveSlashCommands?: (
|
||||
binaryPath: string,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
@@ -546,6 +569,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
});
|
||||
}
|
||||
|
||||
const slashCommands =
|
||||
(resolveSlashCommands
|
||||
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
)
|
||||
: undefined) ?? [];
|
||||
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
|
||||
|
||||
// ── Auth check + subscription detection ────────────────────────────
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
@@ -571,8 +602,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
|
||||
}
|
||||
|
||||
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
|
||||
|
||||
// ── Handle auth results (same logic as before, adjusted models) ──
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
@@ -581,7 +610,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -600,7 +630,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -617,7 +648,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
models,
|
||||
slashCommands: dedupedSlashCommands,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -640,12 +672,18 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
const subscriptionProbeCache = yield* Cache.make({
|
||||
capacity: 1,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (binaryPath: string) =>
|
||||
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
|
||||
lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
|
||||
});
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath),
|
||||
const checkProvider = checkClaudeProviderStatus(
|
||||
(binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath).pipe(
|
||||
Effect.map((probe) => probe?.subscriptionType),
|
||||
),
|
||||
(binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath).pipe(
|
||||
Effect.map((probe) => probe?.slashCommands),
|
||||
),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSkill,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -44,7 +45,7 @@ import {
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { probeCodexDiscovery } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
@@ -304,8 +305,9 @@ const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
const probeCodexCapabilities = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) =>
|
||||
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
|
||||
Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe(
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
@@ -334,6 +336,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
|
||||
resolveSkills?: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
@@ -449,12 +456,22 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
});
|
||||
}
|
||||
|
||||
const skills =
|
||||
(resolveSkills
|
||||
? yield* resolveSkills({
|
||||
binaryPath: codexSettings.binaryPath,
|
||||
homePath: codexSettings.homePath,
|
||||
cwd: process.cwd(),
|
||||
}).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined) ?? [];
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -484,6 +501,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -500,6 +518,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -518,6 +537,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -543,16 +563,29 @@ export const CodexProviderLive = Layer.effect(
|
||||
capacity: 4,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (key: string) => {
|
||||
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
|
||||
const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string];
|
||||
return probeCodexCapabilities({
|
||||
binaryPath,
|
||||
cwd,
|
||||
...(homePath ? { homePath } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const checkProvider = checkCodexProviderStatus((input) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
|
||||
const getDiscovery = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd]));
|
||||
|
||||
const checkProvider = checkCodexProviderStatus(
|
||||
(input) =>
|
||||
getDiscovery({
|
||||
...input,
|
||||
cwd: process.cwd(),
|
||||
}).pipe(Effect.map((discovery) => discovery?.account)),
|
||||
(input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
|
||||
@@ -221,6 +221,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes probed codex skills in the provider snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "pro" as const,
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
shortDescription: "Debug failing GitHub Actions checks",
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.skills, [
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
shortDescription: "Debug failing GitHub Actions checks",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
@@ -499,6 +542,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
@@ -509,6 +554,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
@@ -887,6 +934,85 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes probed claude slash commands in the provider snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
() => Effect.succeed("maxplan"),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "review",
|
||||
description: "Review a pull request",
|
||||
input: { hint: "pr-or-branch" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.slashCommands, [
|
||||
{
|
||||
name: "review",
|
||||
description: "Review a pull request",
|
||||
input: { hint: "pr-or-branch" },
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("deduplicates probed claude slash commands by name", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
() => Effect.succeed("maxplan"),
|
||||
() =>
|
||||
Effect.succeed([
|
||||
{
|
||||
name: "ui",
|
||||
description: "Explore and refine UI",
|
||||
},
|
||||
{
|
||||
name: "ui",
|
||||
input: { hint: "component-or-screen" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(status.slashCommands, [
|
||||
{
|
||||
name: "ui",
|
||||
description: "Explore and refine UI",
|
||||
input: { hint: "component-or-screen" },
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for claude api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
@@ -10,10 +11,74 @@ interface JsonRpcProbeResponse {
|
||||
};
|
||||
}
|
||||
|
||||
export interface CodexDiscoverySnapshot {
|
||||
readonly account: CodexAccountSnapshot;
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
function readObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: unknown): string | undefined {
|
||||
const candidate = readString(value)?.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
}
|
||||
|
||||
function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
|
||||
const resultRecord = readObject(result);
|
||||
const dataBuckets = readArray(resultRecord?.data) ?? [];
|
||||
const matchingBucket = dataBuckets.find(
|
||||
(value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
|
||||
);
|
||||
const rawSkills =
|
||||
readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
|
||||
|
||||
return rawSkills.flatMap((value) => {
|
||||
const skill = readObject(value);
|
||||
const display = readObject(skill?.interface);
|
||||
const name = nonEmptyTrimmed(skill?.name);
|
||||
const path = nonEmptyTrimmed(skill?.path);
|
||||
if (!name || !path) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
path,
|
||||
enabled: skill?.enabled !== false,
|
||||
...(nonEmptyTrimmed(skill?.description)
|
||||
? { description: nonEmptyTrimmed(skill?.description) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
|
||||
...(nonEmptyTrimmed(display?.displayName)
|
||||
? { displayName: nonEmptyTrimmed(display?.displayName) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
|
||||
? {
|
||||
shortDescription:
|
||||
nonEmptyTrimmed(skill?.shortDescription) ??
|
||||
nonEmptyTrimmed(display?.shortDescription),
|
||||
}
|
||||
: {}),
|
||||
} satisfies ServerProviderSkill,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
@@ -40,11 +105,12 @@ export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): vo
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexAccount(input: {
|
||||
export async function probeCodexDiscovery(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexAccountSnapshot> {
|
||||
}): Promise<CodexDiscoverySnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
@@ -57,6 +123,8 @@ export async function probeCodexAccount(input: {
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
let account: CodexAccountSnapshot | undefined;
|
||||
let skills: ReadonlyArray<ServerProviderSkill> | undefined;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
@@ -79,15 +147,25 @@ export async function probeCodexAccount(input: {
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex account probe failed: ${String(error)}.`),
|
||||
: new Error(`Codex discovery probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
const maybeResolve = () => {
|
||||
if (account && skills !== undefined) {
|
||||
const resolvedAccount = account;
|
||||
const resolvedSkills = skills;
|
||||
finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
|
||||
}
|
||||
};
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex account probe aborted."));
|
||||
fail(new Error("Codex discovery probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
|
||||
input.signal?.addEventListener("abort", () =>
|
||||
fail(new Error("Codex discovery probe aborted.")),
|
||||
);
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
@@ -103,7 +181,7 @@ export async function probeCodexAccount(input: {
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during account probe."));
|
||||
fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -120,18 +198,27 @@ export async function probeCodexAccount(input: {
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "account/read", params: {} });
|
||||
writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
|
||||
writeMessage({ id: 3, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
|
||||
maybeResolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 3) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
finish(() => resolve(readCodexAccountSnapshot(response.result)));
|
||||
account = readCodexAccountSnapshot(response.result);
|
||||
maybeResolve();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderSkill,
|
||||
ServerProviderSlashCommand,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -130,6 +132,8 @@ export function buildServerProvider(input: {
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProvider {
|
||||
return {
|
||||
@@ -142,6 +146,8 @@ export function buildServerProvider(input: {
|
||||
checkedAt: input.checkedAt,
|
||||
...(input.probe.message ? { message: input.probe.message } : {}),
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+16
-235
@@ -31,6 +31,7 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Stream,
|
||||
} from "effect";
|
||||
@@ -68,7 +69,6 @@ import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { PersistenceSqlError } from "./persistence/Errors.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
@@ -410,6 +410,20 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
),
|
||||
@@ -789,7 +803,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"browser-session-cookie",
|
||||
"bearer-session-token",
|
||||
]);
|
||||
assert.equal(body.auth.sessionCookieName, "t3_session");
|
||||
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -2748,11 +2762,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const snapshotResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
|
||||
);
|
||||
assert.equal(snapshotResult.snapshotSequence, 1);
|
||||
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
@@ -3306,234 +3315,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const now = new Date().toISOString();
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
let replayCursor: number | null = null;
|
||||
const makeEvent = (sequence: number): OrchestrationEvent =>
|
||||
({
|
||||
sequence,
|
||||
eventId: `event-${sequence}`,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.reverted",
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount: sequence,
|
||||
},
|
||||
}) as OrchestrationEvent;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 1,
|
||||
}),
|
||||
readEvents: (fromSequenceExclusive) => {
|
||||
replayCursor = fromSequenceExclusive;
|
||||
return Stream.make(makeEvent(2), makeEvent(3));
|
||||
},
|
||||
streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(3),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(replayCursor, 1);
|
||||
assert.deepEqual(
|
||||
Array.from(events).map((event) => event.sequence),
|
||||
[2, 3, 4],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches replayed project events only once before streaming them to subscribers", () =>
|
||||
Effect.gen(function* () {
|
||||
let resolveCalls = 0;
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:t3tools/t3code.git",
|
||||
},
|
||||
displayName: "t3tools/t3code",
|
||||
provider: "github" as const,
|
||||
owner: "t3tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
readEvents: () =>
|
||||
Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-06T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Replayed Project",
|
||||
updatedAt: "2026-04-06T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
streamDomainEvents: Stream.empty,
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => {
|
||||
resolveCalls += 1;
|
||||
return Effect.succeed(repositoryIdentity);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(resolveCalls, 1);
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches subscribed project meta updates with repository identity metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "upstream",
|
||||
remoteUrl: "[email protected]:T3Tools/t3code.git",
|
||||
},
|
||||
displayName: "T3Tools/t3code",
|
||||
provider: "github",
|
||||
owner: "T3Tools",
|
||||
name: "t3code",
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
getReadModel: () =>
|
||||
Effect.succeed({
|
||||
...makeDefaultOrchestrationReadModel(),
|
||||
snapshotSequence: 0,
|
||||
}),
|
||||
streamDomainEvents: Stream.make({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: defaultProjectId,
|
||||
occurredAt: "2026-04-05T00:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Renamed Project",
|
||||
updatedAt: "2026-04-05T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.meta-updated" }>),
|
||||
},
|
||||
repositoryIdentityResolver: {
|
||||
resolve: () => Effect.succeed(repositoryIdentity),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const event = Array.from(events)[0];
|
||||
assert.equal(event?.type, "project.meta-updated");
|
||||
assert.deepEqual(
|
||||
event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null,
|
||||
repositoryIdentity,
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc orchestration.getSnapshot errors", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getSnapshot: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "ProjectionSnapshotQuery.getSnapshot",
|
||||
detail: "projection unavailable",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe(
|
||||
Effect.result,
|
||||
),
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
|
||||
assertInclude(result.failure.message, "Failed to load orchestration snapshot");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc terminal methods", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = {
|
||||
|
||||
@@ -72,6 +72,9 @@ import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http";
|
||||
import { isPerfProviderEnabled } from "./perf/config";
|
||||
import { PerfProviderRegistryLive } from "./perf/PerfProviderRegistry";
|
||||
import { PerfProviderLayerLive } from "./perf/PerfProviderLayers";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -134,7 +137,7 @@ const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
const DefaultProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
@@ -163,6 +166,14 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const SelectedProviderLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderLayerLive
|
||||
: DefaultProviderLayerLive;
|
||||
|
||||
const SelectedProviderRegistryLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderRegistryLive
|
||||
: ProviderRegistryLive;
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
|
||||
const GitManagerLayerLive = GitManagerLive.pipe(
|
||||
@@ -199,11 +210,11 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(SelectedProviderLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SelectedProviderRegistryLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
|
||||
@@ -70,6 +70,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -78,8 +79,11 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: () => Effect.void,
|
||||
|
||||
@@ -129,6 +129,18 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prioritizes exact basename matches ahead of broader path matches", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-exact-ranking-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "docs/composer.tsx-notes.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "Composer.tsx", limit: 5 });
|
||||
|
||||
expect(result.entries[0]?.path).toBe("src/components/Composer.tsx");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tracks truncation without sorting every fuzzy match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" });
|
||||
|
||||
@@ -4,6 +4,12 @@ import type { Dirent } from "node:fs";
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type ProjectEntry } from "@t3tools/contracts";
|
||||
import {
|
||||
insertRankedSearchResult,
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
type RankedSearchResult,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
@@ -40,10 +46,7 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
@@ -74,45 +77,6 @@ function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEnt
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
@@ -120,81 +84,32 @@ function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | nu
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
const scores = [
|
||||
scoreQueryMatch({
|
||||
value: normalizedName,
|
||||
query,
|
||||
exactBase: 0,
|
||||
prefixBase: 2,
|
||||
includesBase: 5,
|
||||
fuzzyBase: 100,
|
||||
}),
|
||||
scoreQueryMatch({
|
||||
value: normalizedPath,
|
||||
query,
|
||||
exactBase: 1,
|
||||
prefixBase: 3,
|
||||
boundaryBase: 4,
|
||||
includesBase: 6,
|
||||
fuzzyBase: 200,
|
||||
boundaryMarkers: ["/"],
|
||||
}),
|
||||
].filter((score): score is number => score !== null);
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
if (scores.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
return Math.min(...scores);
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
@@ -469,7 +384,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe(
|
||||
Effect.map((index) => {
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const normalizedQuery = normalizeSearchQuery(input.query, {
|
||||
trimLeadingPattern: /^[@./]+/,
|
||||
});
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
@@ -481,11 +398,15 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
insertRankedSearchResult(
|
||||
rankedEntries,
|
||||
{ item: entry, score, tieBreaker: entry.path },
|
||||
limit,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
entries: rankedEntries.map((candidate) => candidate.item),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}),
|
||||
|
||||
+146
-66
@@ -1,4 +1,4 @@
|
||||
import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect";
|
||||
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AuthSessionId,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type GitManagerServiceError,
|
||||
OrchestrationDispatchCommandError,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationShellStreamEvent,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
@@ -62,6 +63,28 @@ import {
|
||||
} from "./auth/Services/SessionCredentialService";
|
||||
import { respondToAuthError } from "./auth/http";
|
||||
|
||||
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.message-sent"
|
||||
| "thread.proposed-plan-upserted"
|
||||
| "thread.activity-appended"
|
||||
| "thread.turn-diff-completed"
|
||||
| "thread.reverted"
|
||||
| "thread.session-set";
|
||||
}
|
||||
> {
|
||||
return (
|
||||
event.type === "thread.message-sent" ||
|
||||
event.type === "thread.proposed-plan-upserted" ||
|
||||
event.type === "thread.activity-appended" ||
|
||||
event.type === "thread.turn-diff-completed" ||
|
||||
event.type === "thread.reverted" ||
|
||||
event.type === "thread.session-set"
|
||||
);
|
||||
}
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -222,6 +245,57 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
|
||||
Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
|
||||
|
||||
const toShellStreamEvent = (
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
case "project.meta-updated":
|
||||
return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe(
|
||||
Effect.map((project) =>
|
||||
Option.map(project, (nextProject) => ({
|
||||
kind: "project-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
project: nextProject,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
case "project.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "project-removed" as const,
|
||||
sequence: event.sequence,
|
||||
projectId: event.payload.projectId,
|
||||
}),
|
||||
);
|
||||
case "thread.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "thread-removed" as const,
|
||||
sequence: event.sequence,
|
||||
threadId: event.payload.threadId,
|
||||
}),
|
||||
);
|
||||
default:
|
||||
if (event.aggregateKind !== "thread") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return projectionSnapshotQuery
|
||||
.getThreadShellById(ThreadId.make(event.aggregateId))
|
||||
.pipe(
|
||||
Effect.map((thread) =>
|
||||
Option.map(thread, (nextThread) => ({
|
||||
kind: "thread-upserted" as const,
|
||||
sequence: event.sequence,
|
||||
thread: nextThread,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const dispatchBootstrapTurnStart = (
|
||||
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
|
||||
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
|
||||
@@ -467,20 +541,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
|
||||
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,
|
||||
@@ -561,65 +621,85 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* orchestrationEngine.getReadModel();
|
||||
const fromSequenceExclusive = snapshot.snapshotSequence;
|
||||
const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(fromSequenceExclusive),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.flatMap(enrichOrchestrationEvents),
|
||||
Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
|
||||
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration shell snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const replayStream = Stream.fromIterable(replayEvents);
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.mapEffect(enrichProjectEvent),
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
);
|
||||
const source = Stream.merge(replayStream, liveStream);
|
||||
type SequenceState = {
|
||||
readonly nextSequence: number;
|
||||
readonly pendingBySequence: Map<number, OrchestrationEvent>;
|
||||
};
|
||||
const state = yield* Ref.make<SequenceState>({
|
||||
nextSequence: fromSequenceExclusive + 1,
|
||||
pendingBySequence: new Map<number, OrchestrationEvent>(),
|
||||
});
|
||||
|
||||
return source.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
Ref.modify(
|
||||
state,
|
||||
({
|
||||
nextSequence,
|
||||
pendingBySequence,
|
||||
}): [Array<OrchestrationEvent>, SequenceState] => {
|
||||
if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
|
||||
return [[], { nextSequence, pendingBySequence }];
|
||||
}
|
||||
|
||||
const updatedPending = new Map(pendingBySequence);
|
||||
updatedPending.set(event.sequence, event);
|
||||
|
||||
const emit: Array<OrchestrationEvent> = [];
|
||||
let expected = nextSequence;
|
||||
for (;;) {
|
||||
const expectedEvent = updatedPending.get(expected);
|
||||
if (!expectedEvent) {
|
||||
break;
|
||||
}
|
||||
emit.push(expectedEvent);
|
||||
updatedPending.delete(expected);
|
||||
expected += 1;
|
||||
}
|
||||
|
||||
return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
|
||||
},
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot,
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
|
||||
observeRpcStreamEffect(
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
Effect.gen(function* () {
|
||||
const [threadDetail, snapshotSequence] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to load thread ${input.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Stream.flatMap((events) => Stream.fromIterable(events)),
|
||||
orchestrationEngine
|
||||
.getReadModel()
|
||||
.pipe(Effect.map((readModel) => readModel.snapshotSequence)),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
return yield* new OrchestrationGetSnapshotError({
|
||||
message: `Thread ${input.threadId} was not found`,
|
||||
cause: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === "thread" &&
|
||||
event.aggregateId === input.threadId &&
|
||||
isThreadDetailEvent(event),
|
||||
),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: {
|
||||
snapshotSequence,
|
||||
thread: threadDetail.value,
|
||||
},
|
||||
}),
|
||||
liveStream,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test:browser:install": "playwright install --with-deps chromium",
|
||||
"test:perf": "vitest run --config vitest.perf.config.ts",
|
||||
"test:perf:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
@@ -21,6 +23,7 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -29,7 +32,6 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
@@ -424,7 +424,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
|
||||
});
|
||||
|
||||
it("revalidates the server session state after a previous authenticated result", async () => {
|
||||
it("memoizes the authenticated gate state after the first successful read", async () => {
|
||||
const fetchMock = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
@@ -459,15 +459,9 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
status: "authenticated",
|
||||
});
|
||||
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
|
||||
status: "requires-auth",
|
||||
auth: {
|
||||
policy: "loopback-browser",
|
||||
bootstrapMethods: ["one-time-token"],
|
||||
sessionMethods: ["browser-session-cookie"],
|
||||
sessionCookieName: "t3_session",
|
||||
},
|
||||
status: "authenticated",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates a pairing credential from the authenticated auth endpoint", async () => {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 600,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when within the auto-scroll threshold", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the user is meaningfully above the bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 520,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clamps negative thresholds to zero", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 539,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
-1,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the default threshold for non-finite values", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
Number.NaN,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
|
||||
|
||||
interface ScrollPosition {
|
||||
scrollTop: number;
|
||||
clientHeight: number;
|
||||
scrollHeight: number;
|
||||
}
|
||||
|
||||
export function isScrollContainerNearBottom(
|
||||
position: ScrollPosition,
|
||||
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
): boolean {
|
||||
const threshold = Number.isFinite(thresholdPx)
|
||||
? Math.max(0, thresholdPx)
|
||||
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
|
||||
const { scrollTop, clientHeight, scrollHeight } = position;
|
||||
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
|
||||
return distanceFromBottom <= threshold;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
interface CommandPaletteStore {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
}
|
||||
|
||||
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
|
||||
open: false,
|
||||
setOpen: (open) => set({ open }),
|
||||
toggleOpen: () => set((state) => ({ open: !state.open })),
|
||||
}));
|
||||
@@ -44,7 +44,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
);
|
||||
const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
|
||||
const serverThread = useStore(serverThreadSelector);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const activeProjectRef = serverThread
|
||||
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
|
||||
: draftThread
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
type CSSProperties,
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
@@ -38,6 +37,7 @@ import {
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxListVirtualized,
|
||||
ComboboxPopup,
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
@@ -91,7 +91,9 @@ export function BranchToolbarBranchSelector({
|
||||
const serverThread = useStore(serverThreadSelector);
|
||||
const serverSession = serverThread?.session ?? null;
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
|
||||
const activeProjectRef = serverThread
|
||||
@@ -388,7 +390,7 @@ export function BranchToolbarBranchSelector({
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / virtualizer plumbing
|
||||
// Combobox / list plumbing
|
||||
// ---------------------------------------------------------------------------
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
@@ -423,49 +425,22 @@ export function BranchToolbarBranchSelector({
|
||||
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
|
||||
const branchListVirtualizer = useVirtualizer({
|
||||
count: filteredBranchPickerItems.length,
|
||||
estimateSize: (index) =>
|
||||
filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
|
||||
getScrollElement: () => branchListScrollElementRef.current,
|
||||
overscan: 12,
|
||||
enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
|
||||
initialRect: {
|
||||
height: 224,
|
||||
width: 0,
|
||||
},
|
||||
});
|
||||
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||
const setBranchListRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current =
|
||||
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
if (element) {
|
||||
branchListVirtualizer.measure();
|
||||
}
|
||||
},
|
||||
[branchListVirtualizer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
|
||||
queueMicrotask(() => {
|
||||
branchListVirtualizer.measure();
|
||||
});
|
||||
}, [
|
||||
branchListVirtualizer,
|
||||
filteredBranchPickerItems.length,
|
||||
isBranchMenuOpen,
|
||||
shouldVirtualizeBranchList,
|
||||
]);
|
||||
const branchListRef = useRef<LegendListRef | null>(null);
|
||||
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
|
||||
if (shouldVirtualizeBranchList) {
|
||||
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
} else {
|
||||
branchListScrollElementRef.current?.scrollTo({ top: 0 });
|
||||
}
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollElement = branchListScrollElementRef.current;
|
||||
@@ -485,8 +460,9 @@ export function BranchToolbarBranchSelector({
|
||||
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualizeBranchList) return;
|
||||
maybeFetchNextBranchPage();
|
||||
}, [branches.length, maybeFetchNextBranchPage]);
|
||||
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
@@ -494,7 +470,7 @@ export function BranchToolbarBranchSelector({
|
||||
resolvedActiveBranch,
|
||||
});
|
||||
|
||||
function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
|
||||
function renderPickerItem(itemValue: string, index: number) {
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
@@ -502,7 +478,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => {
|
||||
if (!prReference || !onCheckoutPullRequestRequest) {
|
||||
return;
|
||||
@@ -527,7 +502,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
@@ -555,7 +529,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
style={style}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
@@ -573,8 +546,13 @@ export function BranchToolbarBranchSelector({
|
||||
autoHighlight
|
||||
virtualized={shouldVirtualizeBranchList}
|
||||
onItemHighlighted={(_value, eventDetails) => {
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
|
||||
return;
|
||||
}
|
||||
branchListRef.current?.scrollIndexIntoView?.({
|
||||
index: eventDetails.index,
|
||||
animated: false,
|
||||
});
|
||||
}}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isBranchMenuOpen}
|
||||
@@ -602,30 +580,30 @@ export function BranchToolbarBranchSelector({
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<ComboboxListVirtualized>
|
||||
<LegendList<string>
|
||||
ref={branchListRef}
|
||||
data={filteredBranchPickerItems}
|
||||
keyExtractor={(item) => item}
|
||||
renderItem={({ item, index }) => renderPickerItem(item, index)}
|
||||
estimatedItemSize={28}
|
||||
drawDistance={336}
|
||||
onEndReached={() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
void fetchNextPage().catch(() => undefined);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{virtualBranchRows.map((virtualRow) => {
|
||||
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||
if (!itemValue) return null;
|
||||
return renderPickerItem(itemValue, virtualRow.index, {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
|
||||
)}
|
||||
</ComboboxList>
|
||||
style={{ maxHeight: "14rem" }}
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
) : (
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
{filteredBranchPickerItems.map((itemValue, index) =>
|
||||
renderPickerItem(itemValue, index),
|
||||
)}
|
||||
</ComboboxList>
|
||||
)}
|
||||
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -530,6 +530,142 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running a newer turn than latestTurn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not clear local dispatch while the session is running but latestTurn has not advanced yet", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: previousLatestTurn,
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: undefined,
|
||||
updatedAt: "2026-03-29T00:01:00.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clears local dispatch once the running latestTurn matches the active session turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: previousSession,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-29T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
latestTurn: previousLatestTurn,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: {
|
||||
...previousLatestTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running",
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
session: {
|
||||
...previousSession,
|
||||
status: "running",
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.make("turn-2"),
|
||||
updatedAt: "2026-03-29T00:01:01.000Z",
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("clears local dispatch when the session changes without an observed running phase", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot({
|
||||
id: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -322,23 +322,37 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
if (!input.localDispatch) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
input.phase === "running" ||
|
||||
input.hasPendingApproval ||
|
||||
input.hasPendingUserInput ||
|
||||
Boolean(input.threadError)
|
||||
) {
|
||||
if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
|
||||
return (
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
if (!latestTurnChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== undefined &&
|
||||
session.activeTurnId !== null &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
);
|
||||
|
||||
@@ -28,7 +28,8 @@ import {
|
||||
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useGitStatus } from "~/lib/gitStatusState";
|
||||
@@ -57,7 +58,7 @@ import {
|
||||
isLatestTurnSettled,
|
||||
formatElapsed,
|
||||
} from "../session-logic";
|
||||
import { isScrollContainerNearBottom } from "../chat-scroll";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingUserInputProgress,
|
||||
@@ -89,6 +90,7 @@ import {
|
||||
} from "../types";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
@@ -160,19 +162,20 @@ import {
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
import { useComposerHandleContext } from "../composerHandleContext";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerConfig,
|
||||
useServerKeybindings,
|
||||
} from "~/rpc/serverState";
|
||||
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
|
||||
import { retainThreadDetailSubscription } from "../environments/runtime/service";
|
||||
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_PROPOSED_PLANS: Thread["proposedPlans"] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID: Record<string, boolean> = {};
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
|
||||
@@ -310,12 +313,16 @@ type ChatViewProps =
|
||||
| {
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
onDiffPanelOpen?: () => void;
|
||||
reserveTitleBarControlInset?: boolean;
|
||||
routeKind: "server";
|
||||
draftId?: never;
|
||||
}
|
||||
| {
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
onDiffPanelOpen?: () => void;
|
||||
reserveTitleBarControlInset?: boolean;
|
||||
routeKind: "draft";
|
||||
draftId: DraftId;
|
||||
};
|
||||
@@ -569,7 +576,13 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
});
|
||||
|
||||
export default function ChatView(props: ChatViewProps) {
|
||||
const { environmentId, threadId, routeKind } = props;
|
||||
const {
|
||||
environmentId,
|
||||
threadId,
|
||||
routeKind,
|
||||
onDiffPanelOpen,
|
||||
reserveTitleBarControlInset = true,
|
||||
} = props;
|
||||
const draftId = routeKind === "draft" ? props.draftId : null;
|
||||
const routeThreadRef = useMemo(
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
@@ -586,18 +599,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const setThreadChangedFilesExpanded = useUiStateStore(
|
||||
(store) => store.setThreadChangedFilesExpanded,
|
||||
);
|
||||
const activeThreadLastVisitedAt = useUiStateStore((store) =>
|
||||
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
|
||||
);
|
||||
const changedFilesExpandedByTurnId = useUiStateStore((store) =>
|
||||
routeKind === "server"
|
||||
? (store.threadChangedFilesExpandedById[routeThreadKey] ??
|
||||
EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID)
|
||||
: EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID,
|
||||
);
|
||||
const settings = useSettings();
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
@@ -648,7 +652,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const promptRef = useRef("");
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
const composerRef = useRef<ChatComposerHandle>(null);
|
||||
const localComposerRef = useRef<ChatComposerHandle | null>(null);
|
||||
const composerRef = useComposerHandleContext() ?? localComposerRef;
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
@@ -668,14 +673,12 @@ export default function ChatView(props: ChatViewProps) {
|
||||
>({});
|
||||
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
|
||||
useState<Record<string, number>>({});
|
||||
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
|
||||
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
|
||||
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
|
||||
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
|
||||
// When set, the thread-change reset effect will open the sidebar instead of closing it.
|
||||
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
|
||||
const planSidebarOpenOnNextThreadRef = useRef(false);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const [pullRequestDialogState, setPullRequestDialogState] =
|
||||
useState<PullRequestDialogState | null>(null);
|
||||
@@ -690,27 +693,12 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{},
|
||||
LastInvokedScriptByProjectSchema,
|
||||
);
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const [messagesScrollElement, setMessagesScrollElement] = useState<HTMLDivElement | null>(null);
|
||||
const shouldAutoScrollRef = useRef(true);
|
||||
const lastKnownScrollTopRef = useRef(0);
|
||||
const isPointerScrollActiveRef = useRef(false);
|
||||
const lastTouchClientYRef = useRef<number | null>(null);
|
||||
const pendingUserScrollUpIntentRef = useRef(false);
|
||||
const pendingAutoScrollFrameRef = useRef<number | null>(null);
|
||||
const pendingInteractionAnchorRef = useRef<{
|
||||
element: HTMLElement;
|
||||
top: number;
|
||||
} | null>(null);
|
||||
const pendingInteractionAnchorFrameRef = useRef<number | null>(null);
|
||||
const legendListRef = useRef<LegendListRef | null>(null);
|
||||
const isAtEndRef = useRef(true);
|
||||
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
|
||||
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
|
||||
const sendInFlightRef = useRef(false);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const setMessagesScrollContainerRef = useCallback((element: HTMLDivElement | null) => {
|
||||
messagesScrollRef.current = element;
|
||||
setMessagesScrollElement(element);
|
||||
}, []);
|
||||
|
||||
const terminalState = useTerminalStateStore((state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
|
||||
@@ -838,6 +826,13 @@ export default function ChatView(props: ChatViewProps) {
|
||||
useMemo(() => createProjectSelectorByRef(activeProjectRef), [activeProjectRef]),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (routeKind !== "server") {
|
||||
return;
|
||||
}
|
||||
return retainThreadDetailSubscription(environmentId, threadId);
|
||||
}, [environmentId, routeKind, threadId]);
|
||||
|
||||
// Compute the list of environments this logical project spans, used to
|
||||
// drive the environment picker in BranchToolbar.
|
||||
const allProjects = useStore(useShallow(selectProjectsAcrossEnvironments));
|
||||
@@ -990,16 +985,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
[openOrReuseProjectDraftThread],
|
||||
);
|
||||
|
||||
const handleSetChangedFilesExpanded = useCallback(
|
||||
(turnId: TurnId, expanded: boolean) => {
|
||||
if (routeKind !== "server") {
|
||||
return;
|
||||
}
|
||||
setThreadChangedFilesExpanded(routeThreadKey, turnId, expanded);
|
||||
},
|
||||
[routeKind, routeThreadKey, setThreadChangedFilesExpanded],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverThread?.id) return;
|
||||
if (!latestTurnSettled) return;
|
||||
@@ -1139,7 +1124,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadError: activeThread?.error,
|
||||
});
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
@@ -1470,6 +1454,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (!isServerThread) {
|
||||
return;
|
||||
}
|
||||
if (!diffOpen) {
|
||||
onDiffPanelOpen?.();
|
||||
}
|
||||
void navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
@@ -1482,7 +1469,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return diffOpen ? { ...rest, diff: undefined } : { ...rest, diff: "1" };
|
||||
},
|
||||
});
|
||||
}, [diffOpen, environmentId, isServerThread, navigate, threadId]);
|
||||
}, [diffOpen, environmentId, isServerThread, navigate, onDiffPanelOpen, threadId]);
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
@@ -1962,169 +1949,33 @@ export default function ChatView(props: ChatViewProps) {
|
||||
[environmentId, serverThread],
|
||||
);
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageCount = timelineMessages.length;
|
||||
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
|
||||
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
|
||||
shouldAutoScrollRef.current = true;
|
||||
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
|
||||
const scrollToEnd = useCallback((animated = false) => {
|
||||
legendListRef.current?.scrollToEnd?.({ animated });
|
||||
}, []);
|
||||
const cancelPendingStickToBottom = useCallback(() => {
|
||||
const pendingFrame = pendingAutoScrollFrameRef.current;
|
||||
if (pendingFrame === null) return;
|
||||
pendingAutoScrollFrameRef.current = null;
|
||||
window.cancelAnimationFrame(pendingFrame);
|
||||
}, []);
|
||||
const cancelPendingInteractionAnchorAdjustment = useCallback(() => {
|
||||
const pendingFrame = pendingInteractionAnchorFrameRef.current;
|
||||
if (pendingFrame === null) return;
|
||||
pendingInteractionAnchorFrameRef.current = null;
|
||||
window.cancelAnimationFrame(pendingFrame);
|
||||
}, []);
|
||||
const scheduleStickToBottom = useCallback(() => {
|
||||
if (pendingAutoScrollFrameRef.current !== null) return;
|
||||
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
|
||||
pendingAutoScrollFrameRef.current = null;
|
||||
scrollMessagesToBottom();
|
||||
});
|
||||
}, [scrollMessagesToBottom]);
|
||||
const onMessagesClickCapture = useCallback(
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer || !(event.target instanceof Element)) return;
|
||||
|
||||
const trigger = event.target.closest<HTMLElement>(
|
||||
"button, summary, [role='button'], [data-scroll-anchor-target]",
|
||||
);
|
||||
if (!trigger || !scrollContainer.contains(trigger)) return;
|
||||
if (trigger.closest("[data-scroll-anchor-ignore]")) return;
|
||||
|
||||
pendingInteractionAnchorRef.current = {
|
||||
element: trigger,
|
||||
top: trigger.getBoundingClientRect().top,
|
||||
};
|
||||
|
||||
cancelPendingInteractionAnchorAdjustment();
|
||||
pendingInteractionAnchorFrameRef.current = window.requestAnimationFrame(() => {
|
||||
pendingInteractionAnchorFrameRef.current = null;
|
||||
const anchor = pendingInteractionAnchorRef.current;
|
||||
pendingInteractionAnchorRef.current = null;
|
||||
const activeScrollContainer = messagesScrollRef.current;
|
||||
if (!anchor || !activeScrollContainer) return;
|
||||
if (!anchor.element.isConnected || !activeScrollContainer.contains(anchor.element)) return;
|
||||
|
||||
const nextTop = anchor.element.getBoundingClientRect().top;
|
||||
const delta = nextTop - anchor.top;
|
||||
if (Math.abs(delta) < 0.5) return;
|
||||
|
||||
activeScrollContainer.scrollTop += delta;
|
||||
lastKnownScrollTopRef.current = activeScrollContainer.scrollTop;
|
||||
});
|
||||
},
|
||||
[cancelPendingInteractionAnchorAdjustment],
|
||||
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
|
||||
// thread switches. LegendList fires scroll events with isAtEnd=false while
|
||||
// initialScrollAtEnd is settling; hiding is always immediate.
|
||||
const showScrollDebouncer = useRef(
|
||||
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
|
||||
);
|
||||
const forceStickToBottom = useCallback(() => {
|
||||
cancelPendingStickToBottom();
|
||||
scrollMessagesToBottom();
|
||||
scheduleStickToBottom();
|
||||
}, [cancelPendingStickToBottom, scheduleStickToBottom, scrollMessagesToBottom]);
|
||||
const onMessagesScroll = useCallback(() => {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
const currentScrollTop = scrollContainer.scrollTop;
|
||||
const isNearBottom = isScrollContainerNearBottom(scrollContainer);
|
||||
|
||||
if (!shouldAutoScrollRef.current && isNearBottom) {
|
||||
shouldAutoScrollRef.current = true;
|
||||
pendingUserScrollUpIntentRef.current = false;
|
||||
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp && !isNearBottom) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
pendingUserScrollUpIntentRef.current = false;
|
||||
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp && !isNearBottom) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
} else if (shouldAutoScrollRef.current && !isNearBottom) {
|
||||
// Catch-all for keyboard/assistive scroll interactions.
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
setShowScrollToBottom(!shouldAutoScrollRef.current);
|
||||
lastKnownScrollTopRef.current = currentScrollTop;
|
||||
}, []);
|
||||
const onMessagesWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
|
||||
if (event.deltaY < 0) {
|
||||
pendingUserScrollUpIntentRef.current = true;
|
||||
const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
|
||||
if (isAtEndRef.current === isAtEnd) return;
|
||||
isAtEndRef.current = isAtEnd;
|
||||
if (isAtEnd) {
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
} else {
|
||||
showScrollDebouncer.current.maybeExecute();
|
||||
}
|
||||
}, []);
|
||||
const onMessagesPointerDown = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = true;
|
||||
}, []);
|
||||
const onMessagesPointerUp = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = false;
|
||||
}, []);
|
||||
const onMessagesPointerCancel = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = false;
|
||||
}, []);
|
||||
const onMessagesTouchStart = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
lastTouchClientYRef.current = touch.clientY;
|
||||
}, []);
|
||||
const onMessagesTouchMove = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
const previousTouchY = lastTouchClientYRef.current;
|
||||
if (previousTouchY !== null && touch.clientY > previousTouchY + 1) {
|
||||
pendingUserScrollUpIntentRef.current = true;
|
||||
}
|
||||
lastTouchClientYRef.current = touch.clientY;
|
||||
}, []);
|
||||
const onMessagesTouchEnd = useCallback((_event: React.TouchEvent<HTMLDivElement>) => {
|
||||
lastTouchClientYRef.current = null;
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cancelPendingStickToBottom();
|
||||
cancelPendingInteractionAnchorAdjustment();
|
||||
};
|
||||
}, [cancelPendingInteractionAnchorAdjustment, cancelPendingStickToBottom]);
|
||||
useLayoutEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
shouldAutoScrollRef.current = true;
|
||||
scheduleStickToBottom();
|
||||
const timeout = window.setTimeout(() => {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
if (isScrollContainerNearBottom(scrollContainer)) return;
|
||||
scheduleStickToBottom();
|
||||
}, 96);
|
||||
return () => {
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
}, [activeThread?.id, scheduleStickToBottom]);
|
||||
useEffect(() => {
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
}, [messageCount, scheduleStickToBottom]);
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
}, [phase, scheduleStickToBottom, timelineEntries]);
|
||||
|
||||
useEffect(() => {
|
||||
setExpandedWorkGroups({});
|
||||
setPullRequestDialogState(null);
|
||||
isAtEndRef.current = true;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
if (planSidebarOpenOnNextThreadRef.current) {
|
||||
planSidebarOpenOnNextThreadRef.current = false;
|
||||
setPlanSidebarOpen(true);
|
||||
@@ -2282,16 +2133,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
terminalState.terminalOpen,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
const timer = window.setInterval(() => {
|
||||
setNowTick(Date.now());
|
||||
}, 1000);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadKey) return;
|
||||
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
|
||||
@@ -2316,7 +2157,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (!activeThreadId || event.defaultPrevented) return;
|
||||
if (!activeThreadId || useCommandPaletteStore.getState().open || event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
const shortcutContext = {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: Boolean(terminalState.terminalOpen),
|
||||
@@ -2565,6 +2408,14 @@ export default function ChatView(props: ChatViewProps) {
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
// Scroll to the current end *before* adding the optimistic message.
|
||||
// This sets LegendList's internal isAtEnd=true so maintainScrollAtEnd
|
||||
// automatically pins to the new item when the data changes.
|
||||
isAtEndRef.current = true;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
await legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
{
|
||||
@@ -2576,9 +2427,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
// Sending a message should always bring the latest user turn into view.
|
||||
shouldAutoScrollRef.current = true;
|
||||
forceStickToBottom();
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
@@ -2959,6 +2807,13 @@ export default function ChatView(props: ChatViewProps) {
|
||||
sendInFlightRef.current = true;
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
setThreadError(threadIdForSend, null);
|
||||
|
||||
// Scroll to the current end *before* adding the optimistic message.
|
||||
isAtEndRef.current = true;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
await legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
{
|
||||
@@ -2969,8 +2824,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
shouldAutoScrollRef.current = true;
|
||||
forceStickToBottom();
|
||||
|
||||
try {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
@@ -3036,7 +2889,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
activeThread,
|
||||
activeProposedPlan,
|
||||
beginLocalDispatch,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
@@ -3231,12 +3083,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
],
|
||||
);
|
||||
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
setExpandedWorkGroups((existing) => ({
|
||||
...existing,
|
||||
[groupId]: !existing[groupId],
|
||||
}));
|
||||
}, []);
|
||||
const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
|
||||
setExpandedImage(preview);
|
||||
}, []);
|
||||
@@ -3245,6 +3091,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (!isServerThread) {
|
||||
return;
|
||||
}
|
||||
onDiffPanelOpen?.();
|
||||
void navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: {
|
||||
@@ -3259,18 +3106,21 @@ export default function ChatView(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
},
|
||||
[environmentId, isServerThread, navigate, threadId],
|
||||
);
|
||||
const onRevertUserMessage = useCallback(
|
||||
(messageId: MessageId) => {
|
||||
const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
|
||||
if (typeof targetTurnCount !== "number") {
|
||||
return;
|
||||
}
|
||||
void onRevertToTurnCount(targetTurnCount);
|
||||
},
|
||||
[onRevertToTurnCount, revertTurnCountByUserMessageId],
|
||||
[environmentId, isServerThread, navigate, onDiffPanelOpen, threadId],
|
||||
);
|
||||
// Both the Map and the revert handler are read from refs at call-time so
|
||||
// the callback reference is fully stable and never busts context identity.
|
||||
const revertTurnCountRef = useRef(revertTurnCountByUserMessageId);
|
||||
revertTurnCountRef.current = revertTurnCountByUserMessageId;
|
||||
const onRevertToTurnCountRef = useRef(onRevertToTurnCount);
|
||||
onRevertToTurnCountRef.current = onRevertToTurnCount;
|
||||
const onRevertUserMessage = useCallback((messageId: MessageId) => {
|
||||
const targetTurnCount = revertTurnCountRef.current.get(messageId);
|
||||
if (typeof targetTurnCount !== "number") {
|
||||
return;
|
||||
}
|
||||
void onRevertToTurnCountRef.current(targetTurnCount);
|
||||
}, []);
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
@@ -3278,17 +3128,27 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<div
|
||||
className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background"
|
||||
data-testid={`chat-thread-${activeThread.id}`}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron ? "drag-region flex h-[52px] items-center" : "py-2 sm:py-3",
|
||||
isElectron
|
||||
? cn(
|
||||
"drag-region flex h-[52px] items-center wco:h-[env(titlebar-area-height)]",
|
||||
reserveTitleBarControlInset &&
|
||||
"wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
)
|
||||
: "py-2 sm:py-3",
|
||||
)}
|
||||
>
|
||||
<ChatHeader
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
activeThreadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isGitRepo={isGitRepo}
|
||||
@@ -3326,56 +3186,39 @@ export default function ChatView(props: ChatViewProps) {
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
{/* Messages Wrapper */}
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={setMessagesScrollContainerRef}
|
||||
className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 py-3 sm:px-5 sm:py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
onClickCapture={onMessagesClickCapture}
|
||||
onWheel={onMessagesWheel}
|
||||
onPointerDown={onMessagesPointerDown}
|
||||
onPointerUp={onMessagesPointerUp}
|
||||
onPointerCancel={onMessagesPointerCancel}
|
||||
onTouchStart={onMessagesTouchStart}
|
||||
onTouchMove={onMessagesTouchMove}
|
||||
onTouchEnd={onMessagesTouchEnd}
|
||||
onTouchCancel={onMessagesTouchEnd}
|
||||
>
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
scrollContainer={messagesScrollElement}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
nowIso={nowIso}
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
expandedWorkGroups={expandedWorkGroups}
|
||||
onToggleWorkGroup={onToggleWorkGroup}
|
||||
changedFilesExpandedByTurnId={changedFilesExpandedByTurnId}
|
||||
onSetChangedFilesExpanded={handleSetChangedFilesExpanded}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
onRevertUserMessage={onRevertUserMessage}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
timestampFormat={timestampFormat}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
/>
|
||||
</div>
|
||||
{/* Messages — LegendList handles virtualization and scrolling internally */}
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnId={activeLatestTurn?.turnId ?? null}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
routeThreadKey={routeThreadKey}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
onRevertUserMessage={onRevertUserMessage}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
timestampFormat={timestampFormat}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
onIsAtEndChange={onIsAtEndChange}
|
||||
/>
|
||||
|
||||
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
|
||||
{showScrollToBottom && (
|
||||
<div className="pointer-events-none absolute bottom-1 left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => scrollMessagesToBottom("smooth")}
|
||||
onClick={() => scrollToEnd(true)}
|
||||
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
|
||||
>
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
@@ -3430,8 +3273,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
shouldAutoScrollRef={shouldAutoScrollRef}
|
||||
scheduleStickToBottom={scheduleStickToBottom}
|
||||
shouldAutoScrollRef={isAtEndRef}
|
||||
scheduleStickToBottom={scrollToEnd}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
buildThreadActionItems,
|
||||
filterCommandPaletteGroups,
|
||||
type CommandPaletteGroup,
|
||||
} from "./CommandPalette.logic";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
codexThreadId: null,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
it("orders threads by most recent activity and formats timestamps from updatedAt", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-25T12:00:00.000Z"));
|
||||
|
||||
try {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-older"),
|
||||
title: "Older thread",
|
||||
updatedAt: "2026-03-24T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-newer"),
|
||||
title: "Newer thread",
|
||||
createdAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-older",
|
||||
"thread:thread-newer",
|
||||
]);
|
||||
expect(items[0]?.timestamp).toBe("1d ago");
|
||||
expect(items[1]?.timestamp).toBe("5d ago");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ranks thread title matches ahead of contextual project-name matches", () => {
|
||||
const threadItems = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-context-match"),
|
||||
title: "Fix navbar spacing",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-title-match"),
|
||||
title: "Project kickoff notes",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: threadItems,
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.value).toBe("threads-search");
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual([
|
||||
"thread:thread-title-match",
|
||||
"thread:thread-context-match",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves thread project-name matches when there is no stronger title match", () => {
|
||||
const group: CommandPaletteGroup = {
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: [
|
||||
{
|
||||
kind: "action",
|
||||
value: "thread:project-context-only",
|
||||
searchTerms: ["Fix navbar spacing", "Project"],
|
||||
title: "Fix navbar spacing",
|
||||
description: "Project",
|
||||
icon: null,
|
||||
run: async () => undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const groups = filterCommandPaletteGroups({
|
||||
activeGroups: [group],
|
||||
query: "project",
|
||||
isInSubmenu: false,
|
||||
projectSearchItems: [],
|
||||
threadSearchItems: [],
|
||||
});
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
|
||||
});
|
||||
|
||||
it("filters archived threads out of thread search items", () => {
|
||||
const items = buildThreadActionItems({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-active"),
|
||||
title: "Active thread",
|
||||
createdAt: "2026-03-02T00:00:00.000Z",
|
||||
updatedAt: "2026-03-19T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-archived"),
|
||||
title: "Archived thread",
|
||||
archivedAt: "2026-03-20T00:00:00.000Z",
|
||||
updatedAt: "2026-03-20T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
projectTitleById: new Map([[PROJECT_ID, "Project"]]),
|
||||
sortOrder: "updated_at",
|
||||
icon: null,
|
||||
runThread: async (_thread) => undefined,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
import { type KeybindingCommand } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
|
||||
|
||||
export const RECENT_THREAD_LIMIT = 12;
|
||||
export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
|
||||
export const ADDON_ICON_CLASS = "size-4";
|
||||
|
||||
export interface CommandPaletteItem {
|
||||
readonly kind: "action" | "submenu";
|
||||
readonly value: string;
|
||||
readonly searchTerms: ReadonlyArray<string>;
|
||||
readonly title: ReactNode;
|
||||
readonly description?: string;
|
||||
readonly timestamp?: string;
|
||||
readonly icon: ReactNode;
|
||||
readonly shortcutCommand?: KeybindingCommand;
|
||||
}
|
||||
|
||||
export interface CommandPaletteActionItem extends CommandPaletteItem {
|
||||
readonly kind: "action";
|
||||
readonly keepOpen?: boolean;
|
||||
readonly run: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
|
||||
readonly kind: "submenu";
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export interface CommandPaletteGroup {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
}
|
||||
|
||||
export interface CommandPaletteView {
|
||||
readonly addonIcon: ReactNode;
|
||||
readonly groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export type CommandPaletteMode = "root" | "submenu";
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function buildProjectActionItems(input: {
|
||||
projects: ReadonlyArray<Project>;
|
||||
valuePrefix: string;
|
||||
icon: (project: Project) => ReactNode;
|
||||
runProject: (project: Project) => Promise<void>;
|
||||
}): CommandPaletteActionItem[] {
|
||||
return input.projects.map((project) => ({
|
||||
kind: "action",
|
||||
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
|
||||
searchTerms: [project.name, project.cwd],
|
||||
title: project.name,
|
||||
description: project.cwd,
|
||||
icon: input.icon(project),
|
||||
run: async () => {
|
||||
await input.runProject(project);
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildThreadActionItems(input: {
|
||||
threads: ReadonlyArray<
|
||||
Pick<
|
||||
SidebarThreadSummary,
|
||||
"archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
|
||||
> & {
|
||||
updatedAt?: string | undefined;
|
||||
latestUserMessageAt?: string | null;
|
||||
}
|
||||
>;
|
||||
activeThreadId?: Thread["id"];
|
||||
projectTitleById: ReadonlyMap<Project["id"], string>;
|
||||
sortOrder: SidebarThreadSortOrder;
|
||||
icon: ReactNode;
|
||||
runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
|
||||
limit?: number;
|
||||
}): CommandPaletteActionItem[] {
|
||||
const sortedThreads = sortThreads(
|
||||
input.threads.filter((thread) => thread.archivedAt === null),
|
||||
input.sortOrder,
|
||||
);
|
||||
const visibleThreads =
|
||||
input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
|
||||
|
||||
return visibleThreads.map((thread) => {
|
||||
const projectTitle = input.projectTitleById.get(thread.projectId);
|
||||
const descriptionParts: string[] = [];
|
||||
|
||||
if (projectTitle) {
|
||||
descriptionParts.push(projectTitle);
|
||||
}
|
||||
if (thread.branch) {
|
||||
descriptionParts.push(`#${thread.branch}`);
|
||||
}
|
||||
if (thread.id === input.activeThreadId) {
|
||||
descriptionParts.push("Current thread");
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "action",
|
||||
value: `thread:${thread.id}`,
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt),
|
||||
icon: input.icon,
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
|
||||
const normalizedField = normalizeSearchText(field);
|
||||
if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
|
||||
return Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
if (normalizedField === normalizedQuery) {
|
||||
return 3;
|
||||
}
|
||||
if (normalizedField.startsWith(normalizedQuery)) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function rankCommandPaletteItemMatch(
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
|
||||
normalizedQuery: string,
|
||||
): number {
|
||||
const terms = item.searchTerms.filter((term) => term.length > 0);
|
||||
if (terms.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const [index, field] of terms.entries()) {
|
||||
const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
|
||||
if (fieldRank !== Number.NEGATIVE_INFINITY) {
|
||||
return 1_000 - index * 100 + fieldRank;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function filterCommandPaletteGroups(input: {
|
||||
activeGroups: ReadonlyArray<CommandPaletteGroup>;
|
||||
query: string;
|
||||
isInSubmenu: boolean;
|
||||
projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const isActionsFilter = input.query.startsWith(">");
|
||||
const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
|
||||
const normalizedQuery = normalizeSearchText(searchQuery);
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
if (isActionsFilter) {
|
||||
return input.activeGroups.filter((group) => group.value === "actions");
|
||||
}
|
||||
return [...input.activeGroups];
|
||||
}
|
||||
|
||||
let baseGroups = [...input.activeGroups];
|
||||
if (isActionsFilter) {
|
||||
baseGroups = baseGroups.filter((group) => group.value === "actions");
|
||||
} else if (!input.isInSubmenu) {
|
||||
baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
|
||||
}
|
||||
|
||||
const searchableGroups = [...baseGroups];
|
||||
if (!input.isInSubmenu && !isActionsFilter) {
|
||||
if (input.projectSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "projects-search",
|
||||
label: "Projects",
|
||||
items: input.projectSearchItems,
|
||||
});
|
||||
}
|
||||
if (input.threadSearchItems.length > 0) {
|
||||
searchableGroups.push({
|
||||
value: "threads-search",
|
||||
label: "Threads",
|
||||
items: input.threadSearchItems,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return searchableGroups.flatMap((group) => {
|
||||
const items = group.items
|
||||
.map((item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
|
||||
entry !== null,
|
||||
)
|
||||
.toSorted((left, right) => right.rank - left.rank || left.index - right.index)
|
||||
.map((entry) => entry.item);
|
||||
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ value: group.value, label: group.label, items }];
|
||||
});
|
||||
}
|
||||
|
||||
export function getCommandPaletteMode(input: {
|
||||
currentView: CommandPaletteView | null;
|
||||
}): CommandPaletteMode {
|
||||
return input.currentView ? "submenu" : "root";
|
||||
}
|
||||
|
||||
export function buildRootGroups(input: {
|
||||
actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
|
||||
recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
|
||||
}): CommandPaletteGroup[] {
|
||||
const groups: CommandPaletteGroup[] = [];
|
||||
if (input.actionItems.length > 0) {
|
||||
groups.push({ value: "actions", label: "Actions", items: input.actionItems });
|
||||
}
|
||||
if (input.recentThreadItems.length > 0) {
|
||||
groups.push({
|
||||
value: "recent-threads",
|
||||
label: "Recent Threads",
|
||||
items: input.recentThreadItems,
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
|
||||
switch (mode) {
|
||||
case "root":
|
||||
return "Search commands, projects, and threads...";
|
||||
case "submenu":
|
||||
return "Search...";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { ProjectId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowUpIcon,
|
||||
MessageSquareIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectSidebarThreadsAcrossEnvironments,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildProjectActionItems,
|
||||
buildRootGroups,
|
||||
buildThreadActionItems,
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteSubmenuItem,
|
||||
type CommandPaletteView,
|
||||
filterCommandPaletteGroups,
|
||||
getCommandPaletteInputPlaceholder,
|
||||
getCommandPaletteMode,
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandDialogPopup,
|
||||
CommandFooter,
|
||||
CommandInput,
|
||||
CommandPanel,
|
||||
} from "./ui/command";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
|
||||
const keybindings = useServerKeybindings();
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useTerminalStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
context: {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen,
|
||||
},
|
||||
});
|
||||
if (command !== "commandPalette.toggle") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOpen();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<ComposerHandleContext.Provider value={composerHandleRef}>
|
||||
<CommandDialog open={open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog />
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteDialog() {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setOpen(false);
|
||||
};
|
||||
}, [setOpen]);
|
||||
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <OpenCommandPaletteDialog />;
|
||||
}
|
||||
|
||||
function OpenCommandPaletteDialog() {
|
||||
const navigate = useNavigate();
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const isActionsOnly = deferredQuery.startsWith(">");
|
||||
const settings = useSettings();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
|
||||
const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments));
|
||||
const keybindings = useServerKeybindings();
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const paletteMode = getCommandPaletteMode({ currentView });
|
||||
|
||||
const projectTitleById = useMemo(
|
||||
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
|
||||
[projects],
|
||||
);
|
||||
|
||||
const activeThreadId = activeThread?.id;
|
||||
const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === project.environmentId),
|
||||
project.id,
|
||||
settings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(
|
||||
scopeThreadRef(latestThread.environmentId, latestThread.id),
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
|
||||
envMode: settings.defaultThreadEnvMode,
|
||||
});
|
||||
},
|
||||
[
|
||||
handleNewThread,
|
||||
navigate,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const projectSearchItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "project",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: openProjectFromSearch,
|
||||
}),
|
||||
[openProjectFromSearch, projects],
|
||||
);
|
||||
|
||||
const projectThreadItems = useMemo(
|
||||
() =>
|
||||
buildProjectActionItems({
|
||||
projects,
|
||||
valuePrefix: "new-thread-in",
|
||||
icon: (project) => (
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.cwd}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
),
|
||||
runProject: async (project) => {
|
||||
await startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
handleNewThread,
|
||||
projects,
|
||||
settings.defaultThreadEnvMode,
|
||||
],
|
||||
);
|
||||
|
||||
const allThreadItems = useMemo(
|
||||
() =>
|
||||
buildThreadActionItems({
|
||||
threads,
|
||||
...(activeThreadId ? { activeThreadId } : {}),
|
||||
projectTitleById,
|
||||
sortOrder: settings.sidebarThreadSortOrder,
|
||||
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
|
||||
runThread: async (thread) => {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
});
|
||||
},
|
||||
}),
|
||||
[activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
|
||||
);
|
||||
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: item.addonIcon,
|
||||
groups: item.groups,
|
||||
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setQuery(item.initialQuery ?? "");
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
setViewStack((previousViews) => previousViews.slice(0, -1));
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function handleQueryChange(nextQuery: string): void {
|
||||
setQuery(nextQuery);
|
||||
if (nextQuery === "" && currentView?.initialQuery) {
|
||||
popView();
|
||||
}
|
||||
}
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
const activeProjectTitle = currentProjectId
|
||||
? (projectTitleById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
|
||||
if (activeProjectTitle) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:new-thread",
|
||||
searchTerms: ["new thread", "chat", "create", "draft"],
|
||||
title: (
|
||||
<>
|
||||
New thread in <span className="font-semibold">{activeProjectTitle}</span>
|
||||
</>
|
||||
),
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
shortcutCommand: "chat.new",
|
||||
run: async () => {
|
||||
await startNewThreadFromContext({
|
||||
activeDraftThread,
|
||||
activeThread,
|
||||
defaultProjectRef,
|
||||
defaultThreadEnvMode: settings.defaultThreadEnvMode,
|
||||
handleNewThread,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:new-thread-in",
|
||||
searchTerms: ["new thread", "project", "pick", "choose", "select"],
|
||||
title: "New thread in...",
|
||||
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
searchTerms: ["settings", "preferences", "configuration", "keybindings"],
|
||||
title: "Open settings",
|
||||
icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
await navigate({ to: "/settings" });
|
||||
},
|
||||
});
|
||||
|
||||
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
|
||||
const activeGroups = currentView ? currentView.groups : rootGroups;
|
||||
|
||||
const displayedGroups = filterCommandPaletteGroups({
|
||||
activeGroups,
|
||||
query: deferredQuery,
|
||||
isInSubmenu: currentView !== null,
|
||||
projectSearchItems: projectSearchItems,
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const isSubmenu = paletteMode === "submenu";
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
if (event.key === "Backspace" && query === "" && isSubmenu) {
|
||||
event.preventDefault();
|
||||
popView();
|
||||
}
|
||||
}
|
||||
|
||||
function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
|
||||
if (item.kind === "submenu") {
|
||||
pushView(item);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item.keepOpen) {
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
void item.run().catch((error: unknown) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to run command",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandDialogPopup
|
||||
aria-label="Command palette"
|
||||
className="overflow-hidden p-0"
|
||||
data-testid="command-palette"
|
||||
finalFocus={() => {
|
||||
composerHandleRef?.current?.focusAtEnd();
|
||||
return false;
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={viewStack.length}
|
||||
aria-label="Command palette"
|
||||
autoHighlight="always"
|
||||
mode="none"
|
||||
onValueChange={handleQueryChange}
|
||||
value={query}
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu
|
||||
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
|
||||
: undefined
|
||||
}
|
||||
{...(isSubmenu
|
||||
? {
|
||||
startAddon: (
|
||||
<button
|
||||
type="button"
|
||||
className="flex cursor-pointer items-center"
|
||||
aria-label="Back"
|
||||
onClick={popView}
|
||||
>
|
||||
<ArrowLeftIcon />
|
||||
</button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
<div className="flex items-center gap-3">
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>
|
||||
<ArrowUpIcon />
|
||||
</Kbd>
|
||||
<Kbd>
|
||||
<ArrowDownIcon />
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
</KbdGroup>
|
||||
{isSubmenu ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Backspace</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Back</span>
|
||||
</KbdGroup>
|
||||
) : null}
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Esc</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Close</span>
|
||||
</KbdGroup>
|
||||
</div>
|
||||
</CommandFooter>
|
||||
</Command>
|
||||
</CommandDialogPopup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { ChevronRightIcon } from "lucide-react";
|
||||
import { shortcutLabelForCommand } from "../keybindings";
|
||||
import {
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteGroup,
|
||||
type CommandPaletteSubmenuItem,
|
||||
} from "./CommandPalette.logic";
|
||||
import {
|
||||
CommandCollection,
|
||||
CommandGroup,
|
||||
CommandGroupLabel,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandShortcut,
|
||||
} from "./ui/command";
|
||||
|
||||
interface CommandPaletteResultsProps {
|
||||
emptyStateMessage?: string;
|
||||
groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
isActionsOnly: boolean;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}
|
||||
|
||||
export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
if (props.groups.length === 0) {
|
||||
return (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
{props.emptyStateMessage ??
|
||||
(props.isActionsOnly
|
||||
? "No matching actions."
|
||||
: "No matching commands, projects, or threads.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CommandList>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup items={group.items} key={group.value}>
|
||||
<CommandGroupLabel>{group.label}</CommandGroupLabel>
|
||||
<CommandCollection>
|
||||
{(item) => (
|
||||
<CommandPaletteResultRow
|
||||
item={item}
|
||||
key={item.value}
|
||||
keybindings={props.keybindings}
|
||||
onExecuteItem={props.onExecuteItem}
|
||||
/>
|
||||
)}
|
||||
</CommandCollection>
|
||||
</CommandGroup>
|
||||
))}
|
||||
</CommandList>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteResultRow(props: {
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}) {
|
||||
const shortcutLabel = props.item.shortcutCommand
|
||||
? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.value}
|
||||
className="cursor-pointer gap-2"
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
props.onExecuteItem(props.item);
|
||||
}}
|
||||
>
|
||||
{props.item.icon}
|
||||
{props.item.description ? (
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm text-foreground">{props.item.title}</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{props.item.description}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate text-sm text-foreground">
|
||||
<span className="truncate">{props.item.title}</span>
|
||||
</span>
|
||||
)}
|
||||
{props.item.timestamp ? (
|
||||
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
|
||||
{props.item.timestamp}
|
||||
</span>
|
||||
) : null}
|
||||
{shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
|
||||
{props.item.kind === "submenu" ? (
|
||||
<ChevronRightIcon className="ml-auto size-4 shrink-0 text-muted-foreground/50" />
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
|
||||
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||
import { type ServerProviderSkill } from "@t3tools/contracts";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelection,
|
||||
@@ -73,8 +74,11 @@ import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
|
||||
} from "./composerInlineChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
const SURROUND_SYMBOLS: [string, string][] = [
|
||||
@@ -102,6 +106,17 @@ type SerializedComposerMentionNode = Spread<
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
type SerializedComposerSkillNode = Spread<
|
||||
{
|
||||
skillName: string;
|
||||
skillLabel?: string;
|
||||
skillDescription?: string;
|
||||
type: "composer-skill";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
type SerializedComposerTerminalContextNode = Spread<
|
||||
{
|
||||
context: TerminalContextDraft;
|
||||
@@ -189,6 +204,155 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
const SKILL_CHIP_ICON_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
|
||||
|
||||
function resolveSkillDescription(
|
||||
skill: Pick<ServerProviderSkill, "shortDescription" | "description">,
|
||||
): string | null {
|
||||
const shortDescription = skill.shortDescription?.trim();
|
||||
if (shortDescription) {
|
||||
return shortDescription;
|
||||
}
|
||||
const description = skill.description?.trim();
|
||||
return description || null;
|
||||
}
|
||||
|
||||
type ComposerSkillMetadata = {
|
||||
label: string;
|
||||
description: string | null;
|
||||
};
|
||||
|
||||
function skillMetadataByName(
|
||||
skills: ReadonlyArray<ServerProviderSkill>,
|
||||
): ReadonlyMap<string, ComposerSkillMetadata> {
|
||||
return new Map(
|
||||
skills.map((skill) => [
|
||||
skill.name,
|
||||
{
|
||||
label: formatProviderSkillDisplayName(skill),
|
||||
description: resolveSkillDescription(skill),
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function ComposerSkillDecorator(props: { skillLabel: string; skillDescription: string | null }) {
|
||||
const chip = (
|
||||
<span
|
||||
className={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}
|
||||
contentEditable={false}
|
||||
spellCheck={false}
|
||||
data-composer-skill-chip="true"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{props.skillLabel}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
if (!props.skillDescription) {
|
||||
return chip;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={chip} />
|
||||
<TooltipPopup side="top" className="max-w-[30rem] whitespace-normal leading-tight">
|
||||
{props.skillDescription}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
class ComposerSkillNode extends DecoratorNode<ReactElement> {
|
||||
__skillName: string;
|
||||
__skillLabel: string;
|
||||
__skillDescription: string | null;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-skill";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerSkillNode): ComposerSkillNode {
|
||||
return new ComposerSkillNode(
|
||||
node.__skillName,
|
||||
node.__skillLabel,
|
||||
node.__skillDescription,
|
||||
node.__key,
|
||||
);
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerSkillNode): ComposerSkillNode {
|
||||
return $createComposerSkillNode(
|
||||
serializedNode.skillName,
|
||||
serializedNode.skillLabel ?? serializedNode.skillName,
|
||||
serializedNode.skillDescription ?? null,
|
||||
).updateFromJSON(serializedNode);
|
||||
}
|
||||
|
||||
constructor(
|
||||
skillName: string,
|
||||
skillLabel: string,
|
||||
skillDescription: string | null,
|
||||
key?: NodeKey,
|
||||
) {
|
||||
super(key);
|
||||
const normalizedSkillName = skillName.startsWith("$") ? skillName.slice(1) : skillName;
|
||||
this.__skillName = normalizedSkillName;
|
||||
this.__skillLabel = skillLabel;
|
||||
this.__skillDescription = skillDescription;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerSkillNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
skillName: this.__skillName,
|
||||
skillLabel: this.__skillLabel,
|
||||
...(this.__skillDescription ? { skillDescription: this.__skillDescription } : {}),
|
||||
type: "composer-skill",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return `$${this.__skillName}`;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return (
|
||||
<ComposerSkillDecorator
|
||||
skillLabel={this.__skillLabel}
|
||||
skillDescription={this.__skillDescription}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerSkillNode(
|
||||
skillName: string,
|
||||
skillLabel: string,
|
||||
skillDescription: string | null,
|
||||
): ComposerSkillNode {
|
||||
return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription));
|
||||
}
|
||||
|
||||
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
@@ -253,11 +417,16 @@ function $createComposerTerminalContextNode(
|
||||
return $applyNodeReplacement(new ComposerTerminalContextNode(context));
|
||||
}
|
||||
|
||||
type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
|
||||
type ComposerInlineTokenNode =
|
||||
| ComposerMentionNode
|
||||
| ComposerSkillNode
|
||||
| ComposerTerminalContextNode;
|
||||
|
||||
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
|
||||
return (
|
||||
candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
|
||||
candidate instanceof ComposerMentionNode ||
|
||||
candidate instanceof ComposerSkillNode ||
|
||||
candidate instanceof ComposerTerminalContextNode
|
||||
);
|
||||
}
|
||||
|
||||
@@ -302,6 +471,22 @@ function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function skillSignature(skills: ReadonlyArray<ServerProviderSkill>): string {
|
||||
return skills
|
||||
.map((skill) =>
|
||||
[
|
||||
skill.name,
|
||||
skill.displayName ?? "",
|
||||
skill.shortDescription ?? "",
|
||||
skill.description ?? "",
|
||||
skill.path,
|
||||
skill.scope ?? "",
|
||||
skill.enabled ? "1" : "0",
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function clampExpandedCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
@@ -415,7 +600,7 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -462,7 +647,7 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -488,7 +673,7 @@ function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
@@ -657,6 +842,7 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
skillMetadata: ReadonlyMap<string, ComposerSkillMetadata>,
|
||||
): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
@@ -669,6 +855,17 @@ function $setComposerEditorPrompt(
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "skill") {
|
||||
const metadata = skillMetadata.get(segment.name);
|
||||
paragraph.append(
|
||||
$createComposerSkillNode(
|
||||
segment.name,
|
||||
metadata?.label ?? formatProviderSkillDisplayName({ name: segment.name }),
|
||||
metadata?.description ?? null,
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (segment.context) {
|
||||
paragraph.append($createComposerTerminalContextNode(segment.context));
|
||||
@@ -705,6 +902,7 @@ interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
skills: ReadonlyArray<ServerProviderSkill>;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
@@ -946,9 +1144,11 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
|
||||
function ComposerSurroundSelectionPlugin(props: {
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const terminalContextsRef = useRef(props.terminalContexts);
|
||||
const skillMetadataRef = useRef(skillMetadataByName(props.skills));
|
||||
const pendingSurroundSelectionRef = useRef<{
|
||||
value: string;
|
||||
expandedStart: number;
|
||||
@@ -964,6 +1164,10 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
terminalContextsRef.current = props.terminalContexts;
|
||||
}, [props.terminalContexts]);
|
||||
|
||||
useEffect(() => {
|
||||
skillMetadataRef.current = skillMetadataByName(props.skills);
|
||||
}, [props.skills]);
|
||||
|
||||
const applySurroundInsertion = useCallback(
|
||||
(inputData: string): boolean => {
|
||||
const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData);
|
||||
@@ -1009,7 +1213,7 @@ function ComposerSurroundSelectionPlugin(props: {
|
||||
selectionSnapshot.expandedEnd,
|
||||
);
|
||||
const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`;
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current);
|
||||
$setComposerEditorPrompt(nextValue, terminalContextsRef.current, skillMetadataRef.current);
|
||||
const selectionStart = collapseExpandedComposerCursor(
|
||||
nextValue,
|
||||
selectionSnapshot.expandedStart,
|
||||
@@ -1211,6 +1415,7 @@ function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
@@ -1225,6 +1430,9 @@ function ComposerPromptEditorInner({
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const terminalContextsSignature = terminalContextSignature(terminalContexts);
|
||||
const terminalContextsSignatureRef = useRef(terminalContextsSignature);
|
||||
const skillsSignature = skillSignature(skills);
|
||||
const skillsSignatureRef = useRef(skillsSignature);
|
||||
const skillMetadataRef = useRef(skillMetadataByName(skills));
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
@@ -1241,6 +1449,10 @@ function ComposerPromptEditorInner({
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
skillMetadataRef.current = skillMetadataByName(skills);
|
||||
}, [skills]);
|
||||
|
||||
useEffect(() => {
|
||||
editor.setEditable(!disabled);
|
||||
}, [disabled, editor]);
|
||||
@@ -1249,10 +1461,12 @@ function ComposerPromptEditorInner({
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
const skillsChanged = skillsSignatureRef.current !== skillsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
!contextsChanged &&
|
||||
!skillsChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -1264,18 +1478,20 @@ function ComposerPromptEditorInner({
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
};
|
||||
terminalContextsSignatureRef.current = terminalContextsSignature;
|
||||
skillsSignatureRef.current = skillsSignature;
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
if (previousSnapshot.value === value && !contextsChanged && !skillsChanged && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
const shouldRewriteEditorState =
|
||||
previousSnapshot.value !== value || contextsChanged || skillsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
|
||||
}
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
@@ -1284,7 +1500,7 @@ function ComposerPromptEditorInner({
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
}, [cursor, editor, skillsSignature, terminalContexts, terminalContextsSignature, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
@@ -1442,7 +1658,7 @@ function ComposerPromptEditorInner({
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} />
|
||||
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} skills={skills} />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
@@ -1460,6 +1676,7 @@ export const ComposerPromptEditor = forwardRef<
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
skills,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
@@ -1472,13 +1689,18 @@ export const ComposerPromptEditor = forwardRef<
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialSkillMetadataRef = useRef(skillMetadataByName(skills));
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
nodes: [ComposerMentionNode, ComposerSkillNode, ComposerTerminalContextNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
$setComposerEditorPrompt(
|
||||
initialValueRef.current,
|
||||
initialTerminalContextsRef.current,
|
||||
initialSkillMetadataRef.current,
|
||||
);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -1493,6 +1715,7 @@ export const ComposerPromptEditor = forwardRef<
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
skills={skills}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
|
||||
@@ -429,12 +429,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const headerRow = (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
{canScrollTurnStripLeft && (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
|
||||
)}
|
||||
{canScrollTurnStripRight && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
@@ -466,6 +460,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
style={
|
||||
canScrollTurnStripLeft || canScrollTurnStripRight
|
||||
? {
|
||||
maskImage: `linear-gradient(to right, ${canScrollTurnStripLeft ? "transparent 24px, black 72px" : "black"}, ${canScrollTurnStripRight ? "black calc(100% - 72px), transparent calc(100% - 24px)" : "black"})`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -10,8 +10,10 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar";
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
|
||||
"flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
shouldUseDragRegion
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]"
|
||||
: "h-12 wco:max-h-[env(titlebar-area-height)]",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -426,4 +426,37 @@ describe("GitActionsControl thread-scoped progress toast", () => {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not overwrite a selected base branch while a new worktree draft is being configured", async () => {
|
||||
hasServerThreadRef.current = false;
|
||||
activeDraftThreadRef.current = {
|
||||
threadId: SHARED_THREAD_ID,
|
||||
environmentId: ENVIRONMENT_A,
|
||||
branch: "feature/base-branch",
|
||||
worktreePath: null,
|
||||
envMode: "worktree",
|
||||
};
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(
|
||||
<GitActionsControl
|
||||
gitCwd={GIT_CWD}
|
||||
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
|
||||
/>,
|
||||
{
|
||||
container: host,
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(setDraftThreadContextSpy).not.toHaveBeenCalled();
|
||||
expect(setThreadBranchSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
|
||||
import { newCommandId, randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { useStore } from "~/store";
|
||||
@@ -58,6 +58,7 @@ import { createThreadSelectorByRef } from "~/storeSelectors";
|
||||
interface GitActionsControlProps {
|
||||
gitCwd: string | null;
|
||||
activeThreadRef: ScopedThreadRef | null;
|
||||
draftId?: DraftId;
|
||||
}
|
||||
|
||||
interface PendingDefaultBranchAction {
|
||||
@@ -209,7 +210,11 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadRef }: GitActionsControlProps) {
|
||||
export default function GitActionsControl({
|
||||
gitCwd,
|
||||
activeThreadRef,
|
||||
draftId,
|
||||
}: GitActionsControlProps) {
|
||||
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
|
||||
@@ -221,7 +226,11 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
);
|
||||
const activeServerThread = useStore(activeServerThreadSelector);
|
||||
const activeDraftThread = useComposerDraftStore((store) =>
|
||||
activeThreadRef ? store.getDraftThreadByRef(activeThreadRef) : null,
|
||||
draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: activeThreadRef
|
||||
? store.getDraftThreadByRef(activeThreadRef)
|
||||
: null,
|
||||
);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const setThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
@@ -282,7 +291,7 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
return;
|
||||
}
|
||||
|
||||
setDraftThreadContext(activeThreadRef, {
|
||||
setDraftThreadContext(draftId ?? activeThreadRef, {
|
||||
branch,
|
||||
worktreePath: activeDraftThread.worktreePath,
|
||||
});
|
||||
@@ -291,6 +300,7 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
activeDraftThread,
|
||||
activeServerThread,
|
||||
activeThreadRef,
|
||||
draftId,
|
||||
setDraftThreadContext,
|
||||
setThreadBranch,
|
||||
],
|
||||
@@ -344,14 +354,18 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
const isPullRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isSelectingWorktreeBase =
|
||||
!activeServerThread &&
|
||||
activeDraftThread?.envMode === "worktree" &&
|
||||
activeDraftThread.worktreePath === null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isGitActionRunning) {
|
||||
if (isGitActionRunning || isSelectingWorktreeBase) {
|
||||
return;
|
||||
}
|
||||
|
||||
const branchUpdate = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: activeServerThread?.branch ?? null,
|
||||
threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
gitStatus: gitStatusForActions,
|
||||
});
|
||||
if (!branchUpdate) {
|
||||
@@ -361,8 +375,10 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
|
||||
persistThreadBranchSync(branchUpdate.branch);
|
||||
}, [
|
||||
activeServerThread?.branch,
|
||||
activeDraftThread?.branch,
|
||||
gitStatusForActions,
|
||||
isGitActionRunning,
|
||||
isSelectingWorktreeBase,
|
||||
persistThreadBranchSync,
|
||||
]);
|
||||
|
||||
|
||||
@@ -80,6 +80,8 @@ function createBaseServerConfig(): ServerConfig {
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
@@ -167,6 +169,43 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function toShellSnapshot(snapshot: OrchestrationReadModel) {
|
||||
return {
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projects: snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
repositoryIdentity: project.repositoryIdentity ?? null,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: project.scripts,
|
||||
createdAt: project.createdAt,
|
||||
updatedAt: project.updatedAt,
|
||||
})),
|
||||
threads: snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt:
|
||||
thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
})),
|
||||
updatedAt: snapshot.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(): TestFixture {
|
||||
return {
|
||||
snapshot: createMinimalSnapshot(),
|
||||
@@ -188,9 +227,6 @@ function buildFixture(): TestFixture {
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
@@ -427,6 +463,28 @@ describe("Keybindings update toast", () => {
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: toShellSnapshot(fixture.snapshot),
|
||||
},
|
||||
];
|
||||
}
|
||||
if (
|
||||
request._tag === ORCHESTRATION_WS_METHODS.subscribeThread &&
|
||||
request.threadId === THREAD_ID
|
||||
) {
|
||||
return [
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot: {
|
||||
snapshotSequence: fixture.snapshot.snapshotSequence,
|
||||
thread: fixture.snapshot.threads[0],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,11 +10,15 @@ export function NoActiveThreadState() {
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron ? "drag-region flex h-[52px] items-center" : "py-2 sm:py-3",
|
||||
isElectron
|
||||
? "drag-region flex h-[52px] items-center wco:h-[env(titlebar-area-height)]"
|
||||
: "py-2 sm:py-3",
|
||||
)}
|
||||
>
|
||||
{isElectron ? (
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
<span className="text-xs text-muted-foreground/50 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]">
|
||||
No active thread
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
@@ -667,133 +666,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
};
|
||||
}
|
||||
|
||||
describe("sortThreadsForSidebar", () => {
|
||||
it("sorts threads by the latest user message in recency mode", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:06:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to thread timestamps when there is no user message", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:02:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to id ordering when threads have no sortable timestamps", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-2"),
|
||||
ThreadId.make("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("can sort threads by createdAt when configured", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
}),
|
||||
],
|
||||
"created_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.make("thread-1"),
|
||||
ThreadId.make("thread-2"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
@@ -860,7 +732,6 @@ describe("getFallbackThreadIdAfterDelete", () => {
|
||||
expect(fallbackThreadId).toBe(ThreadId.make("thread-next"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortProjectsForSidebar", () => {
|
||||
it("sorts projects by the most recent user message across their threads", () => {
|
||||
const projects = [
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import * as React from "react";
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getThreadSortTimestamp,
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
type ThreadSortInput,
|
||||
} from "../lib/threadSort";
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
@@ -13,10 +19,6 @@ type SidebarProject = {
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
|
||||
latestUserMessageAt?: string | null;
|
||||
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
|
||||
};
|
||||
|
||||
export type ThreadTraversalDirection = "previous" | "next";
|
||||
|
||||
@@ -441,61 +443,8 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
|
||||
};
|
||||
}
|
||||
|
||||
function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
if (!iso) return null;
|
||||
const ms = Date.parse(iso);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
|
||||
if (thread.latestUserMessageAt) {
|
||||
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
for (const message of thread.messages ?? []) {
|
||||
if (message.role !== "user") continue;
|
||||
const messageTimestamp = toSortableTimestamp(message.createdAt);
|
||||
if (messageTimestamp === null) continue;
|
||||
latestUserMessageTimestamp =
|
||||
latestUserMessageTimestamp === null
|
||||
? messageTimestamp
|
||||
: Math.max(latestUserMessageTimestamp, messageTimestamp);
|
||||
}
|
||||
|
||||
if (latestUserMessageTimestamp !== null) {
|
||||
return latestUserMessageTimestamp;
|
||||
}
|
||||
|
||||
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function getThreadSortTimestamp(
|
||||
thread: SidebarThreadSortInput,
|
||||
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
return getLatestUserMessageTimestamp(thread);
|
||||
}
|
||||
|
||||
export function sortThreadsForSidebar<
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
|
||||
return threads.toSorted((left, right) => {
|
||||
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
|
||||
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return right.id.localeCompare(left.id);
|
||||
});
|
||||
}
|
||||
|
||||
export function getFallbackThreadIdAfterDelete<
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(input: {
|
||||
threads: readonly T[];
|
||||
deletedThreadId: T["id"];
|
||||
@@ -509,7 +458,7 @@ export function getFallbackThreadIdAfterDelete<
|
||||
}
|
||||
|
||||
return (
|
||||
sortThreadsForSidebar(
|
||||
sortThreads(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.projectId === deletedThread.projectId &&
|
||||
@@ -520,10 +469,9 @@ export function getFallbackThreadIdAfterDelete<
|
||||
)[0]?.id ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function getProjectSortTimestamp(
|
||||
project: SidebarProject,
|
||||
projectThreads: readonly SidebarThreadSortInput[],
|
||||
projectThreads: readonly ThreadSortInput[],
|
||||
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (projectThreads.length > 0) {
|
||||
@@ -541,7 +489,7 @@ export function getProjectSortTimestamp(
|
||||
|
||||
export function sortProjectsForSidebar<
|
||||
TProject extends SidebarProject,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
|
||||
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
|
||||
>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
@@ -90,6 +91,7 @@ import {
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
import {
|
||||
getArm64IntelBuildWarningDescription,
|
||||
getDesktopUpdateActionError,
|
||||
@@ -130,12 +132,13 @@ import {
|
||||
orderItemsByPreferredIds,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
@@ -1139,7 +1142,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
},
|
||||
});
|
||||
};
|
||||
const visibleProjectThreads = sortThreadsForSidebar(
|
||||
const visibleProjectThreads = sortThreads(
|
||||
projectThreads.filter((thread) => thread.archivedAt === null),
|
||||
threadSortOrder,
|
||||
);
|
||||
@@ -1971,7 +1974,7 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
);
|
||||
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px] wco:h-[env(titlebar-area-height)] wco:pl-[calc(env(titlebar-area-x)+1em)]">
|
||||
{wordmark}
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
@@ -2041,6 +2044,7 @@ interface SidebarProjectsContentProps {
|
||||
activeRouteProjectKey: string | null;
|
||||
routeThreadKey: string | null;
|
||||
newThreadShortcutLabel: string | null;
|
||||
commandPaletteShortcutLabel: string | null;
|
||||
threadJumpLabelByKey: ReadonlyMap<string, string>;
|
||||
attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void;
|
||||
expandThreadListForProject: (projectKey: string) => void;
|
||||
@@ -2092,6 +2096,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
activeRouteProjectKey,
|
||||
routeThreadKey,
|
||||
newThreadShortcutLabel,
|
||||
commandPaletteShortcutLabel,
|
||||
threadJumpLabelByKey,
|
||||
attachThreadListAutoAnimateRef,
|
||||
expandThreadListForProject,
|
||||
@@ -2138,6 +2143,29 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
|
||||
return (
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon className="size-3.5" />
|
||||
<span className="flex-1 truncate text-left text-xs">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
|
||||
<SidebarGroup className="px-2 pt-2 pb-0">
|
||||
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
|
||||
@@ -2535,7 +2563,7 @@ export default function Sidebar() {
|
||||
scopeProjectRef(projectRef.environmentId, projectRef.projectId),
|
||||
);
|
||||
const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
|
||||
const latestThread = sortThreadsForSidebar(
|
||||
const latestThread = sortThreads(
|
||||
(threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null),
|
||||
sidebarThreadSortOrder,
|
||||
)[0];
|
||||
@@ -2549,7 +2577,7 @@ export default function Sidebar() {
|
||||
[sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
const addProjectFromInput = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
@@ -2575,7 +2603,6 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2588,7 +2615,7 @@ export default function Sidebar() {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
if (activeEnvironmentId !== null) {
|
||||
await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), {
|
||||
@@ -2624,7 +2651,7 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
void addProjectFromPath(newCwd);
|
||||
void addProjectFromInput(newCwd);
|
||||
};
|
||||
|
||||
const canAddProject = newCwd.trim().length > 0 && !isAddingProject;
|
||||
@@ -2640,7 +2667,7 @@ export default function Sidebar() {
|
||||
// Ignore picker failures and leave the current thread selection unchanged.
|
||||
}
|
||||
if (pickedPath) {
|
||||
await addProjectFromPath(pickedPath);
|
||||
await addProjectFromInput(pickedPath);
|
||||
} else if (!shouldBrowseForProjectImmediately) {
|
||||
addProjectInputRef.current?.focus();
|
||||
}
|
||||
@@ -2696,7 +2723,9 @@ export default function Sidebar() {
|
||||
const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
|
||||
const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
|
||||
if (!activeProject || !overProject) return;
|
||||
reorderProjects(activeProject.projectKey, overProject.projectKey);
|
||||
const activeMemberKeys = activeProject.memberProjectRefs.map(scopedProjectKey);
|
||||
const overMemberKeys = overProject.memberProjectRefs.map(scopedProjectKey);
|
||||
reorderProjects(activeMemberKeys, overMemberKeys);
|
||||
},
|
||||
[sidebarProjectSortOrder, reorderProjects, sidebarProjects],
|
||||
);
|
||||
@@ -2769,7 +2798,7 @@ export default function Sidebar() {
|
||||
const visibleSidebarThreadKeys = useMemo(
|
||||
() =>
|
||||
sortedProjects.flatMap((project) => {
|
||||
const projectThreads = sortThreadsForSidebar(
|
||||
const projectThreads = sortThreads(
|
||||
(threadsByProjectKey.get(project.projectKey) ?? []).filter(
|
||||
(thread) => thread.archivedAt === null,
|
||||
),
|
||||
@@ -3040,6 +3069,11 @@ export default function Sidebar() {
|
||||
desktopUpdateState && showArm64IntelBuildWarning
|
||||
? getArm64IntelBuildWarningDescription(desktopUpdateState)
|
||||
: null;
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
"commandPalette.toggle",
|
||||
newThreadShortcutLabelOptions,
|
||||
);
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || !desktopUpdateState) return;
|
||||
@@ -3165,6 +3199,7 @@ export default function Sidebar() {
|
||||
activeRouteProjectKey={activeRouteProjectKey}
|
||||
routeThreadKey={routeThreadKey}
|
||||
newThreadShortcutLabel={newThreadShortcutLabel}
|
||||
commandPaletteShortcutLabel={commandPaletteShortcutLabel}
|
||||
threadJumpLabelByKey={visibleThreadJumpLabelByKey}
|
||||
attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef}
|
||||
expandThreadListForProject={expandThreadListForProject}
|
||||
|
||||
@@ -21,9 +21,12 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
collectWrappedTerminalLinkLine,
|
||||
extractTerminalLinks,
|
||||
isTerminalLinkActivation,
|
||||
resolvePathLinkTarget,
|
||||
resolveWrappedTerminalLinkRange,
|
||||
wrappedTerminalLinkRangeIntersectsBufferLine,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
||||
import {
|
||||
@@ -419,26 +422,31 @@ export function TerminalViewport({
|
||||
return;
|
||||
}
|
||||
|
||||
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
|
||||
if (!line) {
|
||||
const wrappedLine = collectWrappedTerminalLinkLine(bufferLineNumber, (bufferLineIndex) =>
|
||||
activeTerminal.buffer.active.getLine(bufferLineIndex),
|
||||
);
|
||||
if (!wrappedLine) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineText = line.translateToString(true);
|
||||
const matches = extractTerminalLinks(lineText);
|
||||
if (matches.length === 0) {
|
||||
const links = extractTerminalLinks(wrappedLine.text)
|
||||
.map((match) => ({
|
||||
match,
|
||||
range: resolveWrappedTerminalLinkRange(wrappedLine, match),
|
||||
}))
|
||||
.filter(({ range }) =>
|
||||
wrappedTerminalLinkRangeIntersectsBufferLine(range, bufferLineNumber),
|
||||
);
|
||||
if (links.length === 0) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(
|
||||
matches.map((match) => ({
|
||||
links.map(({ match, range }) => ({
|
||||
text: match.text,
|
||||
range: {
|
||||
start: { x: match.start + 1, y: bufferLineNumber },
|
||||
end: { x: match.end, y: bufferLineNumber },
|
||||
},
|
||||
range,
|
||||
activate: (event: MouseEvent) => {
|
||||
if (!isTerminalLinkActivation(event)) return;
|
||||
|
||||
|
||||
@@ -55,8 +55,6 @@ import {
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../../lib/terminalContext";
|
||||
import {
|
||||
resolveComposerFooterContentWidth,
|
||||
shouldForceCompactComposerFooterForFit,
|
||||
shouldUseCompactComposerPrimaryActions,
|
||||
shouldUseCompactComposerFooter,
|
||||
} from "../composerFooterLayout";
|
||||
@@ -69,6 +67,8 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
|
||||
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
@@ -100,6 +100,8 @@ import type { SessionPhase, Thread } from "../../types";
|
||||
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
|
||||
import type { PendingApproval, PendingUserInput } from "../../session-logic";
|
||||
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
|
||||
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
|
||||
import { searchProviderSkills } from "../../providerSkillSearch";
|
||||
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
|
||||
@@ -560,6 +562,10 @@ export const ChatComposer = memo(
|
||||
});
|
||||
|
||||
const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);
|
||||
const selectedProviderStatus = useMemo(
|
||||
() => providerStatuses.find((provider) => provider.provider === selectedProvider),
|
||||
[providerStatuses, selectedProvider],
|
||||
);
|
||||
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
@@ -636,6 +642,9 @@ export const ChatComposer = memo(
|
||||
detectComposerTrigger(prompt, prompt.length),
|
||||
);
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
|
||||
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
|
||||
@@ -646,9 +655,6 @@ export const ChatComposer = memo(
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerFooterRef = useRef<HTMLDivElement>(null);
|
||||
const composerFooterLeadingRef = useRef<HTMLDivElement>(null);
|
||||
const composerFooterActionsRef = useRef<HTMLDivElement>(null);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -704,7 +710,7 @@ export const ChatComposer = memo(
|
||||
}));
|
||||
}
|
||||
if (composerTrigger.kind === "slash-command") {
|
||||
const slashCommandItems = [
|
||||
const builtInSlashCommandItems = [
|
||||
{
|
||||
id: "slash:model",
|
||||
type: "slash-command",
|
||||
@@ -727,13 +733,38 @@ export const ChatComposer = memo(
|
||||
description: "Switch this thread back to normal build mode",
|
||||
},
|
||||
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) {
|
||||
return [...slashCommandItems];
|
||||
}
|
||||
return slashCommandItems.filter(
|
||||
(item) => item.command.includes(query) || item.label.slice(1).includes(query),
|
||||
const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map(
|
||||
(command) => ({
|
||||
id: `provider-slash-command:${selectedProvider}:${command.name}`,
|
||||
type: "provider-slash-command" as const,
|
||||
provider: selectedProvider,
|
||||
command,
|
||||
label: `/${command.name}`,
|
||||
description: command.description ?? command.input?.hint ?? "Run provider command",
|
||||
}),
|
||||
);
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
const slashCommandItems = [...builtInSlashCommandItems, ...providerSlashCommandItems];
|
||||
if (!query) {
|
||||
return slashCommandItems;
|
||||
}
|
||||
return searchSlashCommandItems(slashCommandItems, query);
|
||||
}
|
||||
if (composerTrigger.kind === "skill") {
|
||||
return searchProviderSkills(
|
||||
selectedProviderStatus?.skills ?? [],
|
||||
composerTrigger.query,
|
||||
).map((skill) => ({
|
||||
id: `skill:${selectedProvider}:${skill.name}`,
|
||||
type: "skill" as const,
|
||||
provider: selectedProvider,
|
||||
skill,
|
||||
label: formatProviderSkillDisplayName(skill),
|
||||
description:
|
||||
skill.shortDescription ??
|
||||
skill.description ??
|
||||
(skill.scope ? `${skill.scope} skill` : "Run provider skill"),
|
||||
}));
|
||||
}
|
||||
return searchableModelOptions
|
||||
.filter(({ searchSlug, searchName, searchProvider }) => {
|
||||
@@ -753,16 +784,32 @@ export const ChatComposer = memo(
|
||||
label: name,
|
||||
description: `${providerLabel} · ${slug}`,
|
||||
}));
|
||||
}, [composerTrigger, searchableModelOptions, workspaceEntries]);
|
||||
}, [
|
||||
composerTrigger,
|
||||
searchableModelOptions,
|
||||
selectedProvider,
|
||||
selectedProviderStatus,
|
||||
workspaceEntries,
|
||||
]);
|
||||
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
composerMenuItems.find((item) => item.id === composerHighlightedItemId) ??
|
||||
composerMenuItems[0] ??
|
||||
null,
|
||||
[composerHighlightedItemId, composerMenuItems],
|
||||
);
|
||||
const composerMenuSearchKey = composerTrigger
|
||||
? `${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}`
|
||||
: null;
|
||||
const activeComposerMenuItem = useMemo(() => {
|
||||
const activeItemId = resolveComposerMenuActiveItemId({
|
||||
items: composerMenuItems,
|
||||
highlightedItemId: composerHighlightedItemId,
|
||||
currentSearchKey: composerMenuSearchKey,
|
||||
highlightedSearchKey: composerHighlightedSearchKey,
|
||||
});
|
||||
return composerMenuItems.find((item) => item.id === activeItemId) ?? null;
|
||||
}, [
|
||||
composerHighlightedItemId,
|
||||
composerHighlightedSearchKey,
|
||||
composerMenuItems,
|
||||
composerMenuSearchKey,
|
||||
]);
|
||||
|
||||
composerMenuOpenRef.current = composerMenuOpen;
|
||||
composerMenuItemsRef.current = composerMenuItems;
|
||||
@@ -810,14 +857,21 @@ export const ChatComposer = memo(
|
||||
((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) ||
|
||||
workspaceEntriesQuery.isLoading ||
|
||||
workspaceEntriesQuery.isFetching);
|
||||
const composerMenuEmptyState = useMemo(() => {
|
||||
if (composerTriggerKind === "skill") {
|
||||
return "No skills found. Try / to browse provider commands.";
|
||||
}
|
||||
return composerTriggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command.";
|
||||
}, [composerTriggerKind]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Provider traits UI
|
||||
// ------------------------------------------------------------------
|
||||
const setPromptFromTraits = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
const currentPrompt = promptRef.current;
|
||||
if (nextPrompt === currentPrompt) {
|
||||
if (nextPrompt === promptRef.current) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
@@ -941,14 +995,28 @@ export const ChatComposer = memo(
|
||||
useEffect(() => {
|
||||
if (!composerMenuOpen) {
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerHighlightedSearchKey(null);
|
||||
return;
|
||||
}
|
||||
const nextActiveItemId = resolveComposerMenuActiveItemId({
|
||||
items: composerMenuItems,
|
||||
highlightedItemId: composerHighlightedItemId,
|
||||
currentSearchKey: composerMenuSearchKey,
|
||||
highlightedSearchKey: composerHighlightedSearchKey,
|
||||
});
|
||||
setComposerHighlightedItemId((existing) =>
|
||||
existing && composerMenuItems.some((item) => item.id === existing)
|
||||
? existing
|
||||
: (composerMenuItems[0]?.id ?? null),
|
||||
existing === nextActiveItemId ? existing : nextActiveItemId,
|
||||
);
|
||||
}, [composerMenuItems, composerMenuOpen]);
|
||||
setComposerHighlightedSearchKey((existing) =>
|
||||
existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
|
||||
);
|
||||
}, [
|
||||
composerHighlightedItemId,
|
||||
composerHighlightedSearchKey,
|
||||
composerMenuItems,
|
||||
composerMenuOpen,
|
||||
composerMenuSearchKey,
|
||||
]);
|
||||
|
||||
const lastSyncedPendingInputRef = useRef<{
|
||||
requestId: string | null;
|
||||
@@ -1017,31 +1085,17 @@ export const ChatComposer = memo(
|
||||
const measureComposerFormWidth = () => composerForm.clientWidth;
|
||||
const measureFooterCompactness = () => {
|
||||
const composerFormWidth = measureComposerFormWidth();
|
||||
const heuristicFooterCompact = shouldUseCompactComposerFooter(composerFormWidth, {
|
||||
const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, {
|
||||
hasWideActions: composerFooterHasWideActions,
|
||||
});
|
||||
const footer = composerFooterRef.current;
|
||||
const footerStyle = footer ? window.getComputedStyle(footer) : null;
|
||||
const footerContentWidth = resolveComposerFooterContentWidth({
|
||||
footerWidth: footer?.clientWidth ?? null,
|
||||
paddingLeft: footerStyle ? Number.parseFloat(footerStyle.paddingLeft) : null,
|
||||
paddingRight: footerStyle ? Number.parseFloat(footerStyle.paddingRight) : null,
|
||||
});
|
||||
const fitInput = {
|
||||
footerContentWidth,
|
||||
leadingContentWidth: composerFooterLeadingRef.current?.scrollWidth ?? null,
|
||||
actionsWidth: composerFooterActionsRef.current?.scrollWidth ?? null,
|
||||
};
|
||||
const nextFooterCompact =
|
||||
heuristicFooterCompact || shouldForceCompactComposerFooterForFit(fitInput);
|
||||
const nextPrimaryActionsCompact =
|
||||
nextFooterCompact &&
|
||||
const primaryActionsCompact =
|
||||
footerCompact &&
|
||||
shouldUseCompactComposerPrimaryActions(composerFormWidth, {
|
||||
hasWideActions: composerFooterHasWideActions,
|
||||
});
|
||||
return {
|
||||
primaryActionsCompact: nextPrimaryActionsCompact,
|
||||
footerCompact: nextFooterCompact,
|
||||
primaryActionsCompact,
|
||||
footerCompact,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1333,6 +1387,42 @@ export const ChatComposer = memo(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.type === "provider-slash-command") {
|
||||
const replacement = `/${item.command.name} `;
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
replacement,
|
||||
);
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
replacementRangeEnd,
|
||||
replacement,
|
||||
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
|
||||
);
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.type === "skill") {
|
||||
const replacement = `$${item.skill.name} `;
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
replacement,
|
||||
);
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
replacementRangeEnd,
|
||||
replacement,
|
||||
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
|
||||
);
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
onProviderModelSelect(item.provider, item.model);
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
|
||||
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
|
||||
@@ -1349,9 +1439,13 @@ export const ChatComposer = memo(
|
||||
],
|
||||
);
|
||||
|
||||
const onComposerMenuItemHighlighted = useCallback((itemId: string | null) => {
|
||||
setComposerHighlightedItemId(itemId);
|
||||
}, []);
|
||||
const onComposerMenuItemHighlighted = useCallback(
|
||||
(itemId: string | null) => {
|
||||
setComposerHighlightedItemId(itemId);
|
||||
setComposerHighlightedSearchKey(composerMenuSearchKey);
|
||||
},
|
||||
[composerMenuSearchKey],
|
||||
);
|
||||
|
||||
const nudgeComposerMenuHighlight = useCallback(
|
||||
(key: "ArrowDown" | "ArrowUp") => {
|
||||
@@ -1676,6 +1770,11 @@ export const ChatComposer = memo(
|
||||
resolvedTheme={resolvedTheme}
|
||||
isLoading={isComposerMenuLoading}
|
||||
triggerKind={composerTriggerKind}
|
||||
groupSlashCommandSections={
|
||||
composerTrigger?.kind === "slash-command" &&
|
||||
composerTrigger.query.trim().length === 0
|
||||
}
|
||||
emptyStateText={composerMenuEmptyState}
|
||||
activeItemId={activeComposerMenuItem?.id ?? null}
|
||||
onHighlightedItemChange={onComposerMenuItemHighlighted}
|
||||
onSelect={onSelectComposerItem}
|
||||
@@ -1765,6 +1864,7 @@ export const ChatComposer = memo(
|
||||
? composerTerminalContexts
|
||||
: []
|
||||
}
|
||||
skills={selectedProviderStatus?.skills ?? []}
|
||||
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
|
||||
onChange={onPromptChange}
|
||||
onCommandKeyDown={onComposerCommandKey}
|
||||
@@ -1795,7 +1895,6 @@ export const ChatComposer = memo(
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
ref={composerFooterRef}
|
||||
data-chat-composer-footer="true"
|
||||
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
|
||||
className={cn(
|
||||
@@ -1803,15 +1902,7 @@ export const ChatComposer = memo(
|
||||
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
ref={composerFooterLeadingRef}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center",
|
||||
isComposerFooterCompact
|
||||
? "gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
: "gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
provider={selectedProvider}
|
||||
@@ -1865,7 +1956,6 @@ export const ChatComposer = memo(
|
||||
|
||||
{/* Right side: send / stop button */}
|
||||
<div
|
||||
ref={composerFooterActionsRef}
|
||||
data-chat-composer-actions="right"
|
||||
data-chat-composer-primary-actions-compact={
|
||||
isComposerPrimaryActionsCompact ? "true" : "false"
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { type DraftId } from "~/composerDraftStore";
|
||||
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -19,6 +20,7 @@ import { OpenInPicker } from "./OpenInPicker";
|
||||
interface ChatHeaderProps {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
activeThreadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isGitRepo: boolean;
|
||||
@@ -44,6 +46,7 @@ interface ChatHeaderProps {
|
||||
export const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadEnvironmentId,
|
||||
activeThreadId,
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isGitRepo,
|
||||
@@ -109,6 +112,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<GitActionsControl
|
||||
gitCwd={gitCwd}
|
||||
activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
/>
|
||||
)}
|
||||
<Tooltip>
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo, useLayoutEffect, useRef } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import {
|
||||
type ProjectEntry,
|
||||
type ProviderKind,
|
||||
type ServerProviderSkill,
|
||||
type ServerProviderSlashCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { memo, useLayoutEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { formatProviderSkillInstallSource } from "~/providerSkillPresentation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Command, CommandItem, CommandList } from "../ui/command";
|
||||
import {
|
||||
Command,
|
||||
CommandGroup,
|
||||
CommandGroupLabel,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "../ui/command";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
|
||||
export type ComposerCommandItem =
|
||||
@@ -23,6 +37,14 @@ export type ComposerCommandItem =
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "provider-slash-command";
|
||||
provider: ProviderKind;
|
||||
command: ServerProviderSlashCommand;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
@@ -30,18 +52,83 @@ export type ComposerCommandItem =
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "skill";
|
||||
provider: ProviderKind;
|
||||
skill: ServerProviderSkill;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
type ComposerCommandGroup = {
|
||||
id: string;
|
||||
label: string | null;
|
||||
items: ComposerCommandItem[];
|
||||
};
|
||||
|
||||
function SkillGlyph(props: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.85"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={props.className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" />
|
||||
<path d="m3.3 7 8.7 5 8.7-5" />
|
||||
<path d="M12 22V12" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function groupCommandItems(
|
||||
items: ComposerCommandItem[],
|
||||
triggerKind: ComposerTriggerKind | null,
|
||||
groupSlashCommandSections: boolean,
|
||||
): ComposerCommandGroup[] {
|
||||
if (triggerKind === "skill") {
|
||||
return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : [];
|
||||
}
|
||||
if (triggerKind !== "slash-command" || !groupSlashCommandSections) {
|
||||
return [{ id: "default", label: null, items }];
|
||||
}
|
||||
|
||||
const builtInItems = items.filter((item) => item.type === "slash-command");
|
||||
const providerItems = items.filter((item) => item.type === "provider-slash-command");
|
||||
|
||||
const groups: ComposerCommandGroup[] = [];
|
||||
if (builtInItems.length > 0) {
|
||||
groups.push({ id: "built-in", label: "Built-in", items: builtInItems });
|
||||
}
|
||||
if (providerItems.length > 0) {
|
||||
groups.push({ id: "provider", label: "Provider", items: providerItems });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
items: ComposerCommandItem[];
|
||||
resolvedTheme: "light" | "dark";
|
||||
isLoading: boolean;
|
||||
triggerKind: ComposerTriggerKind | null;
|
||||
groupSlashCommandSections?: boolean;
|
||||
emptyStateText?: string;
|
||||
activeItemId: string | null;
|
||||
onHighlightedItemChange: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
groupCommandItems(props.items, props.triggerKind, props.groupSlashCommandSections ?? true),
|
||||
[props.groupSlashCommandSections, props.items, props.triggerKind],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!props.activeItemId || !listRef.current) return;
|
||||
@@ -65,27 +152,56 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
ref={listRef}
|
||||
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
|
||||
>
|
||||
<CommandList className="max-h-64">
|
||||
{props.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onHighlight={props.onHighlightedItemChange}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
<CommandList className="max-h-72">
|
||||
{groups.map((group, groupIndex) => (
|
||||
<div key={group.id}>
|
||||
{groupIndex > 0 ? <CommandSeparator className="my-0.5" /> : null}
|
||||
<CommandGroup>
|
||||
{group.label ? (
|
||||
<CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
|
||||
{group.label}
|
||||
</CommandGroupLabel>
|
||||
) : null}
|
||||
{group.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onHighlight={props.onHighlightedItemChange}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
</CommandList>
|
||||
{props.items.length === 0 && (
|
||||
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace files..."
|
||||
: props.triggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."}
|
||||
</p>
|
||||
)}
|
||||
{props.items.length === 0 ? (
|
||||
<div className="px-3 py-2">
|
||||
{props.triggerKind === "skill" ? (
|
||||
<CommandGroup>
|
||||
<CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
|
||||
Skills
|
||||
</CommandGroupLabel>
|
||||
<p className="text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace skills..."
|
||||
: (props.emptyStateText ??
|
||||
"No skills found. Try / to browse provider commands.")}
|
||||
</p>
|
||||
</CommandGroup>
|
||||
) : (
|
||||
<p className="text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace files..."
|
||||
: (props.emptyStateText ??
|
||||
(props.triggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Command>
|
||||
);
|
||||
@@ -98,6 +214,9 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
onHighlight: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
const skillSourceLabel =
|
||||
props.item.type === "skill" ? formatProviderSkillInstallSource(props.item.skill) : null;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.id}
|
||||
@@ -124,17 +243,32 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
/>
|
||||
) : null}
|
||||
{props.item.type === "slash-command" ? (
|
||||
<BotIcon className="size-4 text-muted-foreground/80" />
|
||||
<BotIcon className="size-4 shrink-0 text-muted-foreground/80" />
|
||||
) : null}
|
||||
{props.item.type === "provider-slash-command" ? (
|
||||
<span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
|
||||
<SkillGlyph className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
{props.item.type === "skill" ? (
|
||||
<span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
|
||||
<SkillGlyph className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
{props.item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
model
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="truncate">{props.item.label}</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="shrink-0">{props.item.label}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs">
|
||||
{props.item.description}
|
||||
</span>
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
|
||||
{skillSourceLabel ? (
|
||||
<span className="shrink-0 pl-2 text-muted-foreground/70 text-xs">{skillSourceLabel}</span>
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
});
|
||||
@@ -100,7 +100,10 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
||||
return;
|
||||
}
|
||||
if (target instanceof HTMLElement && target.isContentEditable) {
|
||||
if (
|
||||
target instanceof HTMLElement &&
|
||||
target.closest('[contenteditable]:not([contenteditable="false"])')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const digit = Number.parseInt(event.key, 10);
|
||||
|
||||
@@ -140,7 +140,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
className={cn("h-9 rounded-l-full rounded-r-none sm:h-8", compact ? "px-3" : "px-4")}
|
||||
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
|
||||
disabled={isSendBusy || isConnecting}
|
||||
>
|
||||
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
|
||||
|
||||
@@ -1,20 +1,82 @@
|
||||
import { memo } from "react";
|
||||
import { memo, useRef } from "react";
|
||||
import { CopyIcon, CheckIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { anchoredToastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
export const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
const ANCHORED_TOAST_TIMEOUT_MS = 1000;
|
||||
const onCopy = (ref: React.RefObject<HTMLButtonElement | null>) => {
|
||||
if (ref.current) {
|
||||
anchoredToastManager.add({
|
||||
data: {
|
||||
tooltipStyle: true,
|
||||
},
|
||||
positionerProps: {
|
||||
anchor: ref.current,
|
||||
},
|
||||
timeout: ANCHORED_TOAST_TIMEOUT_MS,
|
||||
title: "Copied!",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onCopyError = (ref: React.RefObject<HTMLButtonElement | null>, error: Error) => {
|
||||
if (ref.current) {
|
||||
anchoredToastManager.add({
|
||||
data: {
|
||||
tooltipStyle: true,
|
||||
},
|
||||
positionerProps: {
|
||||
anchor: ref.current,
|
||||
},
|
||||
timeout: ANCHORED_TOAST_TIMEOUT_MS,
|
||||
title: "Failed to copy",
|
||||
description: error.message,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const MessageCopyButton = memo(function MessageCopyButton({
|
||||
text,
|
||||
size = "xs",
|
||||
variant = "outline",
|
||||
className,
|
||||
}: {
|
||||
text: string;
|
||||
size?: "xs" | "icon-xs";
|
||||
variant?: "outline" | "ghost";
|
||||
className?: string;
|
||||
}) {
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard<void>({
|
||||
onCopy: () => onCopy(ref),
|
||||
onError: (error: Error) => onCopyError(ref, error),
|
||||
timeout: ANCHORED_TOAST_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy message"
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
aria-label="Copy link"
|
||||
disabled={isCopied}
|
||||
onClick={() => copyToClipboard(text)}
|
||||
ref={ref}
|
||||
type="button"
|
||||
size={size}
|
||||
variant={variant}
|
||||
className={cn(className)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup>
|
||||
<p>Copy to clipboard</p>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
computeMessageDurationStart,
|
||||
deriveMessagesTimelineRows,
|
||||
normalizeCompactToolLabel,
|
||||
resolveAssistantMessageCopyState,
|
||||
} from "./MessagesTimeline.logic";
|
||||
|
||||
describe("computeMessageDurationStart", () => {
|
||||
it("returns message createdAt when there is no preceding user message", () => {
|
||||
@@ -143,3 +149,287 @@ describe("normalizeCompactToolLabel", () => {
|
||||
expect(normalizeCompactToolLabel("Read file completed")).toBe("Read file");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAssistantMessageCopyState", () => {
|
||||
it("returns enabled copy state for completed assistant messages", () => {
|
||||
expect(
|
||||
resolveAssistantMessageCopyState({
|
||||
showCopyButton: true,
|
||||
text: "Ship it",
|
||||
streaming: false,
|
||||
}),
|
||||
).toEqual({
|
||||
text: "Ship it",
|
||||
visible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides copy while an assistant message is still streaming", () => {
|
||||
expect(
|
||||
resolveAssistantMessageCopyState({
|
||||
showCopyButton: true,
|
||||
text: "Still streaming",
|
||||
streaming: true,
|
||||
}),
|
||||
).toEqual({
|
||||
text: "Still streaming",
|
||||
visible: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides copy for empty completed assistant messages", () => {
|
||||
expect(
|
||||
resolveAssistantMessageCopyState({
|
||||
showCopyButton: true,
|
||||
text: " ",
|
||||
streaming: false,
|
||||
}),
|
||||
).toEqual({
|
||||
text: null,
|
||||
visible: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides copy for non-terminal assistant messages", () => {
|
||||
expect(
|
||||
resolveAssistantMessageCopyState({
|
||||
showCopyButton: false,
|
||||
text: "Interim thought",
|
||||
streaming: false,
|
||||
}),
|
||||
).toEqual({
|
||||
text: "Interim thought",
|
||||
visible: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveMessagesTimelineRows", () => {
|
||||
it("only enables assistant copy for the terminal assistant message in a turn", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "user-1-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Write a poem",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-thought-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "I should ground this first.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
completedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-final-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Here is the poem.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: "assistant-final-entry",
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRows = rows.filter(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(assistantRows).toHaveLength(2);
|
||||
expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
|
||||
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
|
||||
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
|
||||
});
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
assistantMessageId: "assistant-1" as never,
|
||||
checkpointTurnCount: 2,
|
||||
files: [{ path: "src/index.ts", additions: 3, deletions: 1 }],
|
||||
};
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Do the thing",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-1" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map([
|
||||
["assistant-1" as never, assistantTurnDiffSummary],
|
||||
]),
|
||||
revertTurnCountByUserMessageId: new Map([["user-1" as never, 1]]),
|
||||
});
|
||||
|
||||
const userRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "user",
|
||||
);
|
||||
const assistantRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(userRow?.revertTurnCount).toBe(1);
|
||||
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
it("returns the previous result when row order and content are unchanged", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
};
|
||||
const secondUserMessage = {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "entry-user-1",
|
||||
kind: "message",
|
||||
createdAt: firstUserMessage.createdAt,
|
||||
message: firstUserMessage,
|
||||
},
|
||||
{
|
||||
id: "entry-user-2",
|
||||
kind: "message",
|
||||
createdAt: secondUserMessage.createdAt,
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const initial = computeStableMessagesTimelineRows(rows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
const repeated = computeStableMessagesTimelineRows(rows, initial);
|
||||
|
||||
expect(repeated).toBe(initial);
|
||||
expect(repeated.result).toBe(initial.result);
|
||||
});
|
||||
|
||||
it("returns a new result when row order changes without content changes", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
};
|
||||
const secondUserMessage = {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
const firstRows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "entry-user-1",
|
||||
kind: "message",
|
||||
createdAt: firstUserMessage.createdAt,
|
||||
message: firstUserMessage,
|
||||
},
|
||||
{
|
||||
id: "entry-user-2",
|
||||
kind: "message",
|
||||
createdAt: secondUserMessage.createdAt,
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const initial = computeStableMessagesTimelineRows(firstRows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
const reordered = computeStableMessagesTimelineRows([firstRows[1]!, firstRows[0]!], initial);
|
||||
|
||||
expect(reordered).not.toBe(initial);
|
||||
expect(reordered.result).toEqual([initial.result[1], initial.result[0]]);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,6 @@
|
||||
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";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
|
||||
@@ -27,6 +25,9 @@ export type MessagesTimelineRow =
|
||||
message: ChatMessage;
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
@@ -36,6 +37,11 @@ export type MessagesTimelineRow =
|
||||
}
|
||||
| { kind: "working"; id: string; createdAt: string | null };
|
||||
|
||||
export interface StableMessagesTimelineRowsState {
|
||||
byId: Map<string, MessagesTimelineRow>;
|
||||
result: MessagesTimelineRow[];
|
||||
}
|
||||
|
||||
export function computeMessageDurationStart(
|
||||
messages: ReadonlyArray<TimelineDurationMessage>,
|
||||
): Map<string, string> {
|
||||
@@ -59,16 +65,61 @@ export function normalizeCompactToolLabel(value: string): string {
|
||||
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
|
||||
}
|
||||
|
||||
export function resolveAssistantMessageCopyState({
|
||||
text,
|
||||
showCopyButton,
|
||||
streaming,
|
||||
}: {
|
||||
text: string | null;
|
||||
showCopyButton: boolean;
|
||||
streaming: boolean;
|
||||
}) {
|
||||
const hasText = text !== null && text.trim().length > 0;
|
||||
return {
|
||||
text: hasText ? text : null,
|
||||
visible: showCopyButton && hasText && !streaming,
|
||||
};
|
||||
}
|
||||
|
||||
function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
|
||||
const lastAssistantMessageIdByResponseKey = new Map<string, string>();
|
||||
let nullTurnResponseIndex = 0;
|
||||
|
||||
for (const timelineEntry of timelineEntries) {
|
||||
if (timelineEntry.kind !== "message") {
|
||||
continue;
|
||||
}
|
||||
const { message } = timelineEntry;
|
||||
if (message.role === "user") {
|
||||
nullTurnResponseIndex += 1;
|
||||
continue;
|
||||
}
|
||||
if (message.role !== "assistant") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const responseKey = message.turnId
|
||||
? `turn:${message.turnId}`
|
||||
: `unkeyed:${nullTurnResponseIndex}`;
|
||||
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
|
||||
}
|
||||
|
||||
return new Set(lastAssistantMessageIdByResponseKey.values());
|
||||
}
|
||||
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
|
||||
}): MessagesTimelineRow[] {
|
||||
const nextRows: MessagesTimelineRow[] = [];
|
||||
const durationStartByMessageId = computeMessageDurationStart(
|
||||
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
|
||||
|
||||
for (let index = 0; index < input.timelineEntries.length; index += 1) {
|
||||
const timelineEntry = input.timelineEntries[index];
|
||||
@@ -115,6 +166,17 @@ export function deriveMessagesTimelineRows(input: {
|
||||
showCompletionDivider:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id,
|
||||
showAssistantCopyButton:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id),
|
||||
assistantTurnDiffSummary:
|
||||
timelineEntry.message.role === "assistant"
|
||||
? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
|
||||
: undefined,
|
||||
revertTurnCount:
|
||||
timelineEntry.message.role === "user"
|
||||
? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -129,71 +191,50 @@ export function deriveMessagesTimelineRows(input: {
|
||||
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);
|
||||
export function computeStableMessagesTimelineRows(
|
||||
rows: MessagesTimelineRow[],
|
||||
previous: StableMessagesTimelineRowsState,
|
||||
): StableMessagesTimelineRowsState {
|
||||
const next = new Map<string, MessagesTimelineRow>();
|
||||
let anyChanged = rows.length !== previous.byId.size;
|
||||
|
||||
const result = rows.map((row, index) => {
|
||||
const prevRow = previous.byId.get(row.id);
|
||||
const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
|
||||
next.set(row.id, nextRow);
|
||||
if (!anyChanged && previous.result[index] !== nextRow) {
|
||||
anyChanged = true;
|
||||
}
|
||||
return nextRow;
|
||||
});
|
||||
|
||||
return anyChanged ? { byId: next, result } : previous;
|
||||
}
|
||||
|
||||
/** Shallow field comparison per row variant — avoids deep equality cost. */
|
||||
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
|
||||
if (a.kind !== b.kind || a.id !== b.id) return false;
|
||||
|
||||
switch (a.kind) {
|
||||
case "working":
|
||||
return 40;
|
||||
return a.createdAt === (b as typeof a).createdAt;
|
||||
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "work":
|
||||
return a.groupedEntries === (b as typeof a).groupedEntries;
|
||||
|
||||
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;
|
||||
const bm = b as typeof a;
|
||||
return (
|
||||
a.message === bm.message &&
|
||||
a.durationStart === bm.durationStart &&
|
||||
a.showCompletionDivider === bm.showCompletionDivider &&
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
a.revertTurnCount === bm.revertTurnCount
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
const classList = {
|
||||
add: () => {},
|
||||
remove: () => {},
|
||||
toggle: () => {},
|
||||
contains: () => false,
|
||||
};
|
||||
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: () => null,
|
||||
setItem: () => {},
|
||||
removeItem: () => {},
|
||||
clear: () => {},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList,
|
||||
offsetHeight: 0,
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
});
|
||||
|
||||
const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("renders inline terminal labels with the composer chip UI", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
message: {
|
||||
id: MessageId.make("message-2"),
|
||||
role: "user",
|
||||
text: [
|
||||
"yoo what's @terminal-1:1-5 mean",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 1-5:",
|
||||
" 1 | julius@mac effect-http-ws-cli % bun i",
|
||||
" 2 | bun install v1.3.9 (cf6cdbbb)",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
changedFilesExpandedByTurnId={{}}
|
||||
onSetChangedFilesExpanded={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
}, 10_000);
|
||||
|
||||
it("renders context compaction entries in the normal work log", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
changedFilesExpandedByTurnId={{}}
|
||||
onSetChangedFilesExpanded={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Context compacted");
|
||||
expect(markup).toContain("Work log");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -24,6 +24,8 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5-codex",
|
||||
@@ -59,6 +61,8 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
@@ -120,6 +124,8 @@ function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
models,
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,8 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
@@ -70,6 +72,8 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
|
||||
describe("resolveComposerMenuActiveItemId", () => {
|
||||
const items = [{ id: "top" }, { id: "second" }, { id: "third" }] as const;
|
||||
|
||||
it("defaults to the first item when nothing is highlighted", () => {
|
||||
expect(
|
||||
resolveComposerMenuActiveItemId({
|
||||
items,
|
||||
highlightedItemId: null,
|
||||
currentSearchKey: "skill:u",
|
||||
highlightedSearchKey: null,
|
||||
}),
|
||||
).toBe("top");
|
||||
});
|
||||
|
||||
it("preserves the highlighted item within the same query", () => {
|
||||
expect(
|
||||
resolveComposerMenuActiveItemId({
|
||||
items,
|
||||
highlightedItemId: "second",
|
||||
currentSearchKey: "skill:u",
|
||||
highlightedSearchKey: "skill:u",
|
||||
}),
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("resets to the top result when the query changes", () => {
|
||||
expect(
|
||||
resolveComposerMenuActiveItemId({
|
||||
items,
|
||||
highlightedItemId: "second",
|
||||
currentSearchKey: "skill:ui",
|
||||
highlightedSearchKey: "skill:u",
|
||||
}),
|
||||
).toBe("top");
|
||||
});
|
||||
|
||||
it("falls back to the first item when the highlighted item disappears", () => {
|
||||
expect(
|
||||
resolveComposerMenuActiveItemId({
|
||||
items,
|
||||
highlightedItemId: "missing",
|
||||
currentSearchKey: "skill:ui",
|
||||
highlightedSearchKey: "skill:ui",
|
||||
}),
|
||||
).toBe("top");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
export function resolveComposerMenuActiveItemId(input: {
|
||||
items: ReadonlyArray<{ id: string }>;
|
||||
highlightedItemId: string | null;
|
||||
currentSearchKey: string | null;
|
||||
highlightedSearchKey: string | null;
|
||||
}): string | null {
|
||||
if (input.items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
input.currentSearchKey === input.highlightedSearchKey &&
|
||||
input.highlightedItemId &&
|
||||
input.items.some((item) => item.id === input.highlightedItemId)
|
||||
) {
|
||||
return input.highlightedItemId;
|
||||
}
|
||||
|
||||
return input.items[0]?.id ?? null;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ComposerCommandItem } from "./ComposerCommandMenu";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
|
||||
describe("searchSlashCommandItems", () => {
|
||||
it("moves exact provider command matches ahead of broader description matches", () => {
|
||||
const items = [
|
||||
{
|
||||
id: "slash:default",
|
||||
type: "slash-command",
|
||||
command: "default",
|
||||
label: "/default",
|
||||
description: "Switch this thread back to normal build mode",
|
||||
},
|
||||
{
|
||||
id: "provider-slash-command:claudeAgent:ui",
|
||||
type: "provider-slash-command",
|
||||
provider: "claudeAgent",
|
||||
command: { name: "ui" },
|
||||
label: "/ui",
|
||||
description: "Explore, build, and refine UI.",
|
||||
},
|
||||
{
|
||||
id: "provider-slash-command:claudeAgent:frontend-design",
|
||||
type: "provider-slash-command",
|
||||
provider: "claudeAgent",
|
||||
command: { name: "frontend-design" },
|
||||
label: "/frontend-design",
|
||||
description: "Create distinctive, production-grade frontend interfaces",
|
||||
},
|
||||
] satisfies Array<
|
||||
Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>
|
||||
>;
|
||||
|
||||
expect(searchSlashCommandItems(items, "ui").map((item) => item.id)).toEqual([
|
||||
"provider-slash-command:claudeAgent:ui",
|
||||
"slash:default",
|
||||
]);
|
||||
});
|
||||
|
||||
it("supports fuzzy provider command matches", () => {
|
||||
const items = [
|
||||
{
|
||||
id: "provider-slash-command:claudeAgent:gh-fix-ci",
|
||||
type: "provider-slash-command",
|
||||
provider: "claudeAgent",
|
||||
command: { name: "gh-fix-ci" },
|
||||
label: "/gh-fix-ci",
|
||||
description: "Fix failing GitHub Actions",
|
||||
},
|
||||
{
|
||||
id: "provider-slash-command:claudeAgent:github",
|
||||
type: "provider-slash-command",
|
||||
provider: "claudeAgent",
|
||||
command: { name: "github" },
|
||||
label: "/github",
|
||||
description: "General GitHub help",
|
||||
},
|
||||
] satisfies Array<
|
||||
Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>
|
||||
>;
|
||||
|
||||
expect(searchSlashCommandItems(items, "gfc").map((item) => item.id)).toEqual([
|
||||
"provider-slash-command:claudeAgent:gh-fix-ci",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
insertRankedSearchResult,
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
|
||||
import type { ComposerCommandItem } from "./ComposerCommandMenu";
|
||||
|
||||
function scoreSlashCommandItem(
|
||||
item: Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>,
|
||||
query: string,
|
||||
): number | null {
|
||||
const primaryValue =
|
||||
item.type === "slash-command" ? item.command.toLowerCase() : item.command.name.toLowerCase();
|
||||
const description = item.description.toLowerCase();
|
||||
|
||||
const scores = [
|
||||
scoreQueryMatch({
|
||||
value: primaryValue,
|
||||
query,
|
||||
exactBase: 0,
|
||||
prefixBase: 2,
|
||||
boundaryBase: 4,
|
||||
includesBase: 6,
|
||||
fuzzyBase: 100,
|
||||
boundaryMarkers: ["-", "_", "/"],
|
||||
}),
|
||||
scoreQueryMatch({
|
||||
value: description,
|
||||
query,
|
||||
exactBase: 20,
|
||||
prefixBase: 22,
|
||||
boundaryBase: 24,
|
||||
includesBase: 26,
|
||||
}),
|
||||
].filter((score): score is number => score !== null);
|
||||
|
||||
if (scores.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.min(...scores);
|
||||
}
|
||||
|
||||
export function searchSlashCommandItems(
|
||||
items: ReadonlyArray<
|
||||
Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>
|
||||
>,
|
||||
query: string,
|
||||
): Array<Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>> {
|
||||
const normalizedQuery = normalizeSearchQuery(query, { trimLeadingPattern: /^\/+/ });
|
||||
if (!normalizedQuery) {
|
||||
return [...items];
|
||||
}
|
||||
|
||||
const ranked: Array<{
|
||||
item: Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>;
|
||||
score: number;
|
||||
tieBreaker: string;
|
||||
}> = [];
|
||||
|
||||
for (const item of items) {
|
||||
const score = scoreSlashCommandItem(item, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
insertRankedSearchResult(
|
||||
ranked,
|
||||
{
|
||||
item,
|
||||
score,
|
||||
tieBreaker:
|
||||
item.type === "slash-command"
|
||||
? `0\u0000${item.command}`
|
||||
: `1\u0000${item.command.name}\u0000${item.provider}`,
|
||||
},
|
||||
Number.POSITIVE_INFINITY,
|
||||
);
|
||||
}
|
||||
|
||||
return ranked.map((entry) => entry.item);
|
||||
}
|
||||
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user