keybindings

This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-02-26 13:20:36 -08:00
1 parent da6706777b
commit 734ab399eb
65 files changed
+10072 -1053

No files matched your search

+1 -4
View File
@@ -46,10 +46,7 @@ async function shutdown(exitCode) {
shuttingDown = true;
try {
await Promise.race([
monitor.destroy(),
new Promise((resolve) => setTimeout(resolve, 1_500)),
]);
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
}
+12 -41
View File
@@ -25,34 +25,22 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
const details = [replaceResult.stderr, insertResult.stderr]
.filter(Boolean)
.join("\n");
throw new Error(
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
);
const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
@@ -81,28 +69,16 @@ function patchHelperBundleInfoPlists(appBundlePath) {
continue;
}
const helperPlistPath = join(
frameworksDir,
entry.name,
"Contents",
"Info.plist",
);
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name
.replace("Electron Helper", "")
.replace(".app", "")
.trim();
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix
.replace(/[()]/g, "")
.trim()
.toLowerCase()
.replace(/\s+/g, "-");
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
@@ -125,12 +101,7 @@ function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(
targetAppBundlePath,
"Contents",
"MacOS",
"Electron",
);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
+5 -2
View File
@@ -126,7 +126,9 @@ function registerDesktopProtocol(): void {
const staticRoot = resolveDesktopStaticDir();
if (!staticRoot) {
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
throw new Error(
"Desktop static bundle missing. Build apps/server (with bundled client) first.",
);
}
const staticRootResolved = path.resolve(staticRoot);
@@ -160,7 +162,8 @@ function registerDesktopProtocol(): void {
}
function dispatchMenuAction(action: string): void {
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const existingWindow =
BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const targetWindow = existingWindow ?? createWindow();
if (!existingWindow) {
mainWindow = targetWindow;
@@ -13,10 +13,10 @@ const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
function baseEvent(eventId: string, createdAt: string): Pick<
ProviderRuntimeEvent,
"eventId" | "provider" | "sessionId" | "createdAt"
> {
function baseEvent(
eventId: string,
createdAt: string,
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.makeUnsafe(eventId),
provider: PROVIDER,
@@ -29,10 +29,12 @@ const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId =>
ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = asThreadId("thread-1");
@@ -45,7 +47,8 @@ function nowIso() {
return new Date().toISOString();
}
const sleep = (ms: number) => Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
function waitForSync<A>(
read: () => A,
@@ -78,9 +81,7 @@ function runtimeBase(eventId: string, createdAt: string) {
};
}
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness,
use,
@@ -176,7 +177,9 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
THREAD_ID,
(entry) =>
entry.session?.status === "ready" &&
entry.messages.some((message) => message.role === "assistant" && message.streaming === false) &&
entry.messages.some(
(message) => message.role === "assistant" && message.streaming === false,
) &&
entry.checkpoints.length === 1,
);
assert.equal(thread.checkpoints[0]?.status, "ready");
@@ -317,7 +320,10 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
const secondCheckpoint = secondTurnThread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === 2,
);
assert.equal(secondCheckpoint?.files.some((file) => file.path === "README.md"), true);
assert.equal(
secondCheckpoint?.files.some((file) => file.path === "README.md"),
true,
);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
@@ -394,9 +400,8 @@ it.live("tracks approval requests and resolves pending approvals on user respons
text: "Run command needing approval",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.activities.some((activity) => activity.kind === "approval.requested"),
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(
thread.activities.some((activity) => activity.kind === "approval.requested"),
@@ -687,39 +692,39 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
),
);
it.live("appends checkpoint.revert.failed activity when revert is requested without an active session", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
it.live(
"appends checkpoint.revert.failed activity when revert is requested without an active session",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
});
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: asCommandId("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some(
(activity) =>
activity.kind === "checkpoint.revert.failed" &&
typeof activity.payload === "object" &&
activity.payload !== null,
),
);
const failureActivity = thread.activities.find(
(activity) => activity.kind === "checkpoint.revert.failed",
);
assert.equal(failureActivity !== undefined, true);
assert.equal(
String((failureActivity?.payload as { readonly detail?: string } | undefined)?.detail).includes(
"No active provider session",
),
true,
);
}),
),
);
const failureActivity = thread.activities.find(
(activity) => activity.kind === "checkpoint.revert.failed",
);
assert.equal(failureActivity !== undefined, true);
assert.equal(
String(
(failureActivity?.payload as { readonly detail?: string } | undefined)?.detail,
).includes("No active provider session"),
true,
);
}),
),
);
@@ -127,7 +127,7 @@ it.effect("replays typed runtime fixture events", () =>
harness: fixture.harness,
sessionId: session.sessionId,
userText: "hello",
response: { events: codexTurnTextFixture },
response: { events: codexTurnTextFixture },
});
assert.deepEqual(
+3 -1
View File
@@ -6,7 +6,9 @@ export interface TurnDiffFileSummary {
readonly deletions: number;
}
export function parseTurnDiffFilesFromUnifiedDiff(diff: string): ReadonlyArray<TurnDiffFileSummary> {
export function parseTurnDiffFilesFromUnifiedDiff(
diff: string,
): ReadonlyArray<TurnDiffFileSummary> {
const normalized = diff.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
return [];
+10 -9
View File
@@ -383,7 +383,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return this.parseThreadSnapshot("thread/read", response);
}
async rollbackThread(sessionId: ProviderSessionId, numTurns: number): Promise<CodexThreadSnapshot> {
async rollbackThread(
sessionId: ProviderSessionId,
numTurns: number,
): Promise<CodexThreadSnapshot> {
const context = this.requireSession(sessionId);
const threadId = context.session.threadId;
if (!threadId) {
@@ -822,19 +825,18 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
const responseRecord = this.readObject(response);
const thread = this.readObject(responseRecord, "thread");
const threadIdRaw = this.readString(thread, "id") ??
this.readString(responseRecord, "threadId");
const threadIdRaw =
this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
if (!threadIdRaw) {
throw new Error(`${method} response did not include a thread id.`);
}
const threadId = ProviderThreadId.makeUnsafe(threadIdRaw);
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
const turnsRaw =
this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
const turns = turnsRaw.map((turnValue, index) => {
const turn = this.readObject(turnValue);
const turnIdRaw =
this.readString(turn, "id") ??
`${threadIdRaw}:turn:${index + 1}`;
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
const turnId = ProviderTurnId.makeUnsafe(turnIdRaw);
const items = this.readArray(turn, "items") ?? [];
return {
@@ -900,8 +902,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"),
);
const itemId = toProviderItemId(
this.readString(params, "itemId") ??
this.readString(this.readObject(params, "item"), "id"),
this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"),
);
if (threadId) {
+1
View File
@@ -10,6 +10,7 @@ export interface ServerConfigShape {
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
+265 -188
View File
@@ -1,225 +1,302 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, afterEach, describe, expect, it, vi } from "vitest";
import { KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
import { NodeServices } from "@effect/platform-node";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
import { ServerConfig, type ServerConfigShape } from "./config";
import {
Keybindings,
KeybindingsConfigError,
KeybindingsLive,
compileResolvedKeybindingRule,
parseKeybindingShortcut,
upsertKeybindingRule,
} from "./keybindings";
describe("server keybindings", () => {
const tempDirs: string[] = [];
const logger = {
warn: vi.fn(),
};
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () =>
KeybindingsLive.pipe(
Layer.provideMerge(
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
),
),
);
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
Effect.mapError((error) => error.detail),
Effect.result,
);
afterEach(() => {
vi.restoreAllMocks();
logger.warn.mockReset();
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(
rules.map((rule) => KeybindingRule.makeUnsafe(rule)),
);
yield* fileSystem.writeFileString(configPath, encoded);
});
it("parses shortcuts including plus key", () => {
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
assert.deepEqual(parseKeybindingShortcut("mod++"), {
key: "+",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
const readKeybindingsConfig = (configPath: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const rawConfig = yield* fileSystem.readFileString(configPath);
return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig);
});
it("compiles valid rule with parsed when AST", () => {
const compiled = compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalOpen && !terminalFocus",
});
assert.deepEqual(compiled, {
command: "terminal.split",
shortcut: {
key: "d",
it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("parses shortcuts including plus key", () =>
Effect.sync(() => {
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "and",
left: { type: "identifier", name: "terminalOpen" },
right: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
});
assert.deepEqual(parseKeybindingShortcut("mod++"), {
key: "+",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
}),
);
it.effect("compiles valid rule with parsed when AST", () =>
Effect.sync(() => {
const compiled = compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalOpen && !terminalFocus",
});
assert.deepEqual(compiled, {
command: "terminal.split",
shortcut: {
key: "d",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
},
});
});
whenAst: {
type: "and",
left: { type: "identifier", name: "terminalOpen" },
right: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
});
}),
);
it("rejects invalid rules", () => {
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+shift+d+o",
command: "terminal.new",
}),
);
it.effect("rejects invalid rules", () =>
Effect.sync(() => {
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+shift+d+o",
command: "terminal.new",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
});
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
}),
);
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
it.effect("upserts custom keybindings to configured path", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+j", command: "terminal.toggle" },
]);
const resolved = upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
const resolved = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
});
expect(persisted).toEqual([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
it("replaces existing custom keybinding for the same command", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
assert.deepEqual(persistedView, [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
assert.isTrue(resolved.some((entry) => entry.command === "script.run-tests.run"));
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
it.effect("replaces existing custom keybinding for the same command", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+r", command: "script.run-tests.run" },
]);
yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it("refuses to overwrite malformed keybindings config", () => {
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, "{ not-json", "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
it.effect("refuses to overwrite malformed keybindings config", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig;
yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/Unable to parse keybindings config/);
const result = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(toDetailResult);
assertFailure(result, "expected JSON array");
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
});
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
assert.equal(persistedRaw, "{ not-json");
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it("reports non-array config parse errors without duplicate prefix", () => {
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
it.effect("reports non-array config parse errors without duplicate prefix", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig;
yield* fs.writeFileString(
keybindingsConfigPath,
'{"key":"mod+j","command":"terminal.toggle"}',
);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
const firstResult = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(toDetailResult);
assertFailure(firstResult, "expected JSON array");
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).not.toThrow(
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
);
});
const secondResult = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(toDetailResult);
assertFailure(secondResult, "expected JSON array");
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it("cleans up temp files when atomic keybinding write fails", () => {
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
vi.spyOn(fs, "renameSync").mockImplementation(() => {
throw new Error("rename failed");
});
it.effect("fails when config directory is not writable", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig;
const { dirname } = yield* Path.Path;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+j", command: "terminal.toggle" },
]);
yield* fs.chmod(dirname(keybindingsConfigPath), 0o500);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/rename failed/);
const result = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(toDetailResult);
assertFailure(result, "failed to write keybindings config");
expect(fs.readFileSync(configPath, "utf8")).toBe(
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
);
const tempFiles = fs
.readdirSync(configDir)
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
expect(tempFiles).toEqual([]);
});
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("caches loaded resolved config across repeated reads", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+j", command: "terminal.toggle" },
]);
const [first, second] = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
const firstLoad = yield* keybindings.loadResolvedKeybindingsConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+x", command: "script.setup.run" },
]);
const secondLoad = yield* keybindings.loadResolvedKeybindingsConfig;
return [firstLoad, secondLoad] as const;
});
assert.deepEqual(first, second);
assert.isTrue(second.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(second.some((entry) => entry.command === "script.setup.run"));
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("updates cached resolved config after upsert", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+j", command: "terminal.toggle" },
]);
const loadedAfterUpsert = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
yield* keybindings.loadResolvedKeybindingsConfig;
yield* keybindings.upsertKeybindingRule({
key: "mod+shift+r",
command: "script.run-tests.run",
});
yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
return yield* keybindings.loadResolvedKeybindingsConfig;
});
assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run"));
assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle"));
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
});
+219 -147
View File
@@ -1,20 +1,42 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
KeybindingRule,
KeybindingsConfig,
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { Mutable } from "effect/Types";
import { Schema } from "effect";
import {
Array,
Cause,
Effect,
FileSystem,
Path,
Layer,
Option,
Predicate,
Ref,
Schema,
SchemaIssue,
SchemaTransformation,
ServiceMap,
} from "effect";
import { ServerConfig } from "./config";
interface KeybindingsLogger {
warn(message: string, context?: Record<string, unknown>): void;
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
{
configPath: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
}
}
type WhenToken =
@@ -25,8 +47,6 @@ type WhenToken =
| { type: "lparen" }
| { type: "rparen" };
const MAX_WHEN_EXPRESSION_DEPTH = 256;
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
@@ -44,6 +64,7 @@ function normalizeKeyToken(token: string): string {
return token;
}
/** @internal - Exported for testing */
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
const rawTokens = value
.toLowerCase()
@@ -157,7 +178,7 @@ function tokenizeWhenExpression(expression: string): WhenToken[] | null {
return tokens;
}
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;
@@ -242,6 +263,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return ast;
}
/** @internal - Exported for testing */
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
const key = rule.key.trim();
if (key.length === 0) return null;
@@ -270,113 +292,85 @@ export function compileResolvedKeybindingsConfig(
): ResolvedKeybindingsConfig {
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
for (const rule of config) {
const resolved = compileResolvedKeybindingRule(rule);
if (!resolved) continue;
compiled.push(resolved);
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
if (result._tag === "Success") {
compiled.push(result.value);
}
}
return compiled;
}
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
const resolved: Mutable<ResolvedKeybindingsConfig> = [];
for (const rule of DEFAULT_KEYBINDINGS) {
const compiled = compileResolvedKeybindingRule(rule);
if (!compiled) {
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
}
resolved.push(compiled);
}
return resolved;
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Schema.decodeTo(
Schema.toType(ResolvedKeybindingRule),
SchemaTransformation.transformOrFail({
decode: (rule) =>
Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
Effect.filterOrFail(
Predicate.isNotNull,
() =>
new SchemaIssue.InvalidValue(Option.some(rule), {
title: "Invalid keybinding rule",
}),
),
Effect.map((resolved) => ResolvedKeybindingRule.makeUnsafe(resolved)),
),
encode: (resolved) =>
Effect.gen(function* () {
const key = encodeShortcut(resolved.shortcut);
if (!key) {
return yield* Effect.fail(
new SchemaIssue.InvalidValue(Option.some(resolved), {
title: "Resolved shortcut cannot be encoded to key string",
}),
);
}
const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
return {
key,
command: resolved.command,
when,
};
}),
}),
),
);
export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
const modifiers: string[] = [];
if (shortcut.modKey) modifiers.push("mod");
if (shortcut.metaKey) modifiers.push("meta");
if (shortcut.ctrlKey) modifiers.push("ctrl");
if (shortcut.altKey) modifiers.push("alt");
if (shortcut.shiftKey) modifiers.push("shift");
if (!shortcut.key || shortcut.key.includes("+")) return null;
const key = shortcut.key === " " ? "space" : shortcut.key;
return [...modifiers, key].join("+");
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
const MAX_KEYBINDINGS = 256;
class KeybindingsConfigParseError extends Error {
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
function encodeWhenAst(node: KeybindingWhenNode): string {
switch (node.type) {
case "identifier":
return node.name;
case "not":
return `!(${encodeWhenAst(node.node)})`;
case "and":
return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
case "or":
return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
}
}
function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
function loadCustomKeybindingsConfig(
logger: KeybindingsLogger,
options?: {
throwOnUnreadableConfig?: boolean;
},
): KeybindingsConfig {
const configPath = resolveKeybindingsConfigPath();
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
if (options?.throwOnUnreadableConfig) {
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [];
}
const sanitized: Mutable<KeybindingsConfig> = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = Schema.decodeExit(KeybindingRule)(entry);
if (result._tag === "Success") {
if (!compileResolvedKeybindingRule(result.value)) {
invalidEntries += 1;
continue;
}
sanitized.push(result.value);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
return sanitized;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
if (options?.throwOnUnreadableConfig) {
if (error instanceof KeybindingsConfigParseError) {
throw error;
}
throw new KeybindingsConfigParseError(
configPath,
error instanceof Error ? error.message : String(error),
{ cause: error },
);
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
});
return [];
}
}
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
fs.renameSync(tempPath, configPath);
} catch (error) {
fs.rmSync(tempPath, { force: true });
throw error;
}
}
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
@@ -389,55 +383,133 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
);
const merged = [...retainedDefaults, ...custom];
if (merged.length <= MAX_KEYBINDINGS) {
if (merged.length <= MAX_KEYBINDINGS_COUNT) {
return merged;
}
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
return merged.slice(-MAX_KEYBINDINGS);
return merged.slice(-MAX_KEYBINDINGS_COUNT);
}
export function loadResolvedKeybindingsConfig(
logger: KeybindingsLogger,
): ResolvedKeybindingsConfig {
const customConfig = loadCustomKeybindingsConfig(logger);
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + compiledCustomConfig.length;
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
logger.warn("truncating merged keybindings config to max entries", {
path: resolveKeybindingsConfigPath(),
maxEntries: MAX_KEYBINDINGS,
});
}
return merged;
export interface KeybindingsShape {
readonly loadResolvedKeybindingsConfig: Effect.Effect<
readonly ResolvedKeybindingRule[],
KeybindingsConfigError
>;
readonly upsertKeybindingRule: (
rule: KeybindingRule,
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
}
export function upsertKeybindingRule(
logger: KeybindingsLogger,
rule: KeybindingRule,
): ResolvedKeybindingsConfig {
const configPath = resolveKeybindingsConfigPath();
const customConfig = loadCustomKeybindingsConfig(logger, {
throwOnUnreadableConfig: true,
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
"server/Keybindings",
) {}
const makeKeybindings = Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cachedResolvedConfig = yield* Ref.make<ResolvedKeybindingsConfig | null>(null);
const loadCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
readonly KeybindingRule[],
KeybindingsConfigError
> {
const rawConfig = yield* fs.readFileString(keybindingsConfigPath).pipe(
Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
detail: "expected JSON array",
cause,
}),
),
);
return yield* Effect.forEach(rawConfig, (entry) =>
Effect.gen(function* () {
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
if (decodedRule._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
entry,
error: Cause.pretty(decodedRule.cause),
});
return null;
}
const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
if (resolved._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
entry,
error: Cause.pretty(resolved.cause),
});
return null;
}
return decodedRule.value;
}),
).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
});
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS) {
logger.warn("truncating keybindings config to max entries", {
path: configPath,
maxEntries: MAX_KEYBINDINGS,
});
}
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
fs.mkdirSync(path.dirname(configPath), { recursive: true });
writeConfigAtomically(configPath, cappedConfig);
return Schema.encodeEffect(KeybindingsConfigJson)(
rules.map((rule) => KeybindingRule.makeUnsafe(rule)),
).pipe(
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
detail: "failed to write keybindings config",
cause,
}),
),
);
};
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
return mergeWithDefaultKeybindings(compiledCustomConfig);
}
const loadResolvedFromCacheOrDisk = Effect.gen(function* () {
const cached = yield* Ref.get(cachedResolvedConfig);
if (cached) return cached;
const resolved = yield* loadCustomKeybindingsConfig().pipe(
Effect.map(compileResolvedKeybindingsConfig),
Effect.map(mergeWithDefaultKeybindings),
);
yield* Ref.set(cachedResolvedConfig, resolved);
return resolved;
});
return {
loadResolvedKeybindingsConfig: loadResolvedFromCacheOrDisk,
upsertKeybindingRule: (rule) =>
Effect.gen(function* () {
const customConfig = yield* loadCustomKeybindingsConfig();
const nextConfig = [
...customConfig.filter((entry) => entry.command !== rule.command),
rule,
];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS_COUNT
? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
: nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
yield* Effect.logWarning("truncating keybindings config to max entries", {
path: keybindingsConfigPath,
maxEntries: MAX_KEYBINDINGS_COUNT,
});
}
yield* writeConfigAtomically(cappedConfig);
const nextResolved = mergeWithDefaultKeybindings(
compileResolvedKeybindingsConfig(cappedConfig),
);
yield* Ref.set(cachedResolvedConfig, nextResolved);
return nextResolved;
}),
} satisfies KeybindingsShape;
});
export const KeybindingsLive = Layer.effect(Keybindings, makeKeybindings);
+3
View File
@@ -120,6 +120,8 @@ const ServerConfigLive = (input: CliInput) =>
});
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
const host =
Option.getOrUndefined(input.host) ??
env.host ??
@@ -129,6 +131,7 @@ const ServerConfigLive = (input: CliInput) =>
mode,
port,
cwd: cliConfig.cwd,
keybindingsConfigPath,
host,
stateDir,
staticDir,
+13 -15
View File
@@ -11,18 +11,16 @@ describe("resolveEditorLaunch", () => {
});
it("maps file-manager editor to OS open commands", () => {
expect(resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "file-manager" }, "darwin")).toEqual(
{
command: "open",
args: ["/tmp/workspace"],
},
);
expect(resolveEditorLaunch({ cwd: "C:\\workspace", editor: "file-manager" }, "win32")).toEqual(
{
command: "explorer",
args: ["C:\\workspace"],
},
);
expect(
resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "file-manager" }, "darwin"),
).toEqual({
command: "open",
args: ["/tmp/workspace"],
});
expect(resolveEditorLaunch({ cwd: "C:\\workspace", editor: "file-manager" }, "win32")).toEqual({
command: "explorer",
args: ["C:\\workspace"],
});
expect(resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "file-manager" }, "linux")).toEqual(
{
command: "xdg-open",
@@ -40,8 +38,8 @@ describe("launchDetached", () => {
});
it("rejects when command does not exist", async () => {
await expect(
launchDetached(`t3code-no-such-command-${Date.now()}`, []),
).rejects.toBeInstanceOf(Error);
await expect(launchDetached(`t3code-no-such-command-${Date.now()}`, [])).rejects.toBeInstanceOf(
Error,
);
});
});
@@ -41,8 +41,7 @@ const asCommandId = (value: string): CommandId => CommandId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId =>
ProviderThreadId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
function checkpointRefForTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
@@ -474,11 +473,12 @@ describe("CheckpointReactor", () => {
status: "completed",
});
const thread = await waitForThread(
harness.engine,
(entry) => entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
const thread = await waitForThread(harness.engine, (entry) =>
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
);
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
true,
);
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(true);
});
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
@@ -581,5 +581,4 @@ describe("CheckpointReactor", () => {
);
expect(harness.provider.rollbackConversation).not.toHaveBeenCalled();
});
});
@@ -347,13 +347,10 @@ const make = Effect.gen(function* () {
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning(
"checkpoint pre-turn capture skipped: no workspace cwd",
{
threadId: thread.id,
turnId,
},
);
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId: thread.id,
turnId,
});
return;
}
@@ -377,10 +374,17 @@ const make = Effect.gen(function* () {
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-start-requested" | "thread.message-sent" }>,
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
>,
) {
if (event.type === "thread.message-sent") {
if (event.payload.role !== "user" || event.payload.streaming || event.payload.turnId !== null) {
if (
event.payload.role !== "user" ||
event.payload.streaming ||
event.payload.turnId !== null
) {
return;
}
}
@@ -403,12 +407,9 @@ const make = Effect.gen(function* () {
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning(
"checkpoint pre-turn capture skipped: no workspace cwd",
{
threadId,
},
);
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId,
});
return;
}
@@ -24,4 +24,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
} satisfies OrchestrationReactorShape;
});
export const OrchestrationReactorLive = Layer.effect(OrchestrationReactor, makeOrchestrationReactor);
export const OrchestrationReactorLive = Layer.effect(
OrchestrationReactor,
makeOrchestrationReactor,
);
@@ -479,7 +479,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
defaultModel: "gpt-5",
});
const projectRows = yield* sql<{ readonly scriptsJson: string; readonly defaultModel: string }>`
const projectRows = yield* sql<{
readonly scriptsJson: string;
readonly defaultModel: string;
}>`
SELECT
scripts_json AS "scriptsJson",
default_model AS "defaultModel"
@@ -1,7 +1,4 @@
import {
ApprovalRequestId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
import { Effect, Layer, Option, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -119,8 +116,7 @@ function retainProjectionMessagesAfterRevert(
if (missingAssistantCount > 0) {
const fallbackAssistantMessages = messages
.filter(
(message) =>
message.role === "assistant" && !retainedMessageIds.has(message.messageId),
(message) => message.role === "assistant" && !retainedMessageIds.has(message.messageId),
)
.toSorted(
(left, right) =>
@@ -142,9 +138,7 @@ function retainProjectionActivitiesAfterRevert(
turnCount: number,
): ReadonlyArray<ProjectionThreadActivity> {
const retainedTurnIds = new Set(
turns
.filter((turn) => turn.turnCount <= turnCount)
.map((turn) => turn.turnId),
turns.filter((turn) => turn.turnCount <= turnCount).map((turn) => turn.turnId),
);
return activities.filter(
(activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
@@ -354,7 +348,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
});
const existingMessage = existingRows.find((row) => row.messageId === event.payload.messageId);
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
@@ -496,7 +492,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionThreadTurnRepository.upsert({
...existingTurn.value,
status: existingTurn.value.status === "completed" ? "completed" : "running",
userMessageId: existingTurn.value.userMessageId ?? (pendingTurnStart?.messageId ?? null),
userMessageId:
existingTurn.value.userMessageId ?? pendingTurnStart?.messageId ?? null,
startedAt: existingTurn.value.startedAt,
});
} else {
@@ -23,7 +23,8 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId =>
ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const projectionSnapshotLayer = it.layer(
@@ -245,10 +245,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql.withTransaction(
Effect.gen(function* () {
const [projectRows, threadRows, messageRows, activityRows, sessionRows, checkpointRows, stateRows] =
yield* Effect.all([
sql
.withTransaction(
Effect.gen(function* () {
const [
projectRows,
threadRows,
messageRows,
activityRows,
sessionRows,
checkpointRows,
stateRows,
] = yield* Effect.all([
listProjectRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -307,122 +315,127 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
]);
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
let updatedAt: string | null = null;
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 stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of messageRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
const threadMessages = messagesByThread.get(row.threadId) ?? [];
threadMessages.push({
id: row.messageId,
role: row.role,
text: row.text,
turnId: row.turnId,
streaming: row.isStreaming === 1,
for (const row of messageRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
const threadMessages = messagesByThread.get(row.threadId) ?? [];
threadMessages.push({
id: row.messageId,
role: row.role,
text: row.text,
turnId: row.turnId,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
messagesByThread.set(row.threadId, threadMessages);
}
for (const row of activityRows) {
updatedAt = maxIso(updatedAt, row.createdAt);
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
threadActivities.push({
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
for (const row of checkpointRows) {
updatedAt = maxIso(updatedAt, row.completedAt);
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
threadCheckpoints.push({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
checkpointRef: row.checkpointRef,
status: row.status,
files: row.files,
assistantMessageId: row.assistantMessageId,
completedAt: row.completedAt,
});
checkpointsByThread.set(row.threadId, threadCheckpoints);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
sessionsByThread.set(row.threadId, {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
providerSessionId: row.providerSessionId,
providerThreadId: row.providerThreadId,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
updatedAt: row.updatedAt,
});
}
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModel: row.defaultModel,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
messagesByThread.set(row.threadId, threadMessages);
}
deletedAt: row.deletedAt,
}));
for (const row of activityRows) {
updatedAt = maxIso(updatedAt, row.createdAt);
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
threadActivities.push({
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
model: row.model,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurnId: row.latestTurnId,
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
for (const row of checkpointRows) {
updatedAt = maxIso(updatedAt, row.completedAt);
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
threadCheckpoints.push({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
checkpointRef: row.checkpointRef,
status: row.status,
files: row.files,
assistantMessageId: row.assistantMessageId,
completedAt: row.completedAt,
});
checkpointsByThread.set(row.threadId, threadCheckpoints);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
sessionsByThread.set(row.threadId, {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
providerSessionId: row.providerSessionId,
providerThreadId: row.providerThreadId,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
updatedAt: row.updatedAt,
});
}
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModel: row.defaultModel,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}));
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects,
threads,
updatedAt: updatedAt ?? new Date(0).toISOString(),
};
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
model: row.model,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurnId: row.latestTurnId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects,
threads,
updatedAt: updatedAt ?? new Date(0).toISOString(),
};
return yield* decodeReadModel(snapshot).pipe(
Effect.mapError(toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel")),
);
}),
).pipe(Effect.mapError(toProjectionRepositoryError("ProjectionSnapshotQuery.getSnapshot:query")));
return yield* decodeReadModel(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
),
);
}),
)
.pipe(
Effect.mapError(toProjectionRepositoryError("ProjectionSnapshotQuery.getSnapshot:query")),
);
return {
getSnapshot,
@@ -31,14 +31,12 @@ const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
async function waitFor(
predicate: () => boolean,
timeoutMs = 2000,
): Promise<void> {
async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (predicate()) {
@@ -344,7 +344,9 @@ const make = Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderIntentEvent>();
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
yield* Effect.forkScoped(Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processDomainEvent))));
yield* Effect.forkScoped(
Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processDomainEvent))),
);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
@@ -29,7 +29,9 @@ function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 1)}...` : value;
}
function runtimeEventToActivities(event: ProviderRuntimeEvent): ReadonlyArray<OrchestrationThreadActivity> {
function runtimeEventToActivities(
event: ProviderRuntimeEvent,
): ReadonlyArray<OrchestrationThreadActivity> {
switch (event.type) {
case "approval.requested": {
return [
@@ -184,14 +186,16 @@ const make = Effect.gen(function* () {
event.type === "turn.started" ||
event.type === "turn.completed"
) {
const activeTurnId = event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
const activeTurnId =
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
const providerThreadIdFromEvent =
event.type === "thread.started"
? ProviderThreadId.makeUnsafe(event.threadId)
: event.threadId !== undefined
? ProviderThreadId.makeUnsafe(event.threadId)
: null;
const providerThreadId = providerThreadIdFromEvent ?? (thread.session?.providerThreadId ?? null);
const providerThreadId =
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
const status =
event.type === "turn.started"
? "running"
@@ -199,7 +203,7 @@ const make = Effect.gen(function* () {
? "stopped"
: event.type === "turn.completed" && event.status === "failed"
? "error"
: "ready";
: "ready";
const lastError =
event.type === "turn.completed" && event.status === "failed"
? (event.errorMessage ?? thread.session?.lastError ?? "Turn failed")
+2 -1
View File
@@ -33,7 +33,8 @@ export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload = ContractsThreadTurnInterruptRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
ContractsThreadTurnInterruptRequestedPayloadSchema;
export const ThreadApprovalResponseRequestedPayload =
ContractsThreadApprovalResponseRequestedPayloadSchema;
export const ThreadCheckpointRevertRequestedPayload =
@@ -2,7 +2,10 @@ import type { OrchestrationEvent } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { OrchestrationEventStoreError, ProjectionRepositoryError } from "../../persistence/Errors.ts";
import type {
OrchestrationEventStoreError,
ProjectionRepositoryError,
} from "../../persistence/Errors.ts";
export type OrchestrationProjectionPipelineError =
| OrchestrationEventStoreError
@@ -38,13 +38,11 @@ export function listThreadsByProjectId(
return readModel.threads.filter((thread) => thread.projectId === projectId);
}
export function requireProject(
input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly projectId: ProjectId;
},
): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {
export function requireProject(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly projectId: ProjectId;
}): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {
const project = findProjectById(input.readModel, input.projectId);
if (project) {
return Effect.succeed(project);
@@ -57,13 +55,11 @@ export function requireProject(
);
}
export function requireProjectAbsent(
input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly projectId: ProjectId;
},
): Effect.Effect<void, OrchestrationCommandInvariantError> {
export function requireProjectAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly projectId: ProjectId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
if (!findProjectById(input.readModel, input.projectId)) {
return Effect.void;
}
@@ -75,13 +71,11 @@ export function requireProjectAbsent(
);
}
export function requireThread(
input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
},
): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
export function requireThread(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
const thread = findThreadById(input.readModel, input.threadId);
if (thread) {
return Effect.succeed(thread);
@@ -94,13 +88,11 @@ export function requireThread(
);
}
export function requireThreadAbsent(
input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
},
): Effect.Effect<void, OrchestrationCommandInvariantError> {
export function requireThreadAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
if (!findThreadById(input.readModel, input.threadId)) {
return Effect.void;
}
@@ -112,13 +104,11 @@ export function requireThreadAbsent(
);
}
export function requireNonNegativeInteger(
input: {
readonly commandType: OrchestrationCommand["type"];
readonly field: string;
readonly value: number;
},
): Effect.Effect<void, OrchestrationCommandInvariantError> {
export function requireNonNegativeInteger(input: {
readonly commandType: OrchestrationCommand["type"];
readonly field: string;
readonly value: number;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
if (Number.isInteger(input.value) && input.value >= 0) {
return Effect.void;
}
+2 -1
View File
@@ -491,7 +491,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command.activity.payload !== null &&
"requestId" in command.activity.payload &&
typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
? ((command.activity.payload as { requestId: string }).requestId as OrchestrationEvent["metadata"]["requestId"])
? ((command.activity.payload as { requestId: string })
.requestId as OrchestrationEvent["metadata"]["requestId"])
: undefined;
return {
...withEventBase({
@@ -1,4 +1,10 @@
import { CommandId, EventId, ProjectId, ThreadId, type OrchestrationEvent } from "@t3tools/contracts";
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
@@ -484,13 +490,15 @@ describe("orchestration projector", () => {
);
const thread = afterRevert.threads[0];
expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual([
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
]);
expect(thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId }))).toEqual([
{ id: "activity-1", turnId: "turn-1" },
]);
expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
expect(
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
expect(thread?.latestTurnId).toBe("turn-1");
});
+8 -23
View File
@@ -1,8 +1,4 @@
import type {
OrchestrationEvent,
OrchestrationReadModel,
ThreadId,
} from "@t3tools/contracts";
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
import {
OrchestrationCheckpointSummary,
OrchestrationMessage,
@@ -147,19 +143,16 @@ export function projectEvent(
return {
...nextBase,
projects: existing
? nextBase.projects.map((entry) => (entry.id === payload.projectId ? nextProject : entry))
? nextBase.projects.map((entry) =>
entry.id === payload.projectId ? nextProject : entry,
)
: [...nextBase.projects, nextProject],
};
}),
);
case "project.meta-updated":
return decodeForEvent(
ProjectMetaUpdatedPayload,
event.payload,
event.type,
"payload",
).pipe(
return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
projects: nextBase.projects.map((project) =>
@@ -247,12 +240,7 @@ export function projectEvent(
);
case "thread.meta-updated":
return decodeForEvent(
ThreadMetaUpdatedPayload,
event.payload,
event.type,
"payload",
).pipe(
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -415,13 +403,10 @@ export function projectEvent(
retainedTurnIds,
payload.turnCount,
);
const activities = retainThreadActivitiesAfterRevert(
thread.activities,
retainedTurnIds,
);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const latestTurnId =
checkpoints.length > 0 ? checkpoints[checkpoints.length - 1]?.turnId ?? null : null;
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
return {
...nextBase,
@@ -88,10 +88,7 @@ function inferActorKind(
return "client";
}
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
) {
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): OrchestrationEventStoreError =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
@@ -3,10 +3,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import {
toPersistenceDecodeError,
toPersistenceSqlError,
} from "../Errors.ts";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import {
DeleteByThreadIdInput,
GetByThreadAndTurnCountInput,
@@ -111,7 +111,9 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
),
),
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivity>>),
Effect.map(
(rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivity>>,
),
);
const deleteByThreadId: ProjectionThreadActivityRepositoryShape["deleteByThreadId"] = (input) =>
@@ -72,9 +72,7 @@ function toPersistenceError(
});
}
function toEntry(
row: Schema.Schema.Type<typeof ProviderSessionRowSchema>,
): ProviderSessionEntry {
function toEntry(row: Schema.Schema.Type<typeof ProviderSessionRowSchema>): ProviderSessionEntry {
return {
sessionId: row.sessionId,
provider: row.provider,
@@ -129,7 +129,10 @@ function makeFakeCodexAdapter() {
(
_sessionId: ProviderSessionId,
): Effect.Effect<
{ threadId: ProviderThreadId; turns: ReadonlyArray<{ id: ProviderTurnId; items: readonly [] }> },
{
threadId: ProviderThreadId;
turns: ReadonlyArray<{ id: ProviderTurnId; items: readonly [] }>;
},
ProviderAdapterError
> =>
Effect.succeed({
@@ -290,101 +293,103 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("ProviderServiceLive restores rollback routing after restart using persisted thread mapping", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-restart-"));
const dbPath = path.join(tempDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(persistenceLayer),
);
it.effect(
"ProviderServiceLive restores rollback routing after restart using persisted thread mapping",
() =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-restart-"));
const dbPath = path.join(tempDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(persistenceLayer),
);
const firstCodex = makeFakeCodexAdapter();
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(firstCodex.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const firstCodex = makeFakeCodexAdapter();
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(firstCodex.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
);
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
);
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession({
provider: "codex",
cwd: "/tmp/project",
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.stopAll();
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
return yield* repository.getBySessionId({
providerSessionId: startedSession.sessionId,
});
}).pipe(Effect.provide(runtimeRepositoryLayer));
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, {
resumeThreadId: startedSession.threadId,
});
}
const secondCodex = makeFakeCodexAdapter();
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(secondCodex.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
);
secondCodex.startSession.mockClear();
secondCodex.rollbackThread.mockClear();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.rollbackConversation({
sessionId: startedSession.sessionId,
numTurns: 1,
});
}).pipe(Effect.provide(secondProviderLayer));
assert.deepEqual(secondCodex.startSession.mock.calls, [
[
{
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession({
provider: "codex",
resumeThreadId: startedSession.threadId,
},
],
]);
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
const rollbackCall = secondCodex.rollbackThread.mock.calls[0];
assert.equal(typeof rollbackCall?.[0], "string");
assert.equal(rollbackCall?.[1], 1);
cwd: "/tmp/project",
});
}).pipe(Effect.provide(firstProviderLayer));
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.stopAll();
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
return yield* repository.getBySessionId({
providerSessionId: startedSession.sessionId,
});
}).pipe(Effect.provide(runtimeRepositoryLayer));
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, {
resumeThreadId: startedSession.threadId,
});
}
const secondCodex = makeFakeCodexAdapter();
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(secondCodex.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
);
secondCodex.startSession.mockClear();
secondCodex.rollbackThread.mockClear();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.rollbackConversation({
sessionId: startedSession.sessionId,
numTurns: 1,
});
}).pipe(Effect.provide(secondProviderLayer));
assert.deepEqual(secondCodex.startSession.mock.calls, [
[
{
provider: "codex",
resumeThreadId: startedSession.threadId,
},
],
]);
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
const rollbackCall = secondCodex.rollbackThread.mock.calls[0];
assert.equal(typeof rollbackCall?.[0], "string");
assert.equal(rollbackCall?.[1], 1);
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
routing.layer("ProviderServiceLive routing", (it) => {
@@ -574,7 +579,10 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
const events = yield* Ref.get(eventsRef);
yield* Fiber.interrupt(consumer);
assert.equal(events.some((entry) => entry.type === "turn.completed"), true);
assert.equal(
events.some((entry) => entry.type === "turn.completed"),
true,
);
}),
);
@@ -586,11 +594,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
});
const receivedByHealthy: string[] = [];
const expectedEventIds = new Set<string>([
"evt-ordered-1",
"evt-ordered-2",
"evt-ordered-3",
]);
const expectedEventIds = new Set<string>(["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"]);
const healthyFiber = yield* Stream.take(provider.streamEvents, 3).pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
@@ -649,11 +653,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
assert.deepEqual(
receivedByHealthy.filter((eventId) => expectedEventIds.has(eventId)).slice(0, 3),
[
"evt-ordered-1",
"evt-ordered-2",
"evt-ordered-3",
],
["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"],
);
}),
);
@@ -712,9 +712,9 @@ validation.layer("ProviderServiceLive validation", (it) => {
assertFailure(
failure,
new ProviderValidationError({
operation: "ProviderService.startSession",
issue: "Provider 'codex' returned a session without threadId.",
}),
operation: "ProviderService.startSession",
issue: "Provider 'codex' returned a session without threadId.",
}),
);
}),
);
@@ -3,17 +3,16 @@ import os from "node:os";
import path from "node:path";
import { NodeServices } from "@effect/platform-node";
import {
ProviderSessionId,
ProviderThreadId,
ThreadId,
} from "@t3tools/contracts";
import { ProviderSessionId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
import { it, assert } from "@effect/vitest";
import { assertFailure, assertSome } from "@effect/vitest/utils";
import { Effect, Layer, Option } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionNotFoundError, ProviderValidationError } from "../Errors.ts";
@@ -78,7 +78,6 @@ export interface ProviderSessionDirectoryShape {
ReadonlyArray<ProviderSessionId>,
ProviderSessionDirectoryPersistenceError
>;
}
/**
+6 -2
View File
@@ -28,6 +28,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
import { makeTerminalManagerLive, TerminalManager } from "./terminalManager";
import { PtyAdapter } from "./ptyAdapter";
import { Keybindings, KeybindingsLive } from "./keybindings";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
@@ -55,7 +56,8 @@ export function makeServerRuntimeServicesLayer(): Layer.Layer<
| ProjectionSnapshotQuery
| CheckpointStore
| OrchestrationReactor
| TerminalManager,
| TerminalManager
| Keybindings,
unknown,
SqlClient.SqlClient | ProviderService | ServerConfig
> {
@@ -93,5 +95,7 @@ export function makeServerRuntimeServicesLayer(): Layer.Layer<
}).pipe(Layer.provide(PtyAdapter.layer()));
}).pipe(Layer.unwrap);
return Layer.merge(orchestrationReactorLayer, terminalLayer);
const keybindingsLayer = KeybindingsLive.pipe(Layer.provide(NodeServices.layer));
return Layer.mergeAll(orchestrationReactorLayer, terminalLayer, keybindingsLayer);
}
@@ -2,13 +2,14 @@ import { assert, beforeEach, describe, it, vi } from "vitest";
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
const { runProcessMock } = vi.hoisted(() => ({
runProcessMock: vi.fn<
(
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>
>(),
runProcessMock:
vi.fn<
(
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>
>(),
}));
vi.mock("./processRunner", () => ({
+24 -24
View File
@@ -124,15 +124,15 @@ describe("searchWorkspaceEntries", () => {
let rootReadCount = 0;
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation(
(async (...args: Parameters<typeof fsPromises.readdir>) => {
if (args[0] === cwd) {
rootReadCount += 1;
await new Promise((resolve) => setTimeout(resolve, 20));
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir,
);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
if (args[0] === cwd) {
rootReadCount += 1;
await new Promise((resolve) => setTimeout(resolve, 20));
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
await Promise.all([
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
@@ -152,22 +152,22 @@ describe("searchWorkspaceEntries", () => {
let activeReads = 0;
let peakReads = 0;
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation(
(async (...args: Parameters<typeof fsPromises.readdir>) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await new Promise((resolve) => setTimeout(resolve, 4));
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await new Promise((resolve) => setTimeout(resolve, 4));
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir,
);
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
+1
View File
@@ -360,6 +360,7 @@ describe("WebSocket Server", () => {
port: 0,
host: undefined,
cwd: options.cwd ?? "/test/project",
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
stateDir,
staticDir: undefined,
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
+12 -6
View File
@@ -31,7 +31,7 @@ import {
removeGitWorktree,
} from "./git";
import { TerminalManager, type TerminalManagerShape } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { Keybindings } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
@@ -150,9 +150,13 @@ export type ServerCoreRuntimeServices =
| ProjectionSnapshotQuery
| CheckpointStore
| OrchestrationReactor
| Open;
| ProviderService;
export type ServerRuntimeServices = ServerCoreRuntimeServices | ProviderService | TerminalManager;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
| TerminalManager
| Keybindings
| Open;
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
"ServerLifecycleError",
@@ -171,8 +175,10 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
unknown, // TODO: This should not be unknown
Scope.Scope | ServerRuntimeServices | ServerConfig
> {
const { port, cwd, staticDir, devUrl, authToken, mode, host } = yield* ServerConfig;
const serverConfig = yield* ServerConfig;
const { port, cwd, staticDir, devUrl, authToken, mode, host } = serverConfig;
const defaultTerminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const {
logWebSocketEvents: explicitLogWsEvents,
gitManager = new GitManager(),
@@ -184,7 +190,6 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -571,11 +576,12 @@ export const createServer = Effect.fn(function* (options: ServerOptions = {}): E
}
case WS_METHODS.serverGetConfig:
const keybindingsConfig = yield* keybindingsManager.loadResolvedKeybindingsConfig;
return { cwd, keybindings: keybindingsConfig };
case WS_METHODS.serverUpsertKeybinding: {
const body = stripRequestTag(request.body);
keybindingsConfig = upsertKeybindingRule(logger, body);
const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
return { keybindings: keybindingsConfig };
}
+9 -1
View File
@@ -108,7 +108,15 @@ export default function BranchToolbar({
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch, api]);
}, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
envMode,
dispatch,
api,
]);
useEffect(() => {
if (isBranchMenuOpen) return;
+17 -26
View File
@@ -1,6 +1,7 @@
import {
EDITORS,
type EditorId,
type KeybindingCommand,
type NativeApi,
type ProjectEntry,
type ProjectScript,
@@ -10,20 +11,7 @@ import {
type ResolvedKeybindingsConfig,
type ProviderApprovalDecision,
} from "@t3tools/contracts";
import {
type ClipboardEvent,
type DragEvent,
type FormEvent,
type KeyboardEvent,
memo,
type RefObject,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
@@ -298,7 +286,7 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
triggerKind: ComposerTriggerKind | null;
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
commandInputRef: RefObject<HTMLInputElement | null>;
commandInputRef: React.RefObject<HTMLInputElement | null>;
}) {
return (
<Command
@@ -820,7 +808,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
previousScripts: ProjectScript[];
nextScripts: ProjectScript[];
keybinding?: string | null;
keybindingCommand: string;
keybindingCommand: KeybindingCommand;
}) => {
if (!api) return;
@@ -1250,7 +1238,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
};
const onComposerPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) {
return;
@@ -1263,7 +1251,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
addComposerImages(imageFiles);
};
const onComposerDragEnter = (event: DragEvent<HTMLDivElement>) => {
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
@@ -1272,7 +1260,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsDragOverComposer(true);
};
const onComposerDragOver = (event: DragEvent<HTMLDivElement>) => {
const onComposerDragOver = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
@@ -1281,7 +1269,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsDragOverComposer(true);
};
const onComposerDragLeave = (event: DragEvent<HTMLDivElement>) => {
const onComposerDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
@@ -1296,7 +1284,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
};
const onComposerDrop = (event: DragEvent<HTMLDivElement>) => {
const onComposerDrop = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
@@ -1350,7 +1338,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
[activeThread, api, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
);
const onSend = async (e: FormEvent) => {
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
@@ -1594,7 +1582,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(nextCursor);
}, []);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (composerMenuOpen && composerMenuItems.length > 0) {
if (e.key === "ArrowDown") {
e.preventDefault();
@@ -1618,7 +1606,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
void onSend(e);
}
};
const onToggleWorkGroup = useCallback((groupId: string) => {
@@ -2086,7 +2074,10 @@ const ChatHeader = memo(function ChatHeader({
<div className="flex min-w-0 flex-1 items-center gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<h2 className="min-w-0 shrink truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
<h2
className="min-w-0 shrink truncate text-sm font-medium text-foreground"
title={activeThreadTitle}
>
{activeThreadTitle}
</h2>
{activeProjectName && (
@@ -2216,7 +2207,7 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
scrollContainerRef: RefObject<HTMLDivElement | null>;
scrollContainerRef: React.RefObject<HTMLDivElement | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
+1 -4
View File
@@ -335,10 +335,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
>
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
<button
type="button"
className="shrink-0 rounded-md"
@@ -3,7 +3,8 @@ import { useMemo, type ReactNode } from "react";
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const workerPoolSize = useMemo(() => {
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
const cores =
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
}, []);
@@ -23,4 +24,3 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
</WorkerPoolContextProvider>
);
}
@@ -597,10 +597,14 @@ export default function ThreadTerminalDrawer({
);
const splitTerminalActionLabel = hasReachedTerminalLimit
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
: splitShortcutLabel
? `Split Terminal (${splitShortcutLabel})`
: "Split Terminal";
const newTerminalActionLabel = hasReachedTerminalLimit
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
: newShortcutLabel
? `New Terminal (${newShortcutLabel})`
: "New Terminal";
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
+2 -8
View File
@@ -8,10 +8,7 @@ function Collapsible({ ...props }: CollapsiblePrimitive.Root.Props) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
className,
...props
}: CollapsiblePrimitive.Trigger.Props) {
function CollapsibleTrigger({ className, ...props }: CollapsiblePrimitive.Trigger.Props) {
return (
<CollapsiblePrimitive.Trigger
className={cn("cursor-pointer", className)}
@@ -21,10 +18,7 @@ function CollapsibleTrigger({
);
}
function CollapsiblePanel({
className,
...props
}: CollapsiblePrimitive.Panel.Props) {
function CollapsiblePanel({ className, ...props }: CollapsiblePrimitive.Panel.Props) {
return (
<CollapsiblePrimitive.Panel
className={cn(
+9 -4
View File
@@ -206,9 +206,9 @@ function Sidebar({
return {
maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY,
minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH,
onResize: options.onResize,
shouldAcceptWidth: options.shouldAcceptWidth,
storageKey: options.storageKey ?? null,
...(options.onResize ? { onResize: options.onResize } : {}),
...(options.shouldAcceptWidth ? { shouldAcceptWidth: options.shouldAcceptWidth } : {}),
};
}, [collapsible, isMobile, resizable]);
const instanceContextValue = React.useMemo<SidebarInstanceContextProps>(
@@ -410,7 +410,9 @@ function SidebarRail({
return;
}
const sidebarContainer = sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-container']");
const sidebarContainer = sidebarRoot.querySelector<HTMLElement>(
"[data-slot='sidebar-container']",
);
if (!sidebarContainer) {
return;
}
@@ -464,7 +466,10 @@ function SidebarRail({
if (Math.abs(delta) > 2) {
resizeState.moved = true;
}
resizeState.pendingWidth = clampSidebarWidth(resizeState.startWidth + delta, resolvedResizable);
resizeState.pendingWidth = clampSidebarWidth(
resizeState.startWidth + delta,
resolvedResizable,
);
if (resizeState.rafId !== null) {
return;
}
+1 -3
View File
@@ -342,9 +342,7 @@ describe("cross-command precedence", () => {
describe("resolveShortcutCommand", () => {
it("returns dynamic script commands", () => {
const keybindings = compile([
{ shortcut: modShortcut("r"), command: "script.setup.run" },
]);
const keybindings = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);
assert.strictEqual(
resolveShortcutCommand(event({ key: "r", ctrlKey: true }), keybindings, {
+2 -8
View File
@@ -96,16 +96,10 @@ describe("checkpointDiffQueryOptions", () => {
expect(retry(1, new Error("Checkpoint turn count 2 exceeds current turn count 1."))).toBe(true);
expect(
retry(
11,
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
),
retry(11, new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1.")),
).toBe(true);
expect(
retry(
12,
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
),
retry(12, new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1.")),
).toBe(false);
expect(retry(2, new Error("Something else failed."))).toBe(true);
expect(retry(3, new Error("Something else failed."))).toBe(false);
+3 -3
View File
@@ -22,9 +22,9 @@ describe("resolveMarkdownFileLinkTarget", () => {
});
it("maps #L line anchors to editor line suffixes", () => {
expect(
resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7"),
).toBe("/Users/julius/project/src/main.ts:42:7");
expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(
"/Users/julius/project/src/main.ts:42:7",
);
});
it("ignores external urls", () => {
+1 -2
View File
@@ -4,8 +4,7 @@ const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
const EXTERNAL_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
const RELATIVE_FILE_PATH_PATTERN =
/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const POSIX_FILE_ROOT_PREFIXES = [
+18 -10
View File
@@ -1,7 +1,10 @@
import type { ProjectScript } from "@t3tools/contracts";
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
const MAX_SCRIPT_ID_LENGTH = 64;
import {
MAX_SCRIPT_ID_LENGTH,
SCRIPT_RUN_COMMAND_PATTERN,
type KeybindingCommand,
type ProjectScript,
} from "@t3tools/contracts";
import { Schema } from "effect";
function normalizeScriptId(value: string): string {
const cleaned = value
@@ -18,13 +21,16 @@ function normalizeScriptId(value: string): string {
return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
}
export function commandForProjectScript(scriptId: string): string {
return `script.${scriptId}.run`;
}
export const commandForProjectScript = (scriptId: string): KeybindingCommand =>
SCRIPT_RUN_COMMAND_PATTERN.makeUnsafe(`script.${scriptId}.run`);
export function projectScriptIdFromCommand(command: string): string | null {
const match = SCRIPT_RUN_COMMAND_PATTERN.exec(command.trim());
return match?.[1] ?? null;
const trimmed = command.trim();
if (!Schema.is(SCRIPT_RUN_COMMAND_PATTERN)(trimmed)) {
return null;
}
const [prefix, , suffix] = SCRIPT_RUN_COMMAND_PATTERN.parts;
return trimmed.slice(prefix.literal.length, -suffix.literal.length);
}
export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
@@ -57,7 +63,9 @@ interface ProjectScriptRuntimeEnvInput {
extraEnv?: Record<string, string>;
}
export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
export function projectScriptRuntimeEnv(
input: ProjectScriptRuntimeEnvInput,
): Record<string, string> {
const env: Record<string, string> = {
T3CODE_PROJECT_ROOT: input.project.cwd,
};
+70 -70
View File
@@ -8,111 +8,111 @@
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
import { Route as rootRouteImport } from "./routes/__root";
import { Route as ChatRouteImport } from "./routes/_chat";
import { Route as ChatIndexRouteImport } from "./routes/_chat.index";
import { Route as ChatSettingsRouteImport } from "./routes/_chat.settings";
import { Route as ChatThreadIdRouteImport } from "./routes/_chat.$threadId";
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
id: "/_chat",
getParentRoute: () => rootRouteImport,
} as any)
} as any);
const ChatIndexRoute = ChatIndexRouteImport.update({
id: '/',
path: '/',
id: "/",
path: "/",
getParentRoute: () => ChatRoute,
} as any)
} as any);
const ChatSettingsRoute = ChatSettingsRouteImport.update({
id: '/settings',
path: '/settings',
id: "/settings",
path: "/settings",
getParentRoute: () => ChatRoute,
} as any)
} as any);
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
id: '/$threadId',
path: '/$threadId',
id: "/$threadId",
path: "/$threadId",
getParentRoute: () => ChatRoute,
} as any)
} as any);
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
"/": typeof ChatIndexRoute;
"/$threadId": typeof ChatThreadIdRoute;
"/settings": typeof ChatSettingsRoute;
}
export interface FileRoutesByTo {
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
'/': typeof ChatIndexRoute
"/$threadId": typeof ChatThreadIdRoute;
"/settings": typeof ChatSettingsRoute;
"/": typeof ChatIndexRoute;
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/_chat/$threadId': typeof ChatThreadIdRoute
'/_chat/settings': typeof ChatSettingsRoute
'/_chat/': typeof ChatIndexRoute
__root__: typeof rootRouteImport;
"/_chat": typeof ChatRouteWithChildren;
"/_chat/$threadId": typeof ChatThreadIdRoute;
"/_chat/settings": typeof ChatSettingsRoute;
"/_chat/": typeof ChatIndexRoute;
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/$threadId' | '/settings'
fileRoutesByTo: FileRoutesByTo
to: '/$threadId' | '/settings' | '/'
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
fileRoutesById: FileRoutesById
fileRoutesByFullPath: FileRoutesByFullPath;
fullPaths: "/" | "/$threadId" | "/settings";
fileRoutesByTo: FileRoutesByTo;
to: "/$threadId" | "/settings" | "/";
id: "__root__" | "/_chat" | "/_chat/$threadId" | "/_chat/settings" | "/_chat/";
fileRoutesById: FileRoutesById;
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
ChatRoute: typeof ChatRouteWithChildren;
}
declare module '@tanstack/react-router' {
declare module "@tanstack/react-router" {
interface FileRoutesByPath {
'/_chat': {
id: '/_chat'
path: ''
fullPath: '/'
preLoaderRoute: typeof ChatRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/': {
id: '/_chat/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/settings': {
id: '/_chat/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof ChatSettingsRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/$threadId': {
id: '/_chat/$threadId'
path: '/$threadId'
fullPath: '/$threadId'
preLoaderRoute: typeof ChatThreadIdRouteImport
parentRoute: typeof ChatRoute
}
"/_chat": {
id: "/_chat";
path: "";
fullPath: "/";
preLoaderRoute: typeof ChatRouteImport;
parentRoute: typeof rootRouteImport;
};
"/_chat/": {
id: "/_chat/";
path: "/";
fullPath: "/";
preLoaderRoute: typeof ChatIndexRouteImport;
parentRoute: typeof ChatRoute;
};
"/_chat/settings": {
id: "/_chat/settings";
path: "/settings";
fullPath: "/settings";
preLoaderRoute: typeof ChatSettingsRouteImport;
parentRoute: typeof ChatRoute;
};
"/_chat/$threadId": {
id: "/_chat/$threadId";
path: "/$threadId";
fullPath: "/$threadId";
preLoaderRoute: typeof ChatThreadIdRouteImport;
parentRoute: typeof ChatRoute;
};
}
}
interface ChatRouteChildren {
ChatThreadIdRoute: typeof ChatThreadIdRoute
ChatSettingsRoute: typeof ChatSettingsRoute
ChatIndexRoute: typeof ChatIndexRoute
ChatThreadIdRoute: typeof ChatThreadIdRoute;
ChatSettingsRoute: typeof ChatSettingsRoute;
ChatIndexRoute: typeof ChatIndexRoute;
}
const ChatRouteChildren: ChatRouteChildren = {
ChatThreadIdRoute: ChatThreadIdRoute,
ChatSettingsRoute: ChatSettingsRoute,
ChatIndexRoute: ChatIndexRoute,
}
};
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren);
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
}
};
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
._addFileTypes<FileRouteTypes>();
+4 -5
View File
@@ -1,7 +1,4 @@
import type {
OrchestrationThreadActivity,
ProviderKind,
} from "@t3tools/contracts";
import type { OrchestrationThreadActivity, ProviderKind } from "@t3tools/contracts";
import type {
ChatMessage,
@@ -223,7 +220,9 @@ export function inferCheckpointTurnCountByTurnId(
return result;
}
export function deriveTurnDiffSummaries(_events: ReadonlyArray<OrchestrationThreadActivity>): TurnDiffSummary[] {
export function deriveTurnDiffSummaries(
_events: ReadonlyArray<OrchestrationThreadActivity>,
): TurnDiffSummary[] {
return [];
}
@@ -1 +1,481 @@
{"version":"12.17.0","source":"https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts","generatedAt":"2026-02-17T20:03:11.362Z","extensionToLanguageId":{"as":"actionscript","ada":"ada","prw":"advpl","affect":"affectscript","agda":"agda","al":"al","alloy":"alloy","ansible":"ansible","g4":"antlr","any":"anyscript","htaccess":"apacheconf","cls":"apex","apib":"apiblueprint","apl":"apl","applescript":"applescript","adoc":"asciidoc","asp":"asp","asm":"arm","astro":"astro","ats":"ats","ahk":"ahk","au3":"autoit","am":"automake","avcs":"avro","azcli":"azcli","azure-pipelines.yml":"azure-pipelines","bal":"ballerina","bat":"bat","bats":"bats","bzl":"bazel","bf":"befunge","bicep":"bicep","bib":"bibtex","biml":"biml","bin":"code-text-binary","rast":"biome_syntax_tree","blade.php":"blade","blitzbasic":"blitzbasic","bolt":"bolt","bsq":"bosque","bru":"bruno","buf.yaml":"buf","lockb":"bun.lockb","c":"c","c3":"c3","cal":"c-al","cabal":"cabal","capnp":"capnp","casc":"casc","cddl":"cddl","ceylon":"ceylon","cfc":"cfc","cfm":"cfmhtml","circom":"circom","clojure":"clojure","clojurescript":"clojurescript","yml":"manifest-yaml","cmake":"cmake","cbl":"cobol","ql":"ql","coffee":"coffeescript","cfml":"cfml","confluence":"confluence","ckbk":"cookbook","instructions.md":"instructions","cpp":"cpp","cr":"crystal","cs":"csharp","css":"css","wxss":"css","acss":"css","mcss":"css","pcss":"css","postcss":"css","nss":"css","ccss":"css","less":"css","scss":"css","sass":"css","csv":"csv","feature":"cucumber","cu":"cuda","cypher":"cypher","pyx":"cython","dal":"dal","dart":"dart","dhall":"dhall","html":"django-html","diff":"diff","d":"d","hcl":"dockerbake","dtx":"doctex","env":"dotenv","dot":"dotjs","dox":"doxygen","drawio":"drawio","drl":"drools","dtd":"dtd","dust":"dustjs","dylan":"dylan","earthfile":"earthfile","edge":"edge","eex":"eex","es":"es","ex":"elixir","elm":"elm","erb":"erb","erl":"erlang","yaml":"esphome","xlsx":"excel","falcon":"falcon","fql":"fql","f":"fortran","ftl":"ftl","fs":"fsharp","fthtml":"fthtml","gspec":"galen","gml":"gml-gms","gcode":"gcode","gen":"genstat","git":"git-commit","gleam":"gleam","gjs":"glimmer-js","glsl":"glsl","glyphs":"glyphs","gp":"gnuplot","go":"go","mod":"go.mod","work":"go.work","api":"goctl","gd":"gdscript","gradle.kts":"gradle-kotlin-dsl","gr":"grain","gql":"graphql","gv":"dot","grit":"grit","groovy":"groovy","haml":"haml","hbs":"handlebars","prg":"harbour","hs":"haskell","haxe":"haxe","helm.tpl":"helm","hjson":"hjson","hlsl":"hlsl","hosts":"hosts","http":"http","aff":"hunspell.aff","hy":"hy","hypr":"hypr","icl":"icl","imba":"imba","4gl":"4GL","ini":"ini","ink":"ink","iss":"innosetup","io":"io","janet":"janet","java":"java","js":"javascript","mjs":"javascript","cjs":"javascript","es6":"javascript","jake":"javascript","jsm":"javascript","jsx":"javascript","njs":"javascript","pac":"javascript","sjs":"javascript","ssjs":"javascript","xsjs":"javascript","xsjslib":"javascript","jekyll":"jekyll","jenkins":"jenkins","jest-snap":"jest-snapshot","jinja":"jinja","json":"json","jsonc":"jsonc","jsonl":"jsonl","jsonnet":"jsonnet","json5":"json5","jl":"julia","id":"iodine","k":"k","kv":"kivy","ks":"kos","kt":"kotlin","kusto":"kusto","tex":"latex","lark":"lark","lat":"latino","lean":"lean4","flex":"lex","ly":"lilypond","lisp":"lisp","lhs":"literate haskell","log":"log","lol":"lolcode","lsl":"lsl","lua":"lua","m4":"m4","mk":"makefile","md":"markdown","markdown":"markdown","mdown":"markdown","mkd":"markdown","marko":"marko","mat":"matlab","ms":"maxscript","mdx":"mdx","mediawiki":"mediawiki","mel":"mel","mmd":"mermaid","metal":"metal","mcfunction":"bc-mcfunction","mjml":"mjml","pq":"powerquery","mojo":"mojo","ep":"mojolicious","mongo":"mongo","mson":"mson","mv":"mv","mvt":"mvt","ne":"nearley","nginx":"nginx","nim":"nim","nimble":"nimble","nix":"nix","nsi":"nsis","nunjucks":"nunjucks","nu":"nushell","m":"objective-c","mm":"objective-cpp","ml":"ocaml","o3":"ogone","w":"abl","things":"openhab","org":"org","pas":"pascal","pddl":"pddl","plan":"plan","happenings":"happenings","pl":"perl","pl6":"perl6","pgsql":"pgsql","php":"php","php4":"php","php5":"php","php7":"php","phtml":"php","phps":"php","phpt":"php","phar":"php","aw":"php","ctp":"php","inc":"php","php3":"php","php8":"php","module":"php","theme":"php","tpl":"php","pine":"pine","txt":"plaintext","dbgasm":"platformio-debug.disassembly","ddl":"plsql","po":"po","dib":"polyglot-notebook","polymer":"polymer","pony":"pony","ps":"postscript","ps1":"powershell","prisma":"prisma","pde":"pde","pro":"prolog","rules":"prometheus","properties":"java-properties","proto":"proto3","pug":"jade","pp":"puppet","purs":"purescript","arr":"pyret","pyscript":"pyscript","py":"python","pyi":"python","pyw":"python","pyc":"python","pyd":"python","pyo":"python","pxd":"python","pxi":"python","rpy":"python","cpy":"python","ipy":"python","pyowo":"pythowo","qvs":"qlik","qml":"qml","qs":"qsharp","r":"r","rkt":"racket","raku":"raku","cshtml":"razor","raml":"raLine truncated
{
"version": "12.17.0",
"source": "https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts",
"generatedAt": "2026-02-17T20:03:11.362Z",
"extensionToLanguageId": {
"as": "actionscript",
"ada": "ada",
"prw": "advpl",
"affect": "affectscript",
"agda": "agda",
"al": "al",
"alloy": "alloy",
"ansible": "ansible",
"g4": "antlr",
"any": "anyscript",
"htaccess": "apacheconf",
"cls": "apex",
"apib": "apiblueprint",
"apl": "apl",
"applescript": "applescript",
"adoc": "asciidoc",
"asp": "asp",
"asm": "arm",
"astro": "astro",
"ats": "ats",
"ahk": "ahk",
"au3": "autoit",
"am": "automake",
"avcs": "avro",
"azcli": "azcli",
"azure-pipelines.yml": "azure-pipelines",
"bal": "ballerina",
"bat": "bat",
"bats": "bats",
"bzl": "bazel",
"bf": "befunge",
"bicep": "bicep",
"bib": "bibtex",
"biml": "biml",
"bin": "code-text-binary",
"rast": "biome_syntax_tree",
"blade.php": "blade",
"blitzbasic": "blitzbasic",
"bolt": "bolt",
"bsq": "bosque",
"bru": "bruno",
"buf.yaml": "buf",
"lockb": "bun.lockb",
"c": "c",
"c3": "c3",
"cal": "c-al",
"cabal": "cabal",
"capnp": "capnp",
"casc": "casc",
"cddl": "cddl",
"ceylon": "ceylon",
"cfc": "cfc",
"cfm": "cfmhtml",
"circom": "circom",
"clojure": "clojure",
"clojurescript": "clojurescript",
"yml": "manifest-yaml",
"cmake": "cmake",
"cbl": "cobol",
"ql": "ql",
"coffee": "coffeescript",
"cfml": "cfml",
"confluence": "confluence",
"ckbk": "cookbook",
"instructions.md": "instructions",
"cpp": "cpp",
"cr": "crystal",
"cs": "csharp",
"css": "css",
"wxss": "css",
"acss": "css",
"mcss": "css",
"pcss": "css",
"postcss": "css",
"nss": "css",
"ccss": "css",
"less": "css",
"scss": "css",
"sass": "css",
"csv": "csv",
"feature": "cucumber",
"cu": "cuda",
"cypher": "cypher",
"pyx": "cython",
"dal": "dal",
"dart": "dart",
"dhall": "dhall",
"html": "django-html",
"diff": "diff",
"d": "d",
"hcl": "dockerbake",
"dtx": "doctex",
"env": "dotenv",
"dot": "dotjs",
"dox": "doxygen",
"drawio": "drawio",
"drl": "drools",
"dtd": "dtd",
"dust": "dustjs",
"dylan": "dylan",
"earthfile": "earthfile",
"edge": "edge",
"eex": "eex",
"es": "es",
"ex": "elixir",
"elm": "elm",
"erb": "erb",
"erl": "erlang",
"yaml": "esphome",
"xlsx": "excel",
"falcon": "falcon",
"fql": "fql",
"f": "fortran",
"ftl": "ftl",
"fs": "fsharp",
"fthtml": "fthtml",
"gspec": "galen",
"gml": "gml-gms",
"gcode": "gcode",
"gen": "genstat",
"git": "git-commit",
"gleam": "gleam",
"gjs": "glimmer-js",
"glsl": "glsl",
"glyphs": "glyphs",
"gp": "gnuplot",
"go": "go",
"mod": "go.mod",
"work": "go.work",
"api": "goctl",
"gd": "gdscript",
"gradle.kts": "gradle-kotlin-dsl",
"gr": "grain",
"gql": "graphql",
"gv": "dot",
"grit": "grit",
"groovy": "groovy",
"haml": "haml",
"hbs": "handlebars",
"prg": "harbour",
"hs": "haskell",
"haxe": "haxe",
"helm.tpl": "helm",
"hjson": "hjson",
"hlsl": "hlsl",
"hosts": "hosts",
"http": "http",
"aff": "hunspell.aff",
"hy": "hy",
"hypr": "hypr",
"icl": "icl",
"imba": "imba",
"4gl": "4GL",
"ini": "ini",
"ink": "ink",
"iss": "innosetup",
"io": "io",
"janet": "janet",
"java": "java",
"js": "javascript",
"mjs": "javascript",
"cjs": "javascript",
"es6": "javascript",
"jake": "javascript",
"jsm": "javascript",
"jsx": "javascript",
"njs": "javascript",
"pac": "javascript",
"sjs": "javascript",
"ssjs": "javascript",
"xsjs": "javascript",
"xsjslib": "javascript",
"jekyll": "jekyll",
"jenkins": "jenkins",
"jest-snap": "jest-snapshot",
"jinja": "jinja",
"json": "json",
"jsonc": "jsonc",
"jsonl": "jsonl",
"jsonnet": "jsonnet",
"json5": "json5",
"jl": "julia",
"id": "iodine",
"k": "k",
"kv": "kivy",
"ks": "kos",
"kt": "kotlin",
"kusto": "kusto",
"tex": "latex",
"lark": "lark",
"lat": "latino",
"lean": "lean4",
"flex": "lex",
"ly": "lilypond",
"lisp": "lisp",
"lhs": "literate haskell",
"log": "log",
"lol": "lolcode",
"lsl": "lsl",
"lua": "lua",
"m4": "m4",
"mk": "makefile",
"md": "markdown",
"markdown": "markdown",
"mdown": "markdown",
"mkd": "markdown",
"marko": "marko",
"mat": "matlab",
"ms": "maxscript",
"mdx": "mdx",
"mediawiki": "mediawiki",
"mel": "mel",
"mmd": "mermaid",
"metal": "metal",
"mcfunction": "bc-mcfunction",
"mjml": "mjml",
"pq": "powerquery",
"mojo": "mojo",
"ep": "mojolicious",
"mongo": "mongo",
"mson": "mson",
"mv": "mv",
"mvt": "mvt",
"ne": "nearley",
"nginx": "nginx",
"nim": "nim",
"nimble": "nimble",
"nix": "nix",
"nsi": "nsis",
"nunjucks": "nunjucks",
"nu": "nushell",
"m": "objective-c",
"mm": "objective-cpp",
"ml": "ocaml",
"o3": "ogone",
"w": "abl",
"things": "openhab",
"org": "org",
"pas": "pascal",
"pddl": "pddl",
"plan": "plan",
"happenings": "happenings",
"pl": "perl",
"pl6": "perl6",
"pgsql": "pgsql",
"php": "php",
"php4": "php",
"php5": "php",
"php7": "php",
"phtml": "php",
"phps": "php",
"phpt": "php",
"phar": "php",
"aw": "php",
"ctp": "php",
"inc": "php",
"php3": "php",
"php8": "php",
"module": "php",
"theme": "php",
"tpl": "php",
"pine": "pine",
"txt": "plaintext",
"dbgasm": "platformio-debug.disassembly",
"ddl": "plsql",
"po": "po",
"dib": "polyglot-notebook",
"polymer": "polymer",
"pony": "pony",
"ps": "postscript",
"ps1": "powershell",
"prisma": "prisma",
"pde": "pde",
"pro": "prolog",
"rules": "prometheus",
"properties": "java-properties",
"proto": "proto3",
"pug": "jade",
"pp": "puppet",
"purs": "purescript",
"arr": "pyret",
"pyscript": "pyscript",
"py": "python",
"pyi": "python",
"pyw": "python",
"pyc": "python",
"pyd": "python",
"pyo": "python",
"pxd": "python",
"pxi": "python",
"rpy": "python",
"cpy": "python",
"ipy": "python",
"pyowo": "pythowo",
"qvs": "qlik",
"qml": "qml",
"qs": "qsharp",
"r": "r",
"rkt": "racket",
"raku": "raku",
"cshtml": "razor",
"raml": "raml",
"re": "reason",
"red": "red",
"res": "rescript",
"rst": "restructuredtext",
"rex": "rexx",
"tag": "riot",
"ripple": "ripple",
"rmd": "rmd",
"rnc": "rnc",
"robot": "robot",
"rb": "ruby",
"rbw": "ruby",
"rake": "ruby",
"gemspec": "ruby",
"ru": "ruby",
"rjs": "ruby",
"rxml": "ruby",
"rsel": "ruby",
"builder": "ruby",
"jbuilder": "ruby",
"rabl": "ruby",
"prawn": "ruby",
"thor": "ruby",
"rs": "rust",
"sl": "s-lang",
"san": "san",
"sas": "SAS",
"sbt": "sbt",
"scad": "scad",
"scala": "scala",
"sce": "scilab",
"sdl": "sdl",
"code-search": "search-result",
"shader": "shaderlab",
"sh": "shellscript",
"bash": "shellscript",
"zsh": "shellscript",
"ksh": "shellscript",
"fish": "shellscript",
"slang": "slang",
"ice": "slice",
"slim": "slim",
"slint": "slint",
"sln": "sln",
"ss": "silverstripe",
"sn": "sino",
"eskip": "eskip",
"smk": "snakemake",
"code-snippets": "snippets",
"snort": "snort",
"sol": "solidity",
"rq": "sparql",
"sqf": "sqf",
"sql": "sql",
"nut": "squirrel",
"stan": "stan",
"bazel": "starlark",
"do": "stata",
"stencil": "stencil",
"html.stencil": "stencil-html",
"st.css": "stylable",
"styled": "source.css.styled",
"styl": "stylus",
"svelte": "svelte",
"svg": "svg",
"swagger": "Swagger",
"swift": "swift",
"swig": "swig",
"link": "systemd-conf",
"sv": "systemverilog",
"tt": "t4",
"teal": "teal",
"templ": "templ",
"tt3": "tt",
"tera": "tera",
"tf": "terraform",
"sty": "tex",
"textile": "textile",
"json-tmlanguage": "json-tmlanguage",
"yaml-tmlanguage": "yaml-tmlanguage",
"toit": "toit",
"toml": "toml",
"toon": "toon",
"ttcn3": "ttcn",
"tuc": "tuc",
"twig": "twig",
"ts": "typescript",
"mts": "typescript",
"cts": "typescript",
"tsx": "typescriptreact",
"typoscript": "typoscript",
"ua": "uiua",
"u": "unison",
"vb": "vb",
"wsf": "vbscript",
"vm": "velocity",
"vto": "vento",
"v": "verilog",
"vhdl": "vhdl",
"vim": "viml",
"vitest-snap": "vitest-snapshot",
"volt": "volt",
"vroom": "vroom",
"vue": "vue",
"vue2": "vue",
"vue3": "vue",
"vues": "vue",
"vuex": "vue",
"vuerc": "vue",
"vy": "vyper",
"wai": "wai",
"wasm": "wasm",
"wat": "wasm",
"wast": "wasm",
"wsm": "wasm",
"wast.js": "wasm",
"wit": "wasm",
"witx": "wasm",
"wy": "wenyan",
"wgsl": "wgsl",
"wt": "wikitext",
"wl": "wolfram",
"wurst": "wurstlang",
"xcompose": "xcompose",
"xmake.lua": "xmake",
"xml": "xml",
"xquery": "xquery",
"xsl": "xsl",
"bison": "yacc",
"yang": "yang",
"zig": "zig",
"zip": "zip"
},
"fileNameToLanguageId": {
"browserslist": "browserslist",
".browserslistrc": "browserslist",
"caddyfile": "caddyfile",
"cmakelists.txt": "cmake",
"cmakecache.txt": "cmake-cache",
"docker-compose.yml": "dockercompose",
"docker-compose.yaml": "dockercompose",
"compose.yaml": "dockercompose",
"compose.yml": "dockercompose",
"dockerfile": "dockerfile",
"dockerfile.dev": "dockerfile",
"dockerfile.prod": "dockerfile",
"dockerfile.test": "dockerfile",
".editorconfig": "editorconfig",
"justfile": "just",
"meson.build": "meson",
".php-version": "php",
"artisan": "php",
"requirements.txt": "pip-requirements",
"requirements-dev.txt": "pip-requirements",
"requirements-test.txt": "pip-requirements",
"requirements-prod.txt": "pip-requirements",
"setup.py": "python",
"setup.cfg": "python",
".python-version": "python",
"pipfile": "python",
"pipfile.lock": "python",
"robots.txt": "robots-txt",
"config.ru": "ruby",
".bashrc": "shellscript",
".zshrc": "shellscript",
".profile": "shellscript",
".bash_profile": "shellscript",
".bash_aliases": "shellscript",
".zprofile": "shellscript",
"tiltfile": "tiltfile",
".vue-cli-rc": "vue",
"yarn.lock": "yarnlock"
}
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -100,6 +100,7 @@
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/vitest": "4.0.0-beta.10",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
},
+1
View File
@@ -28,6 +28,7 @@
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/vitest": "4.0.0-beta.10",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
+65 -43
View File
@@ -1,5 +1,6 @@
import { Schema } from "effect";
import { assert, describe, it } from "vitest";
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import {
KeybindingsConfig,
@@ -8,60 +9,75 @@ import {
ResolvedKeybindingsConfig,
} from "./keybindings";
const decode = <S extends Schema.Top>(schema: S, input: unknown): Schema.Schema.Type<S> =>
Schema.decodeUnknownSync(schema as never)(input) as Schema.Schema.Type<S>;
const decode = <S extends Schema.Top>(
schema: S,
input: unknown,
): Effect.Effect<Schema.Schema.Type<S>, Schema.SchemaError, never> =>
Schema.decodeUnknownEffect(schema as never)(input) as Effect.Effect<
Schema.Schema.Type<S>,
Schema.SchemaError,
never
>;
const decodeResolvedRuleStrict = (input: unknown) =>
Schema.decodeUnknownSync(ResolvedKeybindingRule as never)(input);
const decodeResolvedRule = Schema.decodeUnknownEffect(ResolvedKeybindingRule as never);
describe("keybindings contracts", () => {
it("parses keybinding rules", () => {
const parsed = decode(KeybindingRule, {
it.effect("parses keybinding rules", () =>
Effect.gen(function* () {
const parsed = yield* decode(KeybindingRule, {
key: "mod+j",
command: "terminal.toggle",
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedClose = decode(KeybindingRule, {
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "terminal.close",
});
assert.strictEqual(parsedClose.command, "terminal.close");
const parsedLocal = decode(KeybindingRule, {
const parsedLocal = yield* decode(KeybindingRule, {
key: "mod+shift+n",
command: "chat.newLocal",
});
assert.strictEqual(parsedLocal.command, "chat.newLocal");
});
}),
);
it("rejects invalid command values", () => {
assert.throws(() =>
it.effect("rejects invalid command values", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decode(KeybindingRule, {
key: "mod+j",
command: "script.Test.run",
}),
);
});
assert.strictEqual(result._tag, "Failure");
}),
);
it("accepts dynamic script run commands", () => {
const parsed = decode(KeybindingRule, {
it.effect("accepts dynamic script run commands", () =>
Effect.gen(function* () {
const parsed = yield* decode(KeybindingRule, {
key: "mod+r",
command: "script.setup.run",
});
assert.strictEqual(parsed.command, "script.setup.run");
});
}),
);
it("parses keybindings array payload", () => {
const parsed = decode(KeybindingsConfig, [
it.effect("parses keybindings array payload", () =>
Effect.gen(function* () {
const parsed = yield* decode(KeybindingsConfig, [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
]);
assert.lengthOf(parsed, 2);
});
}),
);
it("parses resolved keybinding rules", () => {
const parsed = decode(ResolvedKeybindingRule, {
it.effect("parses resolved keybinding rules", () =>
Effect.gen(function* () {
const parsed = yield* decode(ResolvedKeybindingRule, {
command: "terminal.split",
shortcut: {
key: "d",
@@ -81,10 +97,12 @@ describe("keybindings contracts", () => {
},
});
assert.strictEqual(parsed.shortcut.key, "d");
});
}),
);
it("parses resolved keybindings arrays", () => {
const parsed = decode(ResolvedKeybindingsConfig, [
it.effect("parses resolved keybindings arrays", () =>
Effect.gen(function* () {
const parsed = yield* decode(ResolvedKeybindingsConfig, [
{
command: "terminal.toggle",
shortcut: {
@@ -98,22 +116,26 @@ describe("keybindings contracts", () => {
},
]);
assert.lengthOf(parsed, 1);
});
}),
);
it("rejects unknown fields in resolved keybinding rules", () => {
assert.throws(() =>
decodeResolvedRuleStrict({
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
key: "mod+j",
}),
);
});
});
it.effect("drops unknown fields in resolved keybinding rules", () =>
decodeResolvedRule({
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
key: "mod+j",
}).pipe(
Effect.map((parsed) => {
const view = parsed as Record<string, unknown>;
assert.strictEqual("key" in view, false);
assert.strictEqual(view.command, "terminal.toggle");
}),
),
);
+31 -9
View File
@@ -1,5 +1,13 @@
import { Schema } from "effect";
export const MAX_KEYBINDING_COMMAND_LENGTH = 96;
export const MAX_KEYBINDING_VALUE_LENGTH = 64;
export const MAX_KEYBINDING_WHEN_LENGTH = 256;
export const MAX_WHEN_EXPRESSION_DEPTH = 64;
export const MAX_SCRIPT_ID_LENGTH = 24;
export const MAX_SCRIPT_RUN_COMMAND_LENGTH = 96;
export const MAX_KEYBINDINGS_COUNT = 256;
export const STATIC_KEYBINDING_COMMANDS = [
"terminal.toggle",
"terminal.split",
@@ -10,19 +18,31 @@ export const STATIC_KEYBINDING_COMMANDS = [
"editor.openFavorite",
] as const;
export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
Schema.Literal("script."),
Schema.NonEmptyString.check(
Schema.isMaxLength(MAX_SCRIPT_ID_LENGTH),
Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
),
Schema.Literal(".run"),
]);
export const KeybindingCommand = Schema.Union([
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
Schema.NonEmptyString.check(
Schema.isMaxLength(96),
Schema.isPattern(/^script\.[a-z0-9][a-z0-9-]*\.run$/),
),
SCRIPT_RUN_COMMAND_PATTERN,
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;
export const KeybindingValue = Schema.Trim.check(Schema.isMinLength(1), Schema.isMaxLength(64));
export const KeybindingValue = Schema.Trim.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
export type KeybindingValue = typeof KeybindingValue.Type;
export const KeybindingWhen = Schema.Trim.check(Schema.isMinLength(1), Schema.isMaxLength(256));
export const KeybindingWhen = Schema.Trim.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
export type KeybindingWhen = typeof KeybindingWhen.Type;
export class KeybindingRule extends Schema.Class<KeybindingRule>("KeybindingRule")({
key: KeybindingValue,
@@ -30,7 +50,9 @@ export class KeybindingRule extends Schema.Class<KeybindingRule>("KeybindingRule
when: Schema.optional(KeybindingWhen),
}) {}
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(Schema.isMaxLength(256));
export const KeybindingsConfig = Schema.Array(KeybindingRule).check(
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export type KeybindingsConfig = typeof KeybindingsConfig.Type;
export class KeybindingShortcut extends Schema.Class<KeybindingShortcut>("KeybindingShortcut")({
@@ -76,10 +98,10 @@ export class ResolvedKeybindingRule extends Schema.Class<ResolvedKeybindingRule>
shortcut: KeybindingShortcut,
whenAst: Schema.optional(KeybindingWhenNode),
},
{ parseOptions: { onExcessProperty: "error" } },
{ parseOptions: { onExcessProperty: "ignore" } },
) {}
export const ResolvedKeybindingsConfig = Schema.Array(ResolvedKeybindingRule).check(
Schema.isMaxLength(256),
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
);
export type ResolvedKeybindingsConfig = typeof ResolvedKeybindingsConfig.Type;
+5 -7
View File
@@ -19,10 +19,7 @@ import {
const RuntimeThreadIdSchema = Schema.Union([ThreadId, ProviderThreadId]);
const RuntimeTurnIdSchema = Schema.Union([TurnId, ProviderTurnId]);
export const ProviderRuntimeToolKind = Schema.Union([
ProviderRequestKind,
Schema.Literal("other"),
]);
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
export const ProviderRuntimeTurnStatus = Schema.Literals([
@@ -157,7 +154,8 @@ export const ProviderRuntimeApprovalRequestedEvent = Schema.Struct({
requestKind: ProviderRequestKind,
detail: Schema.optional(Schema.String),
});
export type ProviderRuntimeApprovalRequestedEvent = typeof ProviderRuntimeApprovalRequestedEvent.Type;
export type ProviderRuntimeApprovalRequestedEvent =
typeof ProviderRuntimeApprovalRequestedEvent.Type;
export const ProviderRuntimeApprovalResolvedEvent = Schema.Struct({
type: Schema.Literal("approval.resolved"),
@@ -185,7 +183,8 @@ export const ProviderRuntimeCheckpointCapturedEvent = Schema.Struct({
turnCount: NonNegativeInt,
status: Schema.optional(ProviderRuntimeTurnStatus),
});
export type ProviderRuntimeCheckpointCapturedEvent = typeof ProviderRuntimeCheckpointCapturedEvent.Type;
export type ProviderRuntimeCheckpointCapturedEvent =
typeof ProviderRuntimeCheckpointCapturedEvent.Type;
export const ProviderRuntimeErrorEvent = Schema.Struct({
type: Schema.Literal("runtime.error"),
@@ -216,4 +215,3 @@ export const ProviderRuntimeEvent = Schema.Union([
ProviderRuntimeErrorEvent,
]);
export type ProviderRuntimeEvent = typeof ProviderRuntimeEvent.Type;
+3 -4
View File
@@ -10,9 +10,9 @@ const TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(5)).ch
Schema.isLessThanOrEqualTo(200),
);
const TerminalIdSchema = Schema.Trim.check(Schema.isNonEmpty()).check(Schema.isMaxLength(128));
const TerminalEnvKeySchema = Schema.String.check(Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/)).check(
Schema.isMaxLength(128),
);
const TerminalEnvKeySchema = Schema.String.check(
Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),
).check(Schema.isMaxLength(128));
const TerminalEnvValueSchema = Schema.String.check(Schema.isMaxLength(8_192));
const TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSchema).check(
Schema.makeFilter<Record<string, string>>((env) => {
@@ -152,4 +152,3 @@ export const TerminalEvent = Schema.Union([
TerminalActivityEvent,
]);
export type TerminalEvent = typeof TerminalEvent.Type;
-1
View File
@@ -120,7 +120,6 @@ export const WebSocketRequest = Schema.Struct({
});
export type WebSocketRequest = typeof WebSocketRequest.Type;
export class WebSocketResponse extends Schema.Class<WebSocketResponse>("WebSocketResponse")({
id: Schema.String,
result: Schema.optional(Schema.Unknown),
+8 -1
View File
@@ -129,7 +129,14 @@ async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
for (const size of iconSizes) {
await run(
"sips",
["-z", String(size), String(size), sourcePng, "--out", path.join(iconsetDir, `icon_${size}x${size}.png`)],
[
"-z",
String(size),
String(size),
sourcePng,
"--out",
path.join(iconsetDir, `icon_${size}x${size}.png`),
],
{ stdio: "ignore" },
);
const retinaSize = size * 2;