Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d8abd6312 | ||
|
|
ad5b3a6a29 | ||
|
|
0e38870647 | ||
|
|
9b604bcae1 | ||
|
|
35721d9a08 | ||
|
|
f4c9418d40 | ||
|
|
02dd47ea31 | ||
|
|
aca0fa4e5b | ||
|
|
0576820755 | ||
|
|
cb3211c8f3 | ||
|
|
826965978b | ||
|
|
623e471a02 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -19,7 +19,6 @@
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
@@ -30,7 +29,7 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
|
||||
@@ -86,10 +86,13 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -163,10 +166,13 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -208,10 +214,13 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
|
||||
@@ -17,7 +17,6 @@ import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
@@ -316,8 +315,8 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
|
||||
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces existing custom keybinding for the same command", () =>
|
||||
it.effect("appends additional custom keybindings for the same command", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
@@ -368,6 +368,55 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+alt+r",
|
||||
command: "script.run-tests.run",
|
||||
replace: { key: "mod+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" },
|
||||
{ key: "mod+alt+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("removes only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.removeKeybindingRule({
|
||||
key: "mod+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" }]);
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
type ServerRemoveKeybindingInput,
|
||||
type ServerUpsertKeybindingInput,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -124,6 +126,25 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
|
||||
return leftContext === rightContext;
|
||||
}
|
||||
|
||||
function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
|
||||
if (!input.replace) return null;
|
||||
return input.replace.when === undefined
|
||||
? { key: input.replace.key, command: input.replace.command }
|
||||
: { key: input.replace.key, command: input.replace.command, when: input.replace.when };
|
||||
}
|
||||
|
||||
function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
||||
const modifiers: string[] = [];
|
||||
if (shortcut.modKey) modifiers.push("mod");
|
||||
@@ -259,7 +280,14 @@ export interface KeybindingsShape {
|
||||
* oldest entries when needed.
|
||||
*/
|
||||
readonly upsertKeybindingRule: (
|
||||
rule: KeybindingRule,
|
||||
input: ServerUpsertKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Remove a single persisted keybinding rule by exact key/command/when match.
|
||||
*/
|
||||
readonly removeKeybindingRule: (
|
||||
input: ServerRemoveKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
}
|
||||
|
||||
@@ -616,12 +644,19 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
upsertKeybindingRule: (rule) =>
|
||||
upsertKeybindingRule: (input) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const rule = keybindingRuleFromUpsertInput(input);
|
||||
const replaceTarget = replaceTargetFromUpsertInput(input);
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||
...customConfig.filter((entry) => {
|
||||
if (replaceTarget) {
|
||||
return !isSameKeybindingRule(entry, replaceTarget);
|
||||
}
|
||||
return !isSameKeybindingRule(entry, rule);
|
||||
}),
|
||||
rule,
|
||||
];
|
||||
const cappedConfig =
|
||||
@@ -649,6 +684,27 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
removeKeybindingRule: (input) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const target = keybindingRuleFromRemoveInput(input);
|
||||
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
|
||||
yield* writeConfigAtomically(nextConfig);
|
||||
const nextResolved = mergeWithDefaultKeybindings(
|
||||
compileResolvedKeybindingsConfig(nextConfig),
|
||||
);
|
||||
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
yield* emitChange({
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
} satisfies KeybindingsShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
@@ -132,7 +133,14 @@ function createProviderServiceHarness(
|
||||
}
|
||||
|
||||
async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
readModel: () => Promise<{
|
||||
readonly threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly latestTurn: { readonly turnId: string } | null;
|
||||
readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string }>;
|
||||
}>;
|
||||
}>,
|
||||
predicate: (thread: {
|
||||
latestTurn: { turnId: string } | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
@@ -146,8 +154,8 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -231,7 +239,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -279,6 +287,10 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-reactor-test-",
|
||||
@@ -304,6 +316,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
@@ -322,6 +335,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
||||
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
@@ -387,6 +401,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
provider,
|
||||
cwd,
|
||||
drain,
|
||||
@@ -443,7 +458,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -541,7 +556,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
@@ -557,7 +572,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -614,7 +629,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
@@ -659,7 +674,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 &&
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||
@@ -794,7 +809,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
@@ -923,7 +938,10 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread.checkpoints).toHaveLength(1);
|
||||
@@ -1105,7 +1123,7 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
|
||||
);
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
@@ -66,6 +67,7 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
@@ -124,29 +126,26 @@ const make = Effect.gen(function* () {
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
return session?.cwd
|
||||
? Option.some({ threadId: session.threadId, cwd: session.cwd })
|
||||
: Option.none();
|
||||
});
|
||||
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
};
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find((session) => session.threadId === thread.id);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
|
||||
projectId: ProjectId,
|
||||
) {
|
||||
const project = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
return project ? [project] : [];
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
@@ -331,8 +330,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
@@ -353,10 +351,11 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -407,8 +406,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
if (!thread) {
|
||||
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
||||
threadId,
|
||||
@@ -429,10 +427,11 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -458,16 +457,16 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -540,16 +539,16 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const threadId = event.payload.threadId;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -587,8 +586,7 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
|
||||
const thread = yield* resolveThreadDetail(event.payload.threadId);
|
||||
if (!thread) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -42,9 +43,13 @@ async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
const orchestrationLayer = Layer.mergeAll(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
),
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
).pipe(
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
@@ -54,8 +59,10 @@ async function createOrchestrationSystem() {
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
return {
|
||||
engine,
|
||||
readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
|
||||
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
||||
dispose: () => runtime.dispose(),
|
||||
};
|
||||
@@ -77,15 +84,18 @@ const hasMetricSnapshot = (
|
||||
);
|
||||
|
||||
describe("OrchestrationEngine", () => {
|
||||
it("bootstraps the in-memory read model from persisted projections", async () => {
|
||||
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
|
||||
append: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.append",
|
||||
detail: "append should not be called during bootstrap",
|
||||
}),
|
||||
),
|
||||
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
|
||||
let nextSequence = 8;
|
||||
const eventStore: OrchestrationEventStoreShape = {
|
||||
append: (event) =>
|
||||
Effect.sync(() => {
|
||||
const savedEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} as OrchestrationEvent;
|
||||
nextSequence += 1;
|
||||
return savedEvent;
|
||||
}),
|
||||
readFromSequence: () => Stream.empty,
|
||||
readAll: () =>
|
||||
Stream.fail(
|
||||
@@ -140,11 +150,27 @@ describe("OrchestrationEngine", () => {
|
||||
},
|
||||
],
|
||||
};
|
||||
const commandReadModel = {
|
||||
...projectionSnapshot,
|
||||
threads: projectionSnapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
})),
|
||||
};
|
||||
let fullSnapshotReadCount = 0;
|
||||
|
||||
const layer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getCommandReadModel: () => Effect.succeed(commandReadModel),
|
||||
getSnapshot: () =>
|
||||
Effect.sync(() => {
|
||||
fullSnapshotReadCount += 1;
|
||||
return projectionSnapshot;
|
||||
}),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
@@ -152,6 +178,8 @@ describe("OrchestrationEngine", () => {
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -167,7 +195,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: () => Effect.void,
|
||||
} satisfies OrchestrationProjectionPipelineShape),
|
||||
),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -175,18 +203,22 @@ describe("OrchestrationEngine", () => {
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const readModel = await runtime.runPromise(engine.getReadModel());
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-bootstrap-thread-update"),
|
||||
threadId: ThreadId.make("thread-bootstrap"),
|
||||
title: "Updated Bootstrap Thread",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(readModel.snapshotSequence).toBe(7);
|
||||
expect(readModel.projects).toHaveLength(1);
|
||||
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
|
||||
expect(readModel.threads).toHaveLength(1);
|
||||
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
|
||||
expect(result.sequence).toBe(8);
|
||||
expect(fullSnapshotReadCount).toBe(0);
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("returns deterministic read models for repeated reads", async () => {
|
||||
it("persists deterministic read models for repeated snapshot reads", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
@@ -240,8 +272,8 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const readModelA = await system.run(engine.getReadModel());
|
||||
const readModelB = await system.run(engine.getReadModel());
|
||||
const readModelA = await system.readModel();
|
||||
const readModelB = await system.readModel();
|
||||
expect(readModelB).toEqual(readModelA);
|
||||
await system.dispose();
|
||||
});
|
||||
@@ -292,9 +324,8 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
await system.run(
|
||||
@@ -305,9 +336,8 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
).toBeNull();
|
||||
|
||||
await system.dispose();
|
||||
@@ -573,7 +603,7 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = (await system.run(engine.getReadModel())).threads.find(
|
||||
const thread = (await system.readModel()).threads.find(
|
||||
(entry) => entry.id === "thread-turn-diff",
|
||||
);
|
||||
expect(thread?.checkpoints).toEqual([
|
||||
@@ -701,7 +731,15 @@ describe("OrchestrationEngine", () => {
|
||||
);
|
||||
|
||||
expect(result.sequence).toBe(2);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
const eventsAfterRetry = await runtime.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -801,7 +839,6 @@ describe("OrchestrationEngine", () => {
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
|
||||
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
||||
expect(retryResult.sequence).toBe(4);
|
||||
@@ -824,7 +861,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("reconciles in-memory state when append persists but projection fails", async () => {
|
||||
it("reconciles command state when append persists but projection fails", async () => {
|
||||
type StoredEvent =
|
||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||
? A
|
||||
@@ -856,7 +893,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||
event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
@@ -919,20 +956,22 @@ describe("OrchestrationEngine", () => {
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-fail"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("projection failed");
|
||||
|
||||
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
|
||||
const updatedThread = readModelAfterFailure.threads.find(
|
||||
(thread) => thread.id === "thread-sync",
|
||||
);
|
||||
expect(readModelAfterFailure.snapshotSequence).toBe(3);
|
||||
expect(updatedThread?.title).toBe("sync-after-failed-projection");
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-retry"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already archived");
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
OrchestrationCommandInvariantError,
|
||||
OrchestrationCommandPreviouslyRejectedError,
|
||||
type OrchestrationDispatchError,
|
||||
type OrchestrationProjectorDecodeError,
|
||||
} from "../Errors.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
@@ -77,13 +78,25 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||
let commandReadModel = createEmptyReadModel(new Date().toISOString());
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const projectEventsOntoReadModel = (
|
||||
baseReadModel: OrchestrationReadModel,
|
||||
events: ReadonlyArray<OrchestrationEvent>,
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
Effect.gen(function* () {
|
||||
let nextReadModel = baseReadModel;
|
||||
for (const event of events) {
|
||||
nextReadModel = yield* projectEvent(nextReadModel, event);
|
||||
}
|
||||
return nextReadModel;
|
||||
});
|
||||
|
||||
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
|
||||
const dispatchStartSequence = readModel.snapshotSequence;
|
||||
const dispatchStartSequence = commandReadModel.snapshotSequence;
|
||||
const processingStartedAtMs = Date.now();
|
||||
const aggregateRef = commandToAggregateRef(envelope.command);
|
||||
const baseMetricAttributes = {
|
||||
@@ -98,11 +111,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
let nextReadModel = readModel;
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
|
||||
}
|
||||
readModel = nextReadModel;
|
||||
commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
|
||||
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||
@@ -135,18 +144,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
const eventBase = yield* decideOrchestrationCommand({
|
||||
command: envelope.command,
|
||||
readModel,
|
||||
readModel: commandReadModel,
|
||||
});
|
||||
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
||||
const committedCommand = yield* sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const committedEvents: OrchestrationEvent[] = [];
|
||||
let nextReadModel = readModel;
|
||||
let nextCommandReadModel = commandReadModel;
|
||||
|
||||
for (const nextEvent of eventBases) {
|
||||
const savedEvent = yield* eventStore.append(nextEvent);
|
||||
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
|
||||
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
|
||||
yield* projectionPipeline.projectEvent(savedEvent);
|
||||
committedEvents.push(savedEvent);
|
||||
}
|
||||
@@ -172,7 +181,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
return {
|
||||
committedEvents,
|
||||
lastSequence: lastSavedEvent.sequence,
|
||||
nextReadModel,
|
||||
nextCommandReadModel,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
@@ -184,7 +193,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
readModel = committedCommand.nextReadModel;
|
||||
commandReadModel = committedCommand.nextCommandReadModel;
|
||||
for (const [index, event] of committedCommand.committedEvents.entries()) {
|
||||
yield* PubSub.publish(eventPubSub, event);
|
||||
if (index === 0) {
|
||||
@@ -242,7 +251,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
).pipe(
|
||||
Effect.annotateLogs({
|
||||
commandId: envelope.command.commandId,
|
||||
snapshotSequence: readModel.snapshotSequence,
|
||||
snapshotSequence: commandReadModel.snapshotSequence,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -255,7 +264,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
aggregateKind: aggregateRef.aggregateKind,
|
||||
aggregateId: aggregateRef.aggregateId,
|
||||
acceptedAt: new Date().toISOString(),
|
||||
resultSequence: readModel.snapshotSequence,
|
||||
resultSequence: commandReadModel.snapshotSequence,
|
||||
status: "rejected",
|
||||
error: error.message,
|
||||
})
|
||||
@@ -270,17 +279,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
|
||||
Effect.sync((): OrchestrationReadModel => readModel);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
|
||||
@@ -292,7 +298,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getReadModel,
|
||||
readEvents,
|
||||
dispatch,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
|
||||
@@ -739,9 +739,31 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const retainedTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
let latestTurnId: ProjectionTurn["turnId"] = null;
|
||||
let latestCheckpointTurnCount = -1;
|
||||
for (let index = 0; index < retainedTurns.length; index += 1) {
|
||||
const turn = retainedTurns[index];
|
||||
if (
|
||||
!turn ||
|
||||
turn.turnId === null ||
|
||||
turn.checkpointTurnCount === null ||
|
||||
turn.checkpointTurnCount > event.payload.turnCount
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
|
||||
latestCheckpointTurnCount = turn.checkpointTurnCount;
|
||||
latestTurnId = turn.turnId;
|
||||
}
|
||||
}
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestTurnId: null,
|
||||
latestTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
@@ -1029,4 +1030,378 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-03T00:00:00.000Z',
|
||||
'2026-04-03T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-03T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-03T00:00:02.000Z',
|
||||
'2026-04-03T00:00:03.000Z',
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-03T00:00:30.000Z',
|
||||
'2026-04-03T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-03T00:00:05.000Z',
|
||||
'2026-04-03T00:00:06.000Z',
|
||||
'2026-04-03T00:00:20.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z')
|
||||
`;
|
||||
|
||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running");
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running");
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps deleted project and thread tombstones in the command read model", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-deleted',
|
||||
'Deleted Project',
|
||||
'/tmp/deleted-project',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-05T00:00:00.000Z',
|
||||
'2026-04-05T00:00:01.000Z',
|
||||
'2026-04-05T00:00:02.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-deleted',
|
||||
'project-deleted',
|
||||
'Deleted Thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-deleted',
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-05T00:00:03.000Z',
|
||||
'2026-04-05T00:00:04.000Z',
|
||||
NULL,
|
||||
'2026-04-05T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES (
|
||||
'thread-deleted',
|
||||
'turn-deleted',
|
||||
'message-deleted-user',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-deleted-assistant',
|
||||
'completed',
|
||||
'2026-04-05T00:00:04.100Z',
|
||||
'2026-04-05T00:00:04.200Z',
|
||||
'2026-04-05T00:00:04.300Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
||||
assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted"));
|
||||
assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z");
|
||||
assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted"));
|
||||
assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z");
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed");
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed");
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.projects.length, 0);
|
||||
assert.equal(shellSnapshot.threads.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots",
|
||||
() => {
|
||||
const resolveCalls: string[] = [];
|
||||
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(RepositoryIdentityResolver, {
|
||||
resolve: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
resolveCalls.push(cwd);
|
||||
return {
|
||||
canonicalKey: `github.com/acme${cwd}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `https://github.com/acme${cwd}.git`,
|
||||
},
|
||||
rootPath: cwd,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'project-1',
|
||||
'Shared Project 1',
|
||||
'/tmp/shared-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:00.000Z',
|
||||
'2026-04-04T00:00:01.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-2',
|
||||
'Shared Project 2',
|
||||
'/tmp/shared-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:02.000Z',
|
||||
'2026-04-04T00:00:03.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-3',
|
||||
'Deleted Project',
|
||||
'/tmp/deleted-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:04.000Z',
|
||||
'2026-04-04T00:00:05.000Z',
|
||||
'2026-04-04T00:00:06.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]);
|
||||
assert.equal(shellSnapshot.projects.length, 2);
|
||||
assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
||||
assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
||||
|
||||
resolveCalls.length = 0;
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]);
|
||||
assert.equal(fullSnapshot.projects.length, 3);
|
||||
assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
@@ -219,6 +219,20 @@ function mapProjectShellRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapProposedPlanRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
|
||||
): OrchestrationProposedPlan {
|
||||
return {
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -230,6 +244,37 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||
const repositoryIdentityResolutionConcurrency = 4;
|
||||
const resolveRepositoryIdentitiesForProjects = Effect.fn(
|
||||
"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects",
|
||||
)(function* (
|
||||
projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,
|
||||
options?: {
|
||||
readonly includeDeleted?: boolean;
|
||||
},
|
||||
) {
|
||||
const filteredProjectRows =
|
||||
options?.includeDeleted === true
|
||||
? projectRows
|
||||
: projectRows.filter((row) => row.deletedAt === null);
|
||||
const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];
|
||||
const repositoryIdentityByWorkspaceRoot = new Map(
|
||||
yield* Effect.forEach(
|
||||
uniqueWorkspaceRoots,
|
||||
(workspaceRoot) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
|
||||
return new Map(
|
||||
filteredProjectRows.map((row) => [
|
||||
row.projectId,
|
||||
repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
const listProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
@@ -335,7 +380,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
ORDER BY
|
||||
thread_id ASC,
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -389,18 +433,46 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.latest_turn_id IS NOT NULL
|
||||
ORDER BY turns.thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listActiveLatestTurnRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.deleted_at IS NULL
|
||||
AND threads.latest_turn_id IS NOT NULL
|
||||
ORDER BY turns.thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -594,7 +666,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -892,15 +963,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
|
||||
projectRows,
|
||||
{ includeDeleted: true },
|
||||
);
|
||||
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
@@ -958,6 +1023,199 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getCommandReadModel: ProjectionSnapshotQueryShape["getCommandReadModel"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(
|
||||
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.sync(() => {
|
||||
let updatedAt: string | null = null;
|
||||
const projects: OrchestrationProject[] = [];
|
||||
const threads: OrchestrationThread[] = [];
|
||||
|
||||
for (let index = 0; index < projectRows.length; index += 1) {
|
||||
const row = projectRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
projects.push({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
});
|
||||
}
|
||||
for (let index = 0; index < threadRows.length; index += 1) {
|
||||
const row = threadRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
||||
const row = proposedPlanRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
||||
const row = sessionRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
||||
const row = latestTurnRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < stateRows.length; index += 1) {
|
||||
const row = stateRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
||||
const row = latestTurnRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
|
||||
}
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const sessionByThread = new Map<string, OrchestrationSession>();
|
||||
|
||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
||||
const row = sessionRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
sessionByThread.set(row.threadId, mapSessionRow(row));
|
||||
}
|
||||
|
||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
||||
const row = proposedPlanRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
|
||||
threadProposedPlans.push(mapProposedPlanRow(row));
|
||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
||||
}
|
||||
|
||||
for (let index = 0; index < threadRows.length; index += 1) {
|
||||
const row = threadRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
threads.push({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
} satisfies OrchestrationReadModel;
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getCommandReadModel:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
@@ -986,7 +1244,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
listActiveLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
@@ -1030,16 +1288,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
@@ -1097,6 +1346,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshotSequence:query",
|
||||
"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((stateRows) => ({
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
})),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -1376,15 +1638,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
@@ -1422,8 +1676,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getSnapshotSequence,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
} from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
@@ -79,7 +80,7 @@ async function waitFor(
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -318,8 +319,13 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
@@ -348,6 +354,7 @@ describe("ProviderCommandReactor", () => {
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
@@ -382,6 +389,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -431,7 +439,7 @@ describe("ProviderCommandReactor", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -476,13 +484,13 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Generated title"
|
||||
);
|
||||
});
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
@@ -522,7 +530,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
@@ -566,14 +574,14 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Reconnect spinner resume bug"
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
@@ -902,7 +910,7 @@ describe("ProviderCommandReactor", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.providerName).toBe("claudeAgent");
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
|
||||
@@ -1014,7 +1022,7 @@ describe("ProviderCommandReactor", () => {
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
|
||||
});
|
||||
@@ -1205,7 +1213,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1239,7 +1247,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -1342,7 +1350,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1352,7 +1360,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
@@ -1404,7 +1412,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1416,7 +1424,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
@@ -1475,7 +1483,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1485,7 +1493,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1639,7 +1647,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1649,7 +1657,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1810,7 +1818,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1818,7 +1826,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1919,7 +1927,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1927,7 +1935,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1983,7 +1991,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
ProviderDriverKind,
|
||||
type ProjectId,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
@@ -22,6 +23,7 @@ import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
@@ -167,6 +169,7 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
@@ -267,9 +270,16 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
||||
@@ -279,8 +289,7 @@ const make = Effect.gen(function* () {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const thread = yield* resolveThread(threadId);
|
||||
if (!thread) {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
@@ -375,9 +384,10 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
}
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
projects: project ? [project] : [],
|
||||
});
|
||||
|
||||
const startProviderSession = (input?: {
|
||||
@@ -682,10 +692,11 @@ const make = Effect.gen(function* () {
|
||||
const isFirstUserMessageTurn =
|
||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
||||
if (isFirstUserMessageTurn) {
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const generationCwd =
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
||||
projects: project ? [project] : [],
|
||||
}) ?? process.cwd();
|
||||
const generationInput = {
|
||||
messageText: message.text,
|
||||
@@ -819,20 +830,16 @@ const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
|
||||
if (!isUnknownPendingApprovalRequestError(cause)) return;
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -36,11 +36,9 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -154,16 +152,23 @@ function createProviderServiceHarness() {
|
||||
};
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
readModel: () => Promise<ProviderRuntimeTestReadModel>,
|
||||
predicate: (thread: ProviderRuntimeTestThread) => boolean,
|
||||
timeoutMs = 2000,
|
||||
threadId: ThreadId = asThreadId("thread-1"),
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<ProviderRuntimeTestThread> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === threadId);
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -176,16 +181,9 @@ async function waitForThread(
|
||||
return poll();
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService,
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -223,8 +221,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
@@ -233,6 +236,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
|
||||
@@ -299,6 +303,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
emit: provider.emit,
|
||||
setProviderSession: provider.setSession,
|
||||
drain,
|
||||
@@ -319,7 +324,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1",
|
||||
);
|
||||
|
||||
@@ -337,7 +342,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -364,7 +369,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
let thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null,
|
||||
);
|
||||
expect(thread.session?.status).toBe("running");
|
||||
@@ -383,7 +388,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -404,7 +409,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "stopped" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -425,7 +430,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -449,7 +454,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-midturn-lifecycle",
|
||||
@@ -471,7 +476,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
|
||||
@@ -487,7 +492,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -524,7 +529,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-claude-placeholder",
|
||||
@@ -541,7 +546,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -560,7 +565,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
||||
);
|
||||
@@ -576,7 +581,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
@@ -592,7 +597,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -611,7 +616,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-guarded-main",
|
||||
@@ -628,7 +633,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
@@ -644,7 +649,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -693,7 +698,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-1" && !message.streaming,
|
||||
@@ -725,7 +730,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-no-delta" && !message.streaming,
|
||||
@@ -764,7 +769,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
|
||||
),
|
||||
@@ -819,7 +824,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
|
||||
),
|
||||
@@ -861,7 +866,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
|
||||
),
|
||||
@@ -894,7 +899,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-final",
|
||||
@@ -1009,7 +1014,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1050,7 +1055,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
const sourceThreadBeforeStart = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1076,7 +1081,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadAfterStart = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1158,7 +1163,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
@@ -1178,7 +1183,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1229,7 +1234,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const sourceThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1340,7 +1345,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1401,7 +1406,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1427,7 +1432,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer",
|
||||
);
|
||||
@@ -1466,7 +1471,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer",
|
||||
@@ -1492,7 +1497,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
|
||||
);
|
||||
@@ -1512,7 +1517,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
midThread?.messages.some(
|
||||
@@ -1534,7 +1539,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered" && !message.streaming,
|
||||
@@ -1560,7 +1565,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-flush",
|
||||
@@ -1593,7 +1598,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-flush" &&
|
||||
@@ -1620,7 +1625,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
|
||||
@@ -1659,7 +1664,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-user-input-flush" &&
|
||||
@@ -1688,7 +1693,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
|
||||
@@ -1721,7 +1726,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
),
|
||||
@@ -1750,7 +1755,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-append",
|
||||
@@ -1783,7 +1788,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append" &&
|
||||
@@ -1819,7 +1824,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append:segment:1" &&
|
||||
@@ -1882,7 +1887,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-request-segment",
|
||||
@@ -1915,7 +1920,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment" &&
|
||||
@@ -1951,7 +1956,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1" &&
|
||||
@@ -2004,7 +2009,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-mode",
|
||||
@@ -2024,7 +2029,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||
const liveThread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
@@ -2052,7 +2057,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||
const finalThread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
@@ -2079,7 +2084,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffer-spill",
|
||||
@@ -2112,7 +2117,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
@@ -2140,7 +2145,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-complete-dedup",
|
||||
@@ -2185,7 +2190,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "ready" &&
|
||||
thread.session?.activeTurnId === null &&
|
||||
@@ -2243,7 +2248,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
@@ -2253,7 +2258,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -2295,7 +2300,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-3" &&
|
||||
@@ -2321,7 +2326,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
@@ -2366,7 +2371,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "running" &&
|
||||
entry.session?.activeTurnId === "turn-warning" &&
|
||||
@@ -2415,7 +2420,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -2508,7 +2513,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.title === "Renamed by provider" &&
|
||||
entry.activities.some(
|
||||
@@ -2595,7 +2600,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2647,7 +2652,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2697,7 +2702,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2732,7 +2737,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
@@ -2802,7 +2807,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed",
|
||||
@@ -2893,7 +2898,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested",
|
||||
@@ -2952,7 +2957,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-after-failure" &&
|
||||
|
||||
@@ -4,12 +4,16 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -19,9 +23,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
type ProviderRuntimeIngestionShape,
|
||||
@@ -77,6 +81,82 @@ function sameId(left: string | null | undefined, right: string | null | undefine
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function hasAssistantMessageForTurn(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
turnId: TurnId,
|
||||
options?: { readonly streamingOnly?: boolean },
|
||||
): boolean {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (!message) {
|
||||
continue;
|
||||
}
|
||||
if (message.role !== "assistant" || message.turnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
if (options?.streamingOnly === true && !message.streaming) {
|
||||
continue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function findMessageById(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
messageId: MessageId,
|
||||
): OrchestrationMessage | undefined {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (message?.id === messageId) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findProposedPlanById(
|
||||
proposedPlans: ReadonlyArray<
|
||||
Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
>,
|
||||
planId: string,
|
||||
):
|
||||
| Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
| undefined {
|
||||
for (let index = 0; index < proposedPlans.length; index += 1) {
|
||||
const proposedPlan = proposedPlans[index];
|
||||
if (proposedPlan?.id === planId) {
|
||||
return proposedPlan;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasCheckpointForTurn(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
turnId: TurnId,
|
||||
): boolean {
|
||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
||||
if (checkpoints[index]?.turnId === turnId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function maxCheckpointTurnCount(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): number {
|
||||
let maxTurnCount = 0;
|
||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
||||
const checkpoint = checkpoints[index];
|
||||
if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {
|
||||
maxTurnCount = checkpoint.checkpointTurnCount;
|
||||
}
|
||||
}
|
||||
return maxTurnCount;
|
||||
}
|
||||
|
||||
function truncateDetail(value: string, limit = 180): string {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
@@ -522,6 +602,7 @@ function runtimeEventToActivities(
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
@@ -553,20 +634,16 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadShellById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
||||
@@ -917,7 +994,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
@@ -1070,8 +1147,7 @@ const make = Effect.gen(function* () {
|
||||
implementationThreadId: ThreadId,
|
||||
implementedAt: string,
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
|
||||
const sourceThread = yield* resolveThreadDetail(sourceThreadId);
|
||||
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||
return;
|
||||
@@ -1096,10 +1172,19 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
const thread = yield* resolveThreadShell(event.threadId);
|
||||
if (!thread) return;
|
||||
|
||||
let loadedThreadDetail: OrchestrationThread | null | undefined;
|
||||
const getLoadedThreadDetail = () =>
|
||||
Effect.gen(function* () {
|
||||
if (loadedThreadDetail !== undefined) {
|
||||
return loadedThreadDetail;
|
||||
}
|
||||
loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
|
||||
return loadedThreadDetail;
|
||||
});
|
||||
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
@@ -1277,6 +1362,7 @@ const make = Effect.gen(function* () {
|
||||
? toTurnId(event.turnId)
|
||||
: undefined;
|
||||
if (pauseForUserTurnId) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
@@ -1307,10 +1393,11 @@ const make = Effect.gen(function* () {
|
||||
event.type === "request.opened"
|
||||
? "assistant-delta-finalize-on-request-opened"
|
||||
: "assistant-delta-finalize-on-user-input-requested",
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) =>
|
||||
entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
|
||||
),
|
||||
hasProjectedMessage:
|
||||
detailedThread !== null &&
|
||||
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
|
||||
streamingOnly: true,
|
||||
}),
|
||||
flushedMessageIds,
|
||||
});
|
||||
}
|
||||
@@ -1339,21 +1426,19 @@ const make = Effect.gen(function* () {
|
||||
: undefined;
|
||||
|
||||
if (assistantCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const activeAssistantMessageId = turnId
|
||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||
: Option.none<MessageId>();
|
||||
const hasAssistantMessagesForTurn =
|
||||
turnId !== undefined
|
||||
? thread.messages.some((entry) => entry.role === "assistant" && entry.turnId === turnId)
|
||||
: false;
|
||||
turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
|
||||
const assistantMessageId = Option.getOrElse(
|
||||
activeAssistantMessageId,
|
||||
() => assistantCompletion.messageId,
|
||||
);
|
||||
const existingAssistantMessage = thread.messages.find(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
);
|
||||
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
||||
|
||||
@@ -1393,10 +1478,11 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (proposedPlanCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
threadProposedPlans: detailedThread?.proposedPlans ?? [],
|
||||
planId: proposedPlanCompletion.planId,
|
||||
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
||||
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
||||
@@ -1405,6 +1491,9 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
|
||||
@@ -1419,9 +1508,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
),
|
||||
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
@@ -1431,7 +1518,7 @@ const make = Effect.gen(function* () {
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
threadProposedPlans: proposedPlans,
|
||||
planId: proposedPlanIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
updatedAt: now,
|
||||
@@ -1483,21 +1570,24 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
const checkpointContext = turnId
|
||||
? yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(thread.id)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
: undefined;
|
||||
const workspaceCwd =
|
||||
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
|
||||
if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
|
||||
// Skip if a checkpoint already exists for this turn. A real
|
||||
// (non-placeholder) capture from CheckpointReactor should not
|
||||
// be clobbered, and dispatching a duplicate placeholder for the
|
||||
// same turnId would produce an unstable checkpointTurnCount.
|
||||
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
|
||||
if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
|
||||
// Already tracked; no-op.
|
||||
} else {
|
||||
const assistantMessageId = MessageId.make(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
(max, c) => Math.max(max, c.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||
@@ -1508,7 +1598,7 @@ const make = Effect.gen(function* () {
|
||||
status: "missing",
|
||||
files: [],
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: maxTurnCount + 1,
|
||||
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,11 +10,7 @@
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
*/
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
@@ -25,13 +21,6 @@ import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
|
||||
* OrchestrationEngineShape - Service API for orchestration command and event flow.
|
||||
*/
|
||||
export interface OrchestrationEngineShape {
|
||||
/**
|
||||
* Read the current in-memory orchestration read model.
|
||||
*
|
||||
* @returns Effect containing the latest read model.
|
||||
*/
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||
|
||||
/**
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
*
|
||||
@@ -70,7 +59,7 @@ export interface OrchestrationEngineShape {
|
||||
* ```ts
|
||||
* const program = Effect.gen(function* () {
|
||||
* const engine = yield* OrchestrationEngineService
|
||||
* return yield* engine.getReadModel()
|
||||
* return yield* engine.dispatch(command)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
|
||||
@@ -28,6 +28,10 @@ export interface ProjectionSnapshotCounts {
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
export interface ProjectionSnapshotSequence {
|
||||
readonly snapshotSequence: number;
|
||||
}
|
||||
|
||||
export interface ProjectionThreadCheckpointContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: ProjectId;
|
||||
@@ -40,6 +44,15 @@ export interface ProjectionThreadCheckpointContext {
|
||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||
*/
|
||||
export interface ProjectionSnapshotQueryShape {
|
||||
/**
|
||||
* Read the lightweight command snapshot used to bootstrap the in-memory
|
||||
* orchestration engine without hydrating message/activity/checkpoint bodies.
|
||||
*/
|
||||
readonly getCommandReadModel: () => Effect.Effect<
|
||||
OrchestrationReadModel,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration projection snapshot.
|
||||
*
|
||||
@@ -59,6 +72,15 @@ export interface ProjectionSnapshotQueryShape {
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read the latest projection snapshot sequence without hydrating read-model
|
||||
* entities.
|
||||
*/
|
||||
readonly getSnapshotSequence: () => Effect.Effect<
|
||||
ProjectionSnapshotSequence,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
|
||||
@@ -41,6 +41,7 @@ import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingAppro
|
||||
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
|
||||
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
|
||||
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
|
||||
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -81,6 +82,7 @@ export const migrationEntries = [
|
||||
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
||||
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
|
||||
[28, "ProjectionThreadSessionInstanceId", Migration0028],
|
||||
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {
|
||||
it.effect("creates indexes matching thread detail ordering queries", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 28 });
|
||||
yield* runMigrations({ toMigrationInclusive: 29 });
|
||||
|
||||
const activityIndexes = yield* sql<{
|
||||
readonly seq: number;
|
||||
readonly name: string;
|
||||
readonly unique: number;
|
||||
readonly origin: string;
|
||||
readonly partial: number;
|
||||
}>`
|
||||
PRAGMA index_list(projection_thread_activities)
|
||||
`;
|
||||
assert.ok(
|
||||
activityIndexes.some(
|
||||
(index) => index.name === "idx_projection_thread_activities_thread_sequence_created_id",
|
||||
),
|
||||
);
|
||||
|
||||
const activityIndexColumns = yield* sql<{
|
||||
readonly seqno: number;
|
||||
readonly cid: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
PRAGMA index_info('idx_projection_thread_activities_thread_sequence_created_id')
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
activityIndexColumns.map((column) => column.name),
|
||||
["thread_id", "sequence", "created_at", "activity_id"],
|
||||
);
|
||||
|
||||
const messageIndexes = yield* sql<{
|
||||
readonly seq: number;
|
||||
readonly name: string;
|
||||
readonly unique: number;
|
||||
readonly origin: string;
|
||||
readonly partial: number;
|
||||
}>`
|
||||
PRAGMA index_list(projection_thread_messages)
|
||||
`;
|
||||
assert.ok(
|
||||
messageIndexes.some(
|
||||
(index) => index.name === "idx_projection_thread_messages_thread_created_id",
|
||||
),
|
||||
);
|
||||
|
||||
const messageIndexColumns = yield* sql<{
|
||||
readonly seqno: number;
|
||||
readonly cid: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
PRAGMA index_info('idx_projection_thread_messages_thread_created_id')
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
messageIndexColumns.map((column) => column.name),
|
||||
["thread_id", "created_at", "message_id"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id
|
||||
ON projection_thread_activities(thread_id, sequence, created_at, activity_id)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id
|
||||
ON projection_thread_messages(thread_id, created_at, message_id)
|
||||
`;
|
||||
});
|
||||
@@ -1,53 +1,52 @@
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
|
||||
|
||||
const emptySnapshot = (
|
||||
scripts: OrchestrationReadModel["projects"][number]["scripts"],
|
||||
): OrchestrationReadModel =>
|
||||
({
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
providerSessions: [],
|
||||
providerStatuses: [],
|
||||
pendingApprovals: [],
|
||||
latestTurnByThreadId: {},
|
||||
}) as unknown as OrchestrationReadModel;
|
||||
const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
|
||||
Effect.succeed(
|
||||
workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
|
||||
),
|
||||
getProjectShellById: (projectId) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
});
|
||||
|
||||
describe("ProjectSetupScriptRunner", () => {
|
||||
it("returns no-script when no setup script exists", async () => {
|
||||
const open = vi.fn();
|
||||
const write = vi.fn();
|
||||
const project = makeProject([]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.succeed(emptySnapshot([])),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
@@ -93,29 +92,20 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
}),
|
||||
);
|
||||
const write = vi.fn(() => Effect.void);
|
||||
const project = makeProject([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () =>
|
||||
Effect.succeed(
|
||||
emptySnapshot([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { ProjectId } from "@t3tools/contracts";
|
||||
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import {
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
@@ -9,18 +10,21 @@ import {
|
||||
} from "../Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
const makeProjectSetupScriptRunner = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
|
||||
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const project =
|
||||
(input.projectId
|
||||
? readModel.projects.find((entry) => entry.id === input.projectId)
|
||||
? yield* projectionSnapshotQuery
|
||||
.getProjectShellById(ProjectId.make(input.projectId))
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
: null) ??
|
||||
(input.projectCwd
|
||||
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
|
||||
? yield* projectionSnapshotQuery
|
||||
.getActiveProjectByWorkspaceRoot(input.projectCwd)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
: null) ??
|
||||
null;
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
@@ -34,15 +35,43 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.local/bin/claude") ||
|
||||
normalized.endsWith("/.local/bin/claude.exe") ||
|
||||
normalized.includes("/.local/share/claude/")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@anthropic-ai/claude-code",
|
||||
homebrewFormula: "claude-code",
|
||||
nativeUpdate: {
|
||||
executable: "claude",
|
||||
args: ["update"],
|
||||
lockKey: "claude-native",
|
||||
isCommandPath: isClaudeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -75,6 +104,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -82,6 +112,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
@@ -121,11 +155,17 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
@@ -35,6 +36,11 @@ import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import {
|
||||
codexContinuationIdentity,
|
||||
materializeCodexShadowHome,
|
||||
@@ -43,6 +49,12 @@ import {
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
homebrewFormula: "codex",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Services the driver needs to materialize an instance. Surfaced as the
|
||||
@@ -52,6 +64,7 @@ const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -89,6 +102,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
@@ -115,6 +129,10 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
@@ -138,11 +156,17 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -34,13 +35,28 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
}),
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -74,6 +90,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -87,6 +104,10 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
@@ -103,6 +124,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
@@ -117,8 +139,10 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
settings,
|
||||
environment: processEnv,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
@@ -34,13 +35,40 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.opencode/bin/opencode") ||
|
||||
normalized.endsWith("/.opencode/bin/opencode.exe")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "opencode-ai",
|
||||
homebrewFormula: "anomalyco/tap/opencode",
|
||||
nativeUpdate: {
|
||||
executable: "opencode",
|
||||
args: ["upgrade"],
|
||||
lockKey: "opencode-native",
|
||||
isCommandPath: isOpenCodeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
@@ -74,6 +102,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -87,6 +116,10 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
@@ -102,11 +135,17 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
@@ -29,6 +30,10 @@ import {
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("cursor");
|
||||
@@ -1216,42 +1221,67 @@ export const enrichCursorSnapshot = (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
if (
|
||||
!settings.enabled ||
|
||||
snapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(snapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...snapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
|
||||
snapshot,
|
||||
input.maintenanceCapabilities,
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: snapshot.models.map((model) => model.slug),
|
||||
Effect.logWarning("Cursor version advisory enrichment failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.as(snapshot)),
|
||||
),
|
||||
);
|
||||
|
||||
return enrichVersionAdvisory.pipe(
|
||||
Effect.flatMap((baseSnapshot) => {
|
||||
if (
|
||||
!settings.enabled ||
|
||||
baseSnapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(baseSnapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(
|
||||
settings,
|
||||
baseSnapshot.models,
|
||||
input.environment,
|
||||
).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...baseSnapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: baseSnapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
import { Cause, Data, Effect } from "effect";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
nonEmptyTrimmed,
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -111,6 +112,10 @@ const makeFakeInstance = (
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
@@ -44,6 +45,13 @@ import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -89,6 +97,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -225,6 +234,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
@@ -26,13 +27,17 @@ import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistr
|
||||
import {
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
|
||||
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
@@ -46,6 +51,13 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -246,7 +258,7 @@ function makeMutableServerSettingsService(
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), TestHttpClientLive))(
|
||||
"ProviderRegistry",
|
||||
(it) => {
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
@@ -500,6 +512,182 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
]);
|
||||
});
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
driver: ProviderDriverKind.make("cursor"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast Mode"),
|
||||
booleanDescriptor("thinking", "Thinking"),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
const refreshedCursor = {
|
||||
...previousProviders[0],
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(persistedProviders, [
|
||||
{
|
||||
...refreshedCursor,
|
||||
models: [...previousProviders[0].models],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("persists the merged snapshot when a live update has empty models", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
const cursorInstanceId = ProviderInstanceId.make("cursor");
|
||||
const initialProvider = {
|
||||
instanceId: cursorInstanceId,
|
||||
driver: cursorDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...initialProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
const changes = yield* PubSub.unbounded<ServerProvider>();
|
||||
const instance = {
|
||||
instanceId: cursorInstanceId,
|
||||
driverKind: cursorDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: cursorDriver,
|
||||
continuationKey: "cursor:instance:cursor",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
});
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: cursorInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
|
||||
...initialProvider.models,
|
||||
]);
|
||||
yield* PubSub.publish(changes, refreshedProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* Effect.sleep("10 millis");
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider, {
|
||||
...refreshedProvider,
|
||||
models: [...initialProvider.models],
|
||||
});
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -527,6 +715,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(cachedProvider),
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -612,6 +804,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -748,6 +944,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
@@ -832,6 +1029,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
@@ -936,6 +1134,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -986,6 +1185,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -43,6 +44,7 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
@@ -59,6 +61,12 @@ const loadProviders = (
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
@@ -96,6 +104,30 @@ export const mergeProviderSnapshot = (
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
@@ -227,6 +259,9 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
@@ -264,6 +299,21 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
@@ -272,15 +322,24 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
@@ -290,13 +349,16 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
@@ -318,6 +380,45 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
@@ -365,6 +466,18 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
@@ -472,6 +585,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
@@ -555,6 +677,8 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
|
||||
@@ -9,10 +9,7 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
@@ -92,6 +89,10 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: thread.session,
|
||||
@@ -163,13 +164,6 @@ describe("ProviderSessionReaper", () => {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const orchestrationEngine: OrchestrationEngineShape = {
|
||||
getReadModel: () => Effect.succeed(input.readModel),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => unsupported(),
|
||||
streamDomainEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -183,7 +177,27 @@ describe("ProviderSessionReaper", () => {
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
||||
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
import { Duration, Effect, Layer, Option, Schedule } from "effect";
|
||||
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
@@ -20,7 +20,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
@@ -29,8 +29,6 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = Date.now();
|
||||
let reapedCount = 0;
|
||||
@@ -55,7 +53,9 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
continue;
|
||||
}
|
||||
|
||||
const thread = threadsById.get(binding.threadId);
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(binding.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
if (thread?.session?.activeTurnId != null) {
|
||||
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
|
||||
threadId: binding.threadId,
|
||||
|
||||
@@ -6,9 +6,17 @@
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts";
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
@@ -39,6 +47,27 @@ export interface ProviderRegistryShape {
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
|
||||
@@ -20,6 +20,20 @@ interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
const maintenanceCapabilities = {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
packageName: "@openai/codex",
|
||||
update: {
|
||||
command: "npm install -g @openai/codex@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const initialSnapshot: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
@@ -90,6 +104,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -131,6 +146,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -172,6 +188,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -212,6 +229,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
|
||||
@@ -13,6 +13,7 @@ interface ProviderSnapshotState {
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
@@ -143,6 +144,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Effect, Random } from "effect";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
createProviderVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
return path.join(os.tmpdir(), `${name}-${id}`);
|
||||
});
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
(commandPath: string): boolean =>
|
||||
normalizeCommandPath(commandPath).includes(expectedPathSegment);
|
||||
const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("packageTool"),
|
||||
npmPackageName: "@example/package-tool",
|
||||
homebrewFormula: "package-tool",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("nativePackageTool"),
|
||||
npmPackageName: "@example/native-package-tool",
|
||||
homebrewFormula: "native-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "native-package-tool",
|
||||
args: ["update"],
|
||||
lockKey: "native-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
|
||||
},
|
||||
});
|
||||
const scopedPackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("scopedPackageTool"),
|
||||
npmPackageName: "@example/scoped-package-tool",
|
||||
homebrewFormula: "example/tap/scoped-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "scoped-package-tool",
|
||||
args: ["upgrade"],
|
||||
lockKey: "scoped-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.scoped-package-tool/bin/scoped-package-tool"),
|
||||
},
|
||||
});
|
||||
const staticToolUpdate = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
updateExecutable: "static-tool",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "static-tool",
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
describe("providerMaintenance", () => {
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks providers with unknown latest versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
message: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks installed providers behind latest when a newer provider version is available", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("nativePackageTool"),
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
maintenanceCapabilities: nativePackageToolUpdate.resolve(),
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
updateCommand: "npm install -g @example/native-package-tool@latest",
|
||||
canUpdate: true,
|
||||
message: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps update commands owned by provider maintenance capabilities", () => {
|
||||
expect(staticToolUpdate.resolve()).toEqual({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
update: {
|
||||
command: "static-tool update",
|
||||
|
||||
executable: "static-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "static-tool",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-vite-plus-capabilities");
|
||||
const vitePlusBinDir = path.join(tempDir, ".vite-plus", "bin");
|
||||
mkdirSync(vitePlusBinDir, { recursive: true });
|
||||
const packageToolPath = path.join(vitePlusBinDir, "package-tool");
|
||||
writeFileSync(packageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(packageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: vitePlusBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "vp i -g @example/package-tool",
|
||||
|
||||
executable: "vp",
|
||||
|
||||
args: ["i", "-g", "@example/package-tool"],
|
||||
|
||||
lockKey: "vite-plus-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to bun updates when the resolved binary lives in bun's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-bun-capabilities");
|
||||
const bunBinDir = path.join(tempDir, ".bun", "bin");
|
||||
mkdirSync(bunBinDir, { recursive: true });
|
||||
writeFileSync(path.join(bunBinDir, "native-package-tool.exe"), "MZ");
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: bunBinDir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "bun i -g @example/native-package-tool@latest",
|
||||
|
||||
executable: "bun",
|
||||
|
||||
args: ["i", "-g", "@example/native-package-tool@latest"],
|
||||
|
||||
lockKey: "bun-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to pnpm updates when the resolved binary lives in pnpm's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
|
||||
const pnpmHomeDir = path.join(tempDir, ".local", "share", "pnpm");
|
||||
mkdirSync(pnpmHomeDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(pnpmHomeDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: pnpmHomeDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/scoped-package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/scoped-package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "brew upgrade package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches native-package-tool to native updates when the binary resolves through the native installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-native-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".local", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const nativePackageToolPath = path.join(nativeBinDir, "native-package-tool");
|
||||
writeFileSync(nativePackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(nativePackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "native-package-tool update",
|
||||
|
||||
executable: "native-package-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "native-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches scoped-package-tool to native upgrades when the binary resolves through the standalone installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-scoped-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".scoped-package-tool", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(nativeBinDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "scoped-package-tool upgrade",
|
||||
|
||||
executable: "scoped-package-tool",
|
||||
|
||||
args: ["upgrade"],
|
||||
|
||||
lockKey: "scoped-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches native-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade native-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "native-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("switches scoped-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade example/tap/scoped-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "example/tap/scoped-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps npm updates for binaries symlinked into npm's global node_modules tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-npm-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
"lib",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "npm install -g @example/package-tool@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Effect FileSystem realPath when detecting pnpm global symlinks", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-realpath-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
".local",
|
||||
"share",
|
||||
"pnpm",
|
||||
"global",
|
||||
"5",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("disables one-click updates for explicit custom binary paths it cannot safely map", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import { DateTime, Effect, FileSystem, Option, Schema } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { compareCliVersions } from "./cliVersion.ts";
|
||||
|
||||
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly update: ProviderMaintenanceCommandAction | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCommandAction {
|
||||
readonly command: string;
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly realCommandPath?: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilitiesResolver {
|
||||
readonly resolve: (
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
) => ProviderMaintenanceCapabilities;
|
||||
}
|
||||
|
||||
export interface PackageManagedProviderMaintenanceDefinition {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly npmPackageName: string;
|
||||
readonly homebrewFormula: string | null;
|
||||
readonly nativeUpdate: {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
readonly isCommandPath: (commandPath: string) => boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LatestVersionCacheEntry {
|
||||
readonly expiresAt: number;
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
const latestVersionCache = new Map<string, LatestVersionCacheEntry>();
|
||||
const NpmLatestVersionResponse = Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export function clearLatestProviderVersionCacheForTests(): void {
|
||||
latestVersionCache.clear();
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function makeProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly updateExecutable: string | null;
|
||||
readonly updateArgs: ReadonlyArray<string>;
|
||||
readonly updateLockKey: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
const update =
|
||||
input.updateExecutable === null || input.updateLockKey === null
|
||||
? null
|
||||
: {
|
||||
command: [input.updateExecutable, ...input.updateArgs].join(" "),
|
||||
executable: input.updateExecutable,
|
||||
args: input.updateArgs,
|
||||
lockKey: input.updateLockKey,
|
||||
};
|
||||
return {
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
updateExecutable: null,
|
||||
updateArgs: [],
|
||||
updateLockKey: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeBunGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makePnpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeVitePlusGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", definition.npmPackageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeHomebrewProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
if (!definition.homebrewFormula) {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "brew",
|
||||
updateArgs: ["upgrade", definition.homebrewFormula],
|
||||
updateLockKey: "homebrew",
|
||||
});
|
||||
}
|
||||
|
||||
function makeNativeProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities | null {
|
||||
if (!definition.nativeUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: definition.nativeUpdate.executable,
|
||||
updateArgs: definition.nativeUpdate.args,
|
||||
updateLockKey: definition.nativeUpdate.lockKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
}
|
||||
|
||||
export function normalizeCommandPath(commandPath: string): string {
|
||||
return commandPath.replaceAll("\\", "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isVitePlusGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
|
||||
}
|
||||
|
||||
function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/.local/share/pnpm/") ||
|
||||
normalized.includes("/library/pnpm/") ||
|
||||
normalized.includes("/local/share/pnpm/") ||
|
||||
normalized.includes("/appdata/local/pnpm/") ||
|
||||
normalized.includes("/pnpm/global/")
|
||||
);
|
||||
}
|
||||
|
||||
function isNpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/node_modules/.bin/") ||
|
||||
normalized.includes("/lib/node_modules/") ||
|
||||
normalized.includes("/npm/node_modules/")
|
||||
);
|
||||
}
|
||||
|
||||
function isHomebrewCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/opt/homebrew/cellar/") ||
|
||||
normalized.includes("/usr/local/cellar/") ||
|
||||
normalized.includes("/homebrew/cellar/") ||
|
||||
normalized.includes("/opt/homebrew/caskroom/") ||
|
||||
normalized.includes("/usr/local/caskroom/") ||
|
||||
normalized.includes("/homebrew/caskroom/") ||
|
||||
normalized.startsWith("/opt/homebrew/bin/") ||
|
||||
normalized.startsWith("/usr/local/bin/")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolvePackageManagedProviderMaintenance(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
resolvedCommandPath,
|
||||
...(options?.realCommandPath ? [options.realCommandPath] : []),
|
||||
];
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (
|
||||
nativeUpdate &&
|
||||
commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))
|
||||
) {
|
||||
return (
|
||||
makeNativeProviderMaintenanceCapabilities(definition) ??
|
||||
makeNpmGlobalProviderMaintenanceCapabilities(definition)
|
||||
);
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeBunGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makePnpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isNpmGlobalCommandPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isHomebrewCommandPath)) {
|
||||
return makeHomebrewProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPathSeparator(binaryPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
export function makePackageManagedProviderMaintenanceResolver(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeStaticProviderMaintenanceResolver(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: () => capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
function makeManualProviderMaintenanceCapabilities(
|
||||
provider: ProviderDriverKind,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
"resolveProviderMaintenanceCapabilitiesEffect",
|
||||
)(function* (
|
||||
resolver: ProviderMaintenanceCapabilitiesResolver,
|
||||
options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,
|
||||
) {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
realCommandPath,
|
||||
});
|
||||
});
|
||||
|
||||
function deriveVersionAdvisory(input: {
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion: string | null;
|
||||
}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
|
||||
if (!input.currentVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (!input.latestVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
return {
|
||||
status: "behind_latest",
|
||||
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
|
||||
};
|
||||
}
|
||||
return { status: "current", message: null };
|
||||
}
|
||||
|
||||
export function createProviderVersionAdvisory(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly checkedAt?: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
|
||||
}): ServerProviderVersionAdvisory {
|
||||
const capabilities =
|
||||
input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
|
||||
const latestVersion = input.latestVersion ?? null;
|
||||
const advisory = deriveVersionAdvisory({
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
});
|
||||
|
||||
return {
|
||||
status: advisory.status,
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
updateCommand: capabilities.update?.command ?? null,
|
||||
canUpdate: capabilities.update !== null,
|
||||
checkedAt: input.checkedAt ?? null,
|
||||
message: advisory.message,
|
||||
};
|
||||
}
|
||||
|
||||
const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const request = HttpClientRequest.get(
|
||||
`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
|
||||
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
}
|
||||
const httpResponse = response.value;
|
||||
if (httpResponse.status < 200 || httpResponse.status >= 300) {
|
||||
return null;
|
||||
}
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return payload ? nonEmptyString(payload.version) : null;
|
||||
});
|
||||
|
||||
export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
) {
|
||||
const packageName = maintenanceCapabilities.packageName;
|
||||
if (!packageName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = latestVersionCache.get(packageName);
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.version;
|
||||
}
|
||||
|
||||
const version = yield* fetchNpmLatestVersion(packageName);
|
||||
latestVersionCache.set(packageName, {
|
||||
expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
|
||||
version,
|
||||
});
|
||||
return version;
|
||||
});
|
||||
|
||||
export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithVersionAdvisory",
|
||||
)(function* (snapshot: ServerProvider, maintenanceCapabilities?: ProviderMaintenanceCapabilities) {
|
||||
const capabilities =
|
||||
maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
|
||||
if (!snapshot.enabled || !snapshot.installed || !snapshot.version) {
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
checkedAt: snapshot.checkedAt,
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const latestVersion = yield* resolveLatestProviderVersion(capabilities);
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
latestVersion,
|
||||
checkedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Effect, Ref } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
export interface ProviderMaintenanceCommandCoordinatorShape<E> {
|
||||
readonly withCommandLock: <A, R>(input: {
|
||||
readonly targetKey: string;
|
||||
readonly lockKey: string;
|
||||
readonly onQueued?: Effect.Effect<void, E, R>;
|
||||
readonly run: Effect.Effect<A, E, R>;
|
||||
}) => Effect.Effect<A, E, R>;
|
||||
}
|
||||
|
||||
export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
|
||||
"makeProviderMaintenanceCommandCoordinator",
|
||||
)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
|
||||
const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());
|
||||
|
||||
const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
|
||||
return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
|
||||
if (runningTargets.has(targetKey)) {
|
||||
return [false, runningTargets] as const;
|
||||
}
|
||||
const next = new Set(runningTargets);
|
||||
next.add(targetKey);
|
||||
return [true, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const releaseTarget = (targetKey: string) =>
|
||||
Ref.update(runningTargetsRef, (runningTargets) => {
|
||||
const next = new Set(runningTargets);
|
||||
next.delete(targetKey);
|
||||
return next;
|
||||
});
|
||||
|
||||
const getLock = Effect.fn("getProviderMaintenanceCommandLock")(function* (lockKey: string) {
|
||||
const existing = (yield* Ref.get(locksRef)).get(lockKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const lock = yield* Semaphore.make(1);
|
||||
return yield* Ref.modify(locksRef, (locks) => {
|
||||
const current = locks.get(lockKey);
|
||||
if (current) {
|
||||
return [current, locks] as const;
|
||||
}
|
||||
const next = new Map(locks);
|
||||
next.set(lockKey, lock);
|
||||
return [lock, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
|
||||
targetKey,
|
||||
lockKey,
|
||||
onQueued,
|
||||
run,
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const acquired = yield* acquireTarget(targetKey);
|
||||
if (!acquired) {
|
||||
return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const lock = yield* getLock(lockKey);
|
||||
if (onQueued) {
|
||||
yield* onQueued;
|
||||
}
|
||||
return yield* lock.withPermits(1)(run);
|
||||
}).pipe(Effect.ensuring(releaseTarget(targetKey)));
|
||||
});
|
||||
|
||||
return {
|
||||
withCommandLock,
|
||||
} satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
|
||||
});
|
||||
@@ -0,0 +1,640 @@
|
||||
import { afterEach, describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerProviderUpdateError } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit, Fiber, Layer, Ref, Schema, Sink, Stream } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
});
|
||||
}
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
const baseProvider: ServerProvider = {
|
||||
instanceId: CODEX_INSTANCE_ID,
|
||||
driver: CODEX_DRIVER,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const baseCursorProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: CURSOR_INSTANCE_ID,
|
||||
driver: CURSOR_DRIVER,
|
||||
};
|
||||
|
||||
const baseOpenCodeProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: OPENCODE_INSTANCE_ID,
|
||||
driver: OPENCODE_DRIVER,
|
||||
};
|
||||
|
||||
const latestVersionHttpClient = (version: string) =>
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ version }, { headers: { "content-type": "application/json" } }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: result.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
},
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeRegistry(
|
||||
initialProviders: ServerProvider | ReadonlyArray<ServerProvider> = baseProvider,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
Array.isArray(initialProviders) ? initialProviders : [initialProviders],
|
||||
);
|
||||
const updateStatesRef = yield* Ref.make<ReadonlyArray<ServerProviderUpdateState>>([]);
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn(
|
||||
"providerMaintenanceRunner.test.setProviderMaintenanceActionState",
|
||||
)(function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
const updateState = input.state;
|
||||
if (updateState) {
|
||||
yield* Ref.update(updateStatesRef, (states) => [...states, updateState]);
|
||||
}
|
||||
return yield* Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((candidate) => {
|
||||
if (candidate.instanceId !== input.instanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = candidate;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
updateState,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const registry: ProviderRegistryShape = {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: () => Ref.get(providersRef),
|
||||
refreshInstance: () => Ref.get(providersRef),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(lifecycleFor(provider)),
|
||||
setProviderMaintenanceActionState,
|
||||
streamChanges: Stream.empty,
|
||||
};
|
||||
|
||||
return {
|
||||
registry,
|
||||
updateStatesRef,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
|
||||
Effect.provide(
|
||||
ProviderMaintenanceRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ProviderRegistry, registry)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("providerMaintenanceRunner", () => {
|
||||
it.effect("runs the allowlisted provider update command and records success", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry, updateStatesRef } = yield* makeRegistry(baseCursorProvider);
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CURSOR_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "agent",
|
||||
args: ["update"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(updateStatesRef)).map((state) => state.status),
|
||||
["queued", "running", "succeeded"],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses the resolved provider capabilities when choosing the update executable", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.0.14",
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "bun i -g @anthropic-ai/claude-code@latest",
|
||||
canUpdate: true,
|
||||
checkedAt: "2026-04-30T12:00:00.000Z",
|
||||
message: "Update available.",
|
||||
},
|
||||
});
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: () =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: CODEX_DRIVER,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "bun-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "bun",
|
||||
args: ["i", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"runs update commands through Effect ChildProcess when no test runner is injected",
|
||||
() => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const runner = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* runner.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "npm",
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("updates a single provider instance without touching sibling instances", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const personalInstanceId = ProviderInstanceId.make("codex_personal");
|
||||
const workInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const refreshedInstanceIds: Array<ProviderInstanceId> = [];
|
||||
const { registry } = yield* makeRegistry([
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: personalInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: workInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex-instance-test",
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", "@openai/codex"],
|
||||
updateLockKey: "vite-plus-global",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => assert.strictEqual(instanceId, personalInstanceId))),
|
||||
),
|
||||
refreshInstance: (instanceId) =>
|
||||
registry.refreshInstance(instanceId).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
refreshedInstanceIds.push(instanceId);
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider({
|
||||
provider: CODEX_DRIVER,
|
||||
instanceId: personalInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "vp",
|
||||
args: ["i", "-g", "@openai/codex"],
|
||||
},
|
||||
]);
|
||||
assert.deepStrictEqual(refreshedInstanceIds, [personalInstanceId]);
|
||||
assert.strictEqual(result.providers[0]?.instanceId, personalInstanceId);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.strictEqual(result.providers[1]?.instanceId, workInstanceId);
|
||||
assert.strictEqual(result.providers[1]?.updateState, undefined);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.124.0-alpha.3"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("records command failure output in provider update state", () =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
const updateState = result.providers[0]?.updateState;
|
||||
|
||||
assert.strictEqual(updateState?.status, "failed");
|
||||
assert.strictEqual(updateState?.message, "Update command exited with code 1.");
|
||||
assert.include(updateState?.output ?? "", "permission denied");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks successful commands as unchanged when the refreshed provider is still outdated",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
});
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");
|
||||
assert.include(result.providers[0]?.updateState?.message ?? "", "still detects");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("9.9.9"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prevents concurrent updates for the same provider", () => {
|
||||
const startedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const started = new Promise<void>((resolve) => {
|
||||
startedLatch.resolve = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
releaseLatch.resolve = resolve;
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => started);
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isFailure(second), true);
|
||||
if (Exit.isFailure(second)) {
|
||||
const error = Cause.squash(second.cause);
|
||||
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
|
||||
if (Schema.is(ServerProviderUpdateError)(error)) {
|
||||
assert.include(error.reason, "already running");
|
||||
}
|
||||
}
|
||||
|
||||
releaseLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => {
|
||||
startedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => release).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("serializes different providers that share the same update lock key", () => {
|
||||
const firstStartedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseFirstLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const firstStarted = new Promise<void>((resolve) => {
|
||||
firstStartedLatch.resolve = resolve;
|
||||
});
|
||||
const releaseFirst = new Promise<void>((resolve) => {
|
||||
releaseFirstLatch.resolve = resolve;
|
||||
});
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry([baseProvider, baseOpenCodeProvider]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => firstStarted);
|
||||
|
||||
const second = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped);
|
||||
let providersWhileQueued: ReadonlyArray<ServerProvider> = [];
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
providersWhileQueued = yield* registry.getProviders;
|
||||
const queuedStatus = providersWhileQueued.find(
|
||||
(provider) => provider.instanceId === OPENCODE_INSTANCE_ID,
|
||||
)?.updateState?.status;
|
||||
if (queuedStatus === "queued") {
|
||||
break;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
assert.strictEqual(
|
||||
providersWhileQueued.find((provider) => provider.instanceId === OPENCODE_INSTANCE_ID)
|
||||
?.updateState?.status,
|
||||
"queued",
|
||||
);
|
||||
|
||||
releaseFirstLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
assert.deepStrictEqual(calls, [
|
||||
"install -g @openai/codex@latest",
|
||||
"install -g opencode-ai@latest",
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
if (calls.length === 1) {
|
||||
firstStartedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => releaseFirst).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts arbitrary driver-provided update lock keys", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "unknown-lock-key",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"releases the running-provider marker when interrupted after queuing but before the lock run starts",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
let blockQueuedState = true;
|
||||
const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const queuedStateWritten = new Promise<void>((resolve) => {
|
||||
queuedStateWrittenLatch.resolve = resolve;
|
||||
});
|
||||
const releaseQueuedState = new Promise<void>((resolve) => {
|
||||
releaseQueuedStateLatch.resolve = resolve;
|
||||
});
|
||||
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
setProviderMaintenanceActionState: Effect.fn(
|
||||
"providerMaintenanceRunner.test.blockQueuedState",
|
||||
)(function* (input) {
|
||||
const providers = yield* registry.setProviderMaintenanceActionState(input);
|
||||
if (input.state?.status === "queued" && blockQueuedState) {
|
||||
queuedStateWrittenLatch.resolve();
|
||||
yield* Effect.promise(() => releaseQueuedState);
|
||||
}
|
||||
return providers;
|
||||
}),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => queuedStateWritten);
|
||||
blockQueuedState = false;
|
||||
|
||||
yield* Fiber.interrupt(first);
|
||||
releaseQueuedStateLatch.resolve();
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isSuccess(second), true);
|
||||
if (Exit.isSuccess(second)) {
|
||||
assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ServerProviderUpdateError,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Context, DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
||||
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
|
||||
|
||||
export interface ProviderMaintenanceCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number | null;
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceRunnerShape {
|
||||
readonly updateProvider: (
|
||||
target:
|
||||
| ProviderDriverKind
|
||||
| {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId?: ProviderInstanceId | undefined;
|
||||
},
|
||||
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
|
||||
}
|
||||
|
||||
export class ProviderMaintenanceRunner extends Context.Service<
|
||||
ProviderMaintenanceRunner,
|
||||
ProviderMaintenanceRunnerShape
|
||||
>()("t3/provider/ProviderMaintenanceRunner") {}
|
||||
|
||||
interface VerifiedProviderRefresh {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly verifiedProviders: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
|
||||
function* (input: {
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(input.command, [...input.args]))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(`Failed to run update command ${input.command}: ${cause.message}`),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(cause instanceof Error ? cause.message : "Update command failed to run."),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode: Number(exitCode),
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProviderMaintenanceCommandResult;
|
||||
},
|
||||
);
|
||||
|
||||
return yield* collectCommandResult().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
|
||||
Effect.map((result) =>
|
||||
Option.match(result, {
|
||||
onSome: (value) => value,
|
||||
onNone: () =>
|
||||
({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}) satisfies ProviderMaintenanceCommandResult,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function trimNullable(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength: number): string {
|
||||
return value.length <= maxLength ? value : value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
|
||||
const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
|
||||
if (!output) {
|
||||
return null;
|
||||
}
|
||||
return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
|
||||
}
|
||||
|
||||
function failureMessage(result: ProviderMaintenanceCommandResult): string {
|
||||
if (result.timedOut) {
|
||||
return "Update timed out.";
|
||||
}
|
||||
if (result.exitCode !== null && result.exitCode !== 0) {
|
||||
return `Update command exited with code ${result.exitCode}.`;
|
||||
}
|
||||
return "Update command failed.";
|
||||
}
|
||||
|
||||
function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
|
||||
return provider?.versionAdvisory?.status === "behind_latest";
|
||||
}
|
||||
|
||||
function makeUpdateState(input: {
|
||||
readonly status: ServerProviderUpdateState["status"];
|
||||
readonly startedAt: string | null;
|
||||
readonly finishedAt: string | null;
|
||||
readonly message: string | null;
|
||||
readonly output?: string | null;
|
||||
}): ServerProviderUpdateState {
|
||||
return {
|
||||
status: input.status,
|
||||
startedAt: input.startedAt,
|
||||
finishedAt: input.finishedAt,
|
||||
message: input.message,
|
||||
output: input.output ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
runProviderMaintenanceCommandWithSpawner({
|
||||
spawner,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
|
||||
makeAlreadyRunningError: () =>
|
||||
new ServerProviderUpdateError({
|
||||
provider: ProviderDriverKind.make("unknown"),
|
||||
reason: "An update is already running for this provider.",
|
||||
}),
|
||||
});
|
||||
|
||||
const verifyRefreshedProvider = (
|
||||
provider: ProviderDriverKind,
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
: Effect.forEach(
|
||||
instanceIds,
|
||||
(instanceId) => providerRegistry.refreshInstance(instanceId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(providerRegistry.getProviders)),
|
||||
),
|
||||
Effect.flatMap((providers) => {
|
||||
const refreshedProviders = providers.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
);
|
||||
if (refreshedProviders.length === 0) {
|
||||
return Effect.succeed<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: [],
|
||||
});
|
||||
}
|
||||
return Effect.forEach(
|
||||
refreshedProviders,
|
||||
(refreshedProvider) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(
|
||||
refreshedProvider,
|
||||
maintenanceCapabilities,
|
||||
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(
|
||||
Effect.map(
|
||||
(verifiedProviders): VerifiedProviderRefresh => ({
|
||||
providers,
|
||||
verifiedProviders,
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Provider post-update version verification failed", {
|
||||
provider,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(
|
||||
Effect.as<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: refreshedProviders,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
|
||||
"ProviderMaintenanceRunner.updateProvider",
|
||||
)(function* (target) {
|
||||
const provider = typeof target === "string" ? target : target.provider;
|
||||
const instanceId =
|
||||
typeof target === "string"
|
||||
? defaultInstanceIdForDriver(provider)
|
||||
: (target.instanceId ?? defaultInstanceIdForDriver(provider));
|
||||
const targetKey = `instance:${instanceId}`;
|
||||
const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
);
|
||||
const update = capabilities.update;
|
||||
if (!update) {
|
||||
return yield* new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: "This provider does not support one-click updates.",
|
||||
});
|
||||
}
|
||||
|
||||
const setUpdateState = (state: ServerProviderUpdateState | null) =>
|
||||
providerRegistry.setProviderMaintenanceActionState({
|
||||
instanceId,
|
||||
action: "update",
|
||||
state,
|
||||
});
|
||||
const setQueuedState = setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
|
||||
function* () {
|
||||
const finish = (state: ServerProviderUpdateState) =>
|
||||
setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
|
||||
const startedAtRef = yield* Ref.make<string | null>(null);
|
||||
|
||||
const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
|
||||
function* () {
|
||||
const startedAt = yield* nowIso;
|
||||
yield* Ref.set(startedAtRef, startedAt);
|
||||
yield* setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "running",
|
||||
startedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runMaintenanceCommand(update.executable, update.args);
|
||||
const finishedAt = yield* nowIso;
|
||||
if (result.timedOut || result.exitCode !== 0) {
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: failureMessage(result),
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { verifiedProviders } = yield* verifyRefreshedProvider(
|
||||
provider,
|
||||
capabilities,
|
||||
instanceId,
|
||||
);
|
||||
const couldNotVerify = verifiedProviders.length === 0;
|
||||
const stillOutdated =
|
||||
couldNotVerify ||
|
||||
verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: stillOutdated ? "unchanged" : "succeeded",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: couldNotVerify
|
||||
? "Update command completed, but T3 Code could not verify the provider version."
|
||||
: stillOutdated
|
||||
? "Update command completed, but T3 Code still detects an outdated provider version."
|
||||
: "Provider updated.",
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
|
||||
function* (cause: Cause.Cause<unknown>) {
|
||||
const failure = Cause.squash(cause);
|
||||
const startedAt = yield* Ref.get(startedAtRef);
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt: yield* nowIso,
|
||||
message: failure instanceof Error ? failure.message : "Update command failed.",
|
||||
output: null,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
|
||||
},
|
||||
);
|
||||
|
||||
return yield* commandCoordinator
|
||||
.withCommandLock({
|
||||
targetKey,
|
||||
lockKey: update.lockKey,
|
||||
onQueued: setQueuedState,
|
||||
run: runProviderUpdate(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(ServerProviderUpdateError)(error)
|
||||
? new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: error.reason,
|
||||
})
|
||||
: error,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return ProviderMaintenanceRunner.of({
|
||||
updateProvider,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderMaintenanceRunner, make());
|
||||
@@ -12,6 +12,8 @@ import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
|
||||
@@ -182,6 +184,7 @@ export function buildBooleanOptionDescriptor(input: {
|
||||
}
|
||||
|
||||
export function buildServerProvider(input: {
|
||||
driver?: ProviderDriverKind;
|
||||
presentation: ServerProviderPresentation;
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
@@ -190,6 +193,13 @@ export function buildServerProvider(input: {
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProviderDraft {
|
||||
const versionAdvisory = input.driver
|
||||
? createProviderVersionAdvisory({
|
||||
driver: input.driver,
|
||||
currentVersion: input.probe.version,
|
||||
checkedAt: input.checkedAt,
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
@@ -206,16 +216,11 @@ export function buildServerProvider(input: {
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
...(versionAdvisory ? { versionAdvisory } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const collectStreamAsString = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, E> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
);
|
||||
collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));
|
||||
@@ -140,8 +140,10 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
}) => {
|
||||
const { updateState: _updateState, ...cacheableProvider } = input.provider;
|
||||
return writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(input.provider, null, 2)}\n`,
|
||||
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
|
||||
});
|
||||
};
|
||||
@@ -80,6 +80,7 @@ import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
@@ -517,6 +518,12 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
@@ -559,7 +566,6 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(OrchestrationEngineService)({
|
||||
getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 0 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
@@ -568,6 +574,7 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
@@ -576,6 +583,7 @@ const buildAppUnderTest = (options?: {
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
@@ -1910,6 +1918,42 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.removeKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
};
|
||||
const resolved: ResolvedKeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
keybindings: {
|
||||
removeKeybindingRule: () => Effect.succeed([resolved]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)),
|
||||
);
|
||||
|
||||
assert.deepEqual(response.issues, []);
|
||||
assert.deepEqual(response.keybindings, [resolved]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -77,8 +77,10 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -129,8 +131,10 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
@@ -152,7 +156,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
@@ -180,8 +183,10 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
@@ -191,7 +196,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
|
||||
@@ -287,7 +287,18 @@ it.effect("expands all-state pull request listing instead of relying on Bitbucke
|
||||
|
||||
it.effect("reads repository clone URLs and default branch", () => {
|
||||
const { layer } = makeLayer({
|
||||
response: () => Response.json(repositoryJson),
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "main" },
|
||||
name: "main",
|
||||
use_mainbranch: true,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -307,6 +318,86 @@ it.effect("reads repository clone URLs and default branch", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"prefers the Bitbucket branching model development branch as the default PR target",
|
||||
() => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "develop" },
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "develop");
|
||||
assert.deepStrictEqual(
|
||||
execute.mock.calls.map((call) => call[0].url).toSorted(),
|
||||
[
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code",
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
|
||||
].toSorted(),
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket development branch is invalid",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
is_valid: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket branching model is unavailable",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
request.url.endsWith("/branching-model")
|
||||
? Response.json({ error: { message: "Not found" } }, { status: 404 })
|
||||
: Response.json(repositoryJson),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("creates repositories through the Bitbucket REST API", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () => Response.json(repositoryJson),
|
||||
|
||||
@@ -65,6 +65,23 @@ const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
),
|
||||
});
|
||||
|
||||
const RawBitbucketBranchingModelSchema = Schema.Struct({
|
||||
development: Schema.optional(
|
||||
Schema.Struct({
|
||||
branch: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
),
|
||||
is_valid: Schema.optional(Schema.Boolean),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
use_mainbranch: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const BitbucketUserSchema = Schema.Struct({
|
||||
username: Schema.optional(TrimmedNonEmptyString),
|
||||
display_name: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -216,7 +233,7 @@ function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawBitbucketRepositorySchema>,
|
||||
raw: typeof RawBitbucketRepositorySchema.Type,
|
||||
): SourceControlRepositoryCloneUrls {
|
||||
const httpClone =
|
||||
raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
|
||||
@@ -230,6 +247,24 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
function defaultChangeRequestTargetBranch(input: {
|
||||
readonly repository: typeof RawBitbucketRepositorySchema.Type;
|
||||
readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
|
||||
}): string | null {
|
||||
const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
|
||||
const development = input.branchingModel?.development;
|
||||
if (!development || development.use_mainbranch === true || development.is_valid === false) {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
|
||||
if (developmentBranch.length === 0 || developmentBranch === "null") {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
return developmentBranch;
|
||||
}
|
||||
|
||||
function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
|
||||
const trimmed = originRemoteUrl?.trim() ?? "";
|
||||
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
|
||||
@@ -430,23 +465,32 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getRepository",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
);
|
||||
|
||||
const getRepository = (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly repository?: string;
|
||||
}) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"getRepository",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
}) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
|
||||
|
||||
const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getBranchingModel",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
|
||||
),
|
||||
),
|
||||
RawBitbucketBranchingModelSchema,
|
||||
);
|
||||
|
||||
const getRawPullRequestFromRepository = (
|
||||
@@ -628,7 +672,22 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
);
|
||||
}),
|
||||
getDefaultBranch: (input) =>
|
||||
getRepository(input).pipe(Effect.map((repository) => repository.mainbranch?.name ?? null)),
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((locator) =>
|
||||
Effect.all(
|
||||
{
|
||||
repository: getRepositoryFromLocator(locator),
|
||||
branchingModel: getBranchingModelFromLocator(locator).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
|
||||
),
|
||||
),
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.map(defaultChangeRequestTargetBranch),
|
||||
),
|
||||
// Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
|
||||
// an official checkout CLI. This provider-local path uses GitVcsDriver as a
|
||||
// narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
import { collectUint8StreamText } from "./collectUint8StreamText.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
describe("collectUint8StreamText", () => {
|
||||
it.effect("collects Uint8Array chunks into decoded text", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("hello "), encoder.encode("world")),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "hello world",
|
||||
bytes: 11,
|
||||
truncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("truncates by bytes and appends an optional marker once", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("abcdef"), encoder.encode("ghij")),
|
||||
maxBytes: 5,
|
||||
truncatedMarker: "[truncated]",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "abcde[truncated]",
|
||||
bytes: 5,
|
||||
truncated: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
export interface CollectedUint8StreamText {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface CollectState {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export const collectUint8StreamText = <E>(input: {
|
||||
readonly stream: Stream.Stream<Uint8Array, E>;
|
||||
readonly maxBytes?: number | undefined;
|
||||
readonly truncatedMarker?: string | null | undefined;
|
||||
}): Effect.Effect<CollectedUint8StreamText, E> => {
|
||||
const decoder = new TextDecoder();
|
||||
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
|
||||
return input.stream.pipe(
|
||||
Stream.runFold(
|
||||
(): CollectState => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk): CollectState => {
|
||||
if (state.truncated) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const remainingBytes = maxBytes - state.bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
return {
|
||||
...state,
|
||||
text: `${state.text}${truncatedMarker}`,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextChunk =
|
||||
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
|
||||
const bytes = state.bytes + nextChunk.byteLength;
|
||||
const truncated = chunk.byteLength > remainingBytes;
|
||||
|
||||
return {
|
||||
text: truncated ? `${text}${truncatedMarker}` : text,
|
||||
bytes,
|
||||
truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
|
||||
bytes: state.bytes,
|
||||
truncated: state.truncated,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export interface VcsProcessInput {
|
||||
readonly operation: string;
|
||||
@@ -86,44 +87,12 @@ export const collectText = Effect.fn("VcsProcess.collectText")(function* (input:
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) {
|
||||
const decoder = new TextDecoder();
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
let truncated = false;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
|
||||
|
||||
yield* Stream.runForEach(input.stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (truncated) return;
|
||||
|
||||
const remainingBytes = maxOutputBytes - bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
text += decoder.decode(nextChunk, { stream: true });
|
||||
bytes += nextChunk.byteLength;
|
||||
|
||||
if (chunk.byteLength > remainingBytes) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (!truncated) {
|
||||
text += decoder.decode();
|
||||
}
|
||||
|
||||
return { text, truncated } satisfies VcsProcessCollectedText;
|
||||
return yield* collectUint8StreamText({
|
||||
stream: input.stream,
|
||||
maxBytes: maxOutputBytes,
|
||||
truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
|
||||
});
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeVcsProcess")(function* () {
|
||||
|
||||
+38
-7
@@ -40,6 +40,7 @@ import {
|
||||
observeRpcStreamEffect,
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
|
||||
import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
|
||||
@@ -152,6 +153,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const config = yield* ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -236,9 +238,13 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
return Effect.gen(function* () {
|
||||
const workspaceRoot =
|
||||
event.payload.workspaceRoot ??
|
||||
(yield* orchestrationEngine.getReadModel()).projects.find(
|
||||
(project) => project.id === event.payload.projectId,
|
||||
)?.workspaceRoot ??
|
||||
Option.match(
|
||||
yield* projectionSnapshotQuery.getProjectShellById(event.payload.projectId),
|
||||
{
|
||||
onNone: () => null,
|
||||
onSome: (project) => project.workspaceRoot,
|
||||
},
|
||||
) ??
|
||||
null;
|
||||
if (workspaceRoot === null) {
|
||||
return event;
|
||||
@@ -252,7 +258,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
repositoryIdentity,
|
||||
},
|
||||
} satisfies OrchestrationEvent;
|
||||
});
|
||||
}).pipe(Effect.catch(() => Effect.succeed(event)));
|
||||
default:
|
||||
return Effect.succeed(event);
|
||||
}
|
||||
@@ -723,9 +729,16 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
),
|
||||
),
|
||||
orchestrationEngine
|
||||
.getReadModel()
|
||||
.pipe(Effect.map((readModel) => readModel.snapshotSequence)),
|
||||
projectionSnapshotQuery.getSnapshotSequence().pipe(
|
||||
Effect.map(({ snapshotSequence }) => snapshotSequence),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot sequence",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
@@ -774,6 +787,14 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
).pipe(Effect.map((providers) => ({ providers }))),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverUpdateProvider]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpdateProvider,
|
||||
providerMaintenanceRunner.updateProvider(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpsertKeybinding,
|
||||
@@ -783,6 +804,15 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverRemoveKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverRemoveKeybinding,
|
||||
Effect.gen(function* () {
|
||||
const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
|
||||
return { keybindings: keybindingsConfig, issues: [] };
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverGetSettings]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetSettings,
|
||||
@@ -1141,6 +1171,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session.sessionId).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(
|
||||
SourceControlDiscoveryLayer.layer.pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
@@ -23,7 +22,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import { type ReactNode, useLayoutEffect, useRef, useState } from "react";
|
||||
import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const HEIGHT_TRANSITION_FALLBACK_MS = 250;
|
||||
|
||||
export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [height, setHeight] = useState<number | null>(null);
|
||||
const [heightState, setHeightState] = useState<{
|
||||
readonly height: number | null;
|
||||
readonly isClipping: boolean;
|
||||
}>({ height: null, isClipping: false });
|
||||
|
||||
useEffect(() => {
|
||||
if (!heightState.isClipping) return;
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
setHeightState((currentState) =>
|
||||
currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
|
||||
);
|
||||
}, HEIGHT_TRANSITION_FALLBACK_MS);
|
||||
return () => window.clearTimeout(timeoutId);
|
||||
}, [heightState.height, heightState.isClipping]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = contentRef.current;
|
||||
@@ -14,7 +29,13 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
|
||||
const updateHeight = () => {
|
||||
const nextHeight = Math.ceil(element.scrollHeight || element.getBoundingClientRect().height);
|
||||
setHeight((currentHeight) => (currentHeight === nextHeight ? currentHeight : nextHeight));
|
||||
setHeightState((currentState) => {
|
||||
if (currentState.height === nextHeight) return currentState;
|
||||
return {
|
||||
height: nextHeight,
|
||||
isClipping: currentState.height !== null,
|
||||
};
|
||||
});
|
||||
};
|
||||
const cancelPendingFrames = () => {
|
||||
if (firstFrameId !== null) {
|
||||
@@ -50,8 +71,19 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="overflow-hidden transition-[height] duration-200 ease-out motion-reduce:transition-none"
|
||||
style={height === null ? undefined : { height }}
|
||||
data-slot="animated-height"
|
||||
className="transition-[height] duration-200 ease-out motion-reduce:transition-none"
|
||||
style={
|
||||
heightState.height === null
|
||||
? undefined
|
||||
: { height: heightState.height, overflow: heightState.isClipping ? "hidden" : "visible" }
|
||||
}
|
||||
onTransitionEnd={(event) => {
|
||||
if (event.target !== event.currentTarget || event.propertyName !== "height") return;
|
||||
setHeightState((currentState) =>
|
||||
currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div ref={contentRef}>{children}</div>
|
||||
</div>
|
||||
|
||||
@@ -211,6 +211,32 @@ function SuspenseShikiCodeBlock({
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<UncachedShikiCodeBlock
|
||||
code={code}
|
||||
language={language}
|
||||
themeName={themeName}
|
||||
cacheKey={cacheKey}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface UncachedShikiCodeBlockProps {
|
||||
code: string;
|
||||
language: string;
|
||||
themeName: DiffThemeName;
|
||||
cacheKey: string;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function UncachedShikiCodeBlock({
|
||||
code,
|
||||
language,
|
||||
themeName,
|
||||
cacheKey,
|
||||
isStreaming,
|
||||
}: UncachedShikiCodeBlockProps) {
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
|
||||
@@ -72,6 +72,7 @@ import {
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../pendingUserInput";
|
||||
import * as Effect from "effect/Effect";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectThreadsAcrossEnvironments,
|
||||
@@ -2845,7 +2846,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
prepareWorktree: {
|
||||
projectCwd: activeProject.cwd,
|
||||
baseBranch: baseBranchForWorktree,
|
||||
branch: buildTemporaryWorktreeBranchName(),
|
||||
branch: Effect.runSync(buildTemporaryWorktreeBranchName),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
@@ -161,6 +162,21 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
|
||||
switch (fileDiff.type) {
|
||||
case "new":
|
||||
return "text-[var(--diffs-addition-base)]";
|
||||
case "deleted":
|
||||
return "text-[var(--diffs-deletion-base)]";
|
||||
case "change":
|
||||
case "rename-pure":
|
||||
case "rename-changed":
|
||||
return "text-[var(--diffs-modified-base)]";
|
||||
default:
|
||||
return "text-muted-foreground/80";
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: DiffPanelMode;
|
||||
}
|
||||
@@ -174,6 +190,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState<ReadonlySet<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
@@ -317,6 +336,19 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (renderableFiles.length === 0) {
|
||||
setCollapsedDiffFileKeys((current) => (current.size === 0 ? current : new Set()));
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleFileKeys = new Set(renderableFiles.map(buildFileDiffRenderKey));
|
||||
setCollapsedDiffFileKeys((current) => {
|
||||
const next = new Set([...current].filter((fileKey) => visibleFileKeys.has(fileKey)));
|
||||
return next.size === current.size ? current : next;
|
||||
});
|
||||
}, [renderableFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
@@ -346,6 +378,17 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
const toggleDiffFileCollapsed = useCallback((fileKey: string) => {
|
||||
setCollapsedDiffFileKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(fileKey)) {
|
||||
next.delete(fileKey);
|
||||
} else {
|
||||
next.add(fileKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
@@ -620,11 +663,12 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
const collapsed = collapsedDiffFileKeys.has(fileKey);
|
||||
return (
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
className="diff-render-file group/diff-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
@@ -638,7 +682,30 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
renderHeaderPrefix={() => (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
getDiffCollapseIconClassName(fileDiff),
|
||||
)}
|
||||
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
|
||||
aria-expanded={!collapsed}
|
||||
title={collapsed ? "Expand diff" : "Collapse diff"}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleDiffFileCollapsed(fileKey);
|
||||
}}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRightIcon className="size-4" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
options={{
|
||||
collapsed,
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
|
||||
@@ -532,16 +532,20 @@ describe("Keybindings update toast", () => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows a toast for each consecutive keybinding update with no issues", async () => {
|
||||
it("coalesces rapid consecutive keybinding update toasts with no issues", async () => {
|
||||
const mounted = await mountApp();
|
||||
|
||||
try {
|
||||
sendServerConfigUpdatedPush([]);
|
||||
await waitForToast("Keybindings updated", 1);
|
||||
|
||||
// Each server push represents a distinct file change, so it should produce its own toast.
|
||||
// A single edit can produce several reload notifications as the direct update and
|
||||
// filesystem watcher settle, so avoid stacking identical success toasts.
|
||||
sendServerConfigUpdatedPush([]);
|
||||
await waitForToast("Keybindings updated", 2);
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
|
||||
const titles = queryToastTitles();
|
||||
expect(titles.filter((title) => title === "Keybindings updated")).toHaveLength(1);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@ import {
|
||||
keybindingValueForCommand,
|
||||
decodeProjectScriptKeybindingRule,
|
||||
} from "~/lib/projectScriptKeybindings";
|
||||
import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
} from "~/projectScripts";
|
||||
import { shortcutLabelForCommand } from "~/keybindings";
|
||||
import { isMacPlatform } from "~/lib/utils";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
@@ -96,57 +96,6 @@ interface ProjectScriptsControlProps {
|
||||
onDeleteScript: (scriptId: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(navigator.platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export default function ProjectScriptsControl({
|
||||
scripts,
|
||||
keybindings,
|
||||
@@ -186,7 +135,7 @@ export default function ProjectScriptsControl({
|
||||
setKeybinding("");
|
||||
return;
|
||||
}
|
||||
const next = keybindingFromEvent(event);
|
||||
const next = keybindingFromKeyboardEvent(event, navigator.platform);
|
||||
if (!next) return;
|
||||
setKeybinding(next);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,673 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectUpdatedProviderSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateSidebarPillView,
|
||||
getSingleProviderUpdateProgressToastView,
|
||||
hasOneClickUpdateProviderCandidate,
|
||||
isProviderUpdateCandidate,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateCandidate,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
|
||||
const checkedAt = "2026-04-23T10:00:00.000Z";
|
||||
const sessionStartedAt = "2026-04-23T09:59:00.000Z";
|
||||
const laterCheckedAt = "2026-04-23T10:01:00.000Z";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const instanceId = (value: string) => ProviderInstanceId.make(value);
|
||||
|
||||
function provider(input: {
|
||||
readonly driver: ReturnType<typeof ProviderDriverKind.make>;
|
||||
readonly instanceId?: ReturnType<typeof ProviderInstanceId.make>;
|
||||
readonly enabled?: boolean;
|
||||
readonly version?: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly canUpdate?: boolean;
|
||||
readonly updateCommand?: string | null;
|
||||
readonly updateState?: ServerProvider["updateState"];
|
||||
readonly advisoryStatus?: NonNullable<ServerProvider["versionAdvisory"]>["status"];
|
||||
}): ServerProvider {
|
||||
const result: ServerProvider = {
|
||||
instanceId: input.instanceId ?? instanceId(String(input.driver)),
|
||||
driver: input.driver,
|
||||
enabled: input.enabled ?? true,
|
||||
installed: true,
|
||||
version: input.version ?? "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
versionAdvisory: {
|
||||
status: input.advisoryStatus ?? "behind_latest",
|
||||
currentVersion: input.version ?? "1.0.0",
|
||||
latestVersion: "latestVersion" in input ? input.latestVersion : "1.1.0",
|
||||
updateCommand: "updateCommand" in input ? input.updateCommand : "npm install -g provider",
|
||||
canUpdate: input.canUpdate ?? true,
|
||||
checkedAt,
|
||||
message: "Update available.",
|
||||
},
|
||||
};
|
||||
|
||||
if (input.updateState) {
|
||||
return { ...result, updateState: input.updateState };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function updateCandidate(input: Parameters<typeof provider>[0]): ProviderUpdateCandidate {
|
||||
return provider(input) as ProviderUpdateCandidate;
|
||||
}
|
||||
|
||||
describe("provider update launch notification logic", () => {
|
||||
it("detects enabled providers with a latest-version advisory", () => {
|
||||
expect(isProviderUpdateCandidate(provider({ driver: driver("codex") }))).toBe(true);
|
||||
expect(isProviderUpdateCandidate(provider({ driver: driver("codex"), enabled: false }))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
isProviderUpdateCandidate(
|
||||
provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isProviderUpdateCandidate(provider({ driver: driver("codex"), latestVersion: null })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("deduplicates multi-instance provider candidates by driver", () => {
|
||||
expect(
|
||||
collectProviderUpdateCandidates([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: instanceId("codex_personal"),
|
||||
latestVersion: "1.1.0",
|
||||
}),
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: instanceId("codex"),
|
||||
latestVersion: "1.1.0",
|
||||
}),
|
||||
provider({ driver: driver("cursor"), latestVersion: "0.3.0" }),
|
||||
]),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("disables one-click updates when provider instances disagree on the update command", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_personal"),
|
||||
latestVersion: "2.1.123",
|
||||
});
|
||||
|
||||
expect(
|
||||
canOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
latestVersion: "2.1.123",
|
||||
canUpdate: true,
|
||||
updateCommand: "bun add -g @anthropic-ai/claude-code@latest",
|
||||
}),
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps one-click updates enabled when sibling instances are already current", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_personal"),
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "npm install -g @anthropic-ai/claude-code@latest",
|
||||
});
|
||||
|
||||
expect(
|
||||
hasOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
version: "2.1.123",
|
||||
latestVersion: "2.1.123",
|
||||
advisoryStatus: "current",
|
||||
canUpdate: false,
|
||||
updateCommand: null,
|
||||
}),
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
version: "2.1.123",
|
||||
latestVersion: "2.1.123",
|
||||
advisoryStatus: "current",
|
||||
canUpdate: false,
|
||||
updateCommand: null,
|
||||
}),
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the inline update action available while a provider update is already running", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(hasOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(true);
|
||||
expect(canOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(false);
|
||||
});
|
||||
|
||||
it("builds a notification key from provider latest versions", () => {
|
||||
const codex = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.0.0",
|
||||
latestVersion: "1.1.0",
|
||||
});
|
||||
const cursor = updateCandidate({
|
||||
driver: driver("cursor"),
|
||||
version: "0.2.0",
|
||||
latestVersion: "0.3.0",
|
||||
});
|
||||
|
||||
expect(providerUpdateNotificationKey([codex, cursor])).toBe("codex:1.1.0|cursor:0.3.0");
|
||||
expect(providerUpdateNotificationKey([])).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the same notification key while the published update version is unchanged", () => {
|
||||
const first = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.0.0",
|
||||
latestVersion: "1.2.0",
|
||||
});
|
||||
const second = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.2.0",
|
||||
});
|
||||
const nextPublishedVersion = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.3.0",
|
||||
});
|
||||
|
||||
expect(providerUpdateNotificationKey([first])).toBe(providerUpdateNotificationKey([second]));
|
||||
expect(providerUpdateNotificationKey([nextPublishedVersion])).not.toBe(
|
||||
providerUpdateNotificationKey([first]),
|
||||
);
|
||||
});
|
||||
|
||||
it("tracks updated provider snapshots by instance instead of collapsing to a sibling driver", () => {
|
||||
const targetInstanceId = instanceId("codex_personal");
|
||||
const siblingInstanceId = instanceId("codex");
|
||||
const updatedPersonal = provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: targetInstanceId,
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
});
|
||||
const currentDefaultSibling = provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: siblingInstanceId,
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: undefined,
|
||||
});
|
||||
|
||||
expect(
|
||||
collectUpdatedProviderSnapshots({
|
||||
results: [
|
||||
{
|
||||
status: "fulfilled",
|
||||
value: {
|
||||
providers: [updatedPersonal, currentDefaultSibling],
|
||||
},
|
||||
},
|
||||
],
|
||||
providerInstanceIds: new Set([targetInstanceId]),
|
||||
}),
|
||||
).toEqual([updatedPersonal]);
|
||||
});
|
||||
|
||||
it("describes a single one-click update", () => {
|
||||
const view = getProviderUpdateInitialToastView({
|
||||
updateProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
oneClickProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "initial",
|
||||
type: "warning",
|
||||
title: "Update Available: Codex v1.1.0",
|
||||
description: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("describes settings-only updates without one-click support", () => {
|
||||
const view = getProviderUpdateInitialToastView({
|
||||
updateProviders: [
|
||||
updateCandidate({ driver: driver("codex"), canUpdate: false }),
|
||||
updateCandidate({ driver: driver("cursor"), canUpdate: false }),
|
||||
],
|
||||
oneClickProviders: [],
|
||||
});
|
||||
|
||||
expect(view.description).toBe("Codex and Cursor can be updated from provider settings.");
|
||||
});
|
||||
|
||||
it("uses server update state for running progress", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "running",
|
||||
type: "loading",
|
||||
title: "Updating provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses server failure state for failed progress", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: "Provider update failed",
|
||||
description: "command failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves a single-provider completion view from the returned provider snapshot", () => {
|
||||
const view = getSingleProviderUpdateProgressToastView(
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: "Codex v1.1.0 update failed",
|
||||
description: "command failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unchanged providers actionable from settings", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "unchanged",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "still old",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "unchanged",
|
||||
type: "warning",
|
||||
title: "Provider still needs an update",
|
||||
description: "Cursor still appears outdated. Check provider settings for details.",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks progress succeeded once every attempted provider is no longer outdated", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: "Provider updated",
|
||||
description: "New sessions will use the updated provider.",
|
||||
dismissAfterVisibleMs: 3_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the updated version in the single-provider success toast title", () => {
|
||||
const view = getSingleProviderUpdateProgressToastView(
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: "Codex updated: v1.1.0",
|
||||
description: "New sessions will use the updated provider.",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a rejected RPC message for transport-level failures", () => {
|
||||
const results: PromiseSettledResult<unknown>[] = [
|
||||
{ status: "rejected", reason: new Error("WebSocket closed") },
|
||||
];
|
||||
|
||||
expect(firstRejectedProviderUpdateMessage(results)).toBe("WebSocket closed");
|
||||
expect(getProviderUpdateRejectedToastView(2, "WebSocket closed")).toMatchObject({
|
||||
phase: "failed",
|
||||
title: "Provider updates failed",
|
||||
description: "WebSocket closed",
|
||||
});
|
||||
});
|
||||
|
||||
it("collects only attempted provider snapshots from update responses", () => {
|
||||
const codex = provider({ driver: driver("codex") });
|
||||
const cursor = provider({ driver: driver("cursor") });
|
||||
const results: PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>[] = [
|
||||
{ status: "fulfilled", value: { providers: [codex, cursor] } },
|
||||
];
|
||||
|
||||
expect(
|
||||
collectUpdatedProviderSnapshots({
|
||||
results,
|
||||
providerInstanceIds: new Set([cursor.instanceId]),
|
||||
}),
|
||||
).toEqual([cursor]);
|
||||
});
|
||||
|
||||
it("summarizes active provider updates for the sidebar pill", () => {
|
||||
const view = getProviderUpdateSidebarPillView([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
tone: "loading",
|
||||
title: "Updating 2 providers",
|
||||
description: "Codex and Cursor updates are in progress.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the provider name for single active sidebar pill updates", () => {
|
||||
const view = getProviderUpdateSidebarPillView([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "loading:codex:running",
|
||||
tone: "loading",
|
||||
title: "Updating Codex",
|
||||
description: "Codex update in progress.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the provider name for single failed sidebar pill updates", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Update command exited with code 1.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",
|
||||
tone: "error",
|
||||
title: "Claude v1.1.0 update failed",
|
||||
description: "Update command exited with code 1.",
|
||||
dismissible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a short-lived success sidebar pill after a single provider update succeeds", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "succeeded:codex:2026-04-23T10:00:00.000Z:Provider updated.",
|
||||
tone: "success",
|
||||
title: "Codex updated: v1.1.0",
|
||||
description: "New sessions will use the updated provider.",
|
||||
dismissAfterVisibleMs: 3_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unchanged sidebar pill states dismissible", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "unchanged",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "still old",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "unchanged:cursor:2026-04-23T10:00:00.000Z:still old",
|
||||
tone: "warning",
|
||||
title: "Cursor still needs an update",
|
||||
dismissible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show sidebar terminal states from before the current app session", () => {
|
||||
expect(
|
||||
getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: "2026-04-23T10:00:01.000Z" },
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a newer success before falling back to an older failure", () => {
|
||||
const providers = [
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Update command exited with code 1.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.2.0",
|
||||
latestVersion: "1.2.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: laterCheckedAt,
|
||||
finishedAt: laterCheckedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
] satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
const successView = getProviderUpdateSidebarPillView(providers, {
|
||||
visibleAfterIso: sessionStartedAt,
|
||||
});
|
||||
expect(successView).toMatchObject({
|
||||
key: "succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated.",
|
||||
tone: "success",
|
||||
title: "Codex updated: v1.2.0",
|
||||
});
|
||||
|
||||
const failureView = getProviderUpdateSidebarPillView(providers, {
|
||||
visibleAfterIso: sessionStartedAt,
|
||||
dismissedKeys: new Set(["succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated."]),
|
||||
});
|
||||
expect(failureView).toMatchObject({
|
||||
key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",
|
||||
tone: "error",
|
||||
title: "Claude v1.1.0 update failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show a sidebar pill for passive update availability", () => {
|
||||
expect(
|
||||
getProviderUpdateSidebarPillView([
|
||||
provider({ driver: driver("codex"), canUpdate: true }),
|
||||
provider({ driver: driver("cursor"), canUpdate: false }),
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,537 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export type ProviderUpdateCandidate = ServerProvider & {
|
||||
readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {
|
||||
readonly status: "behind_latest";
|
||||
readonly latestVersion: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ProviderUpdateToastType = "warning" | "loading" | "error" | "success";
|
||||
export type ProviderUpdateToastPhase = "initial" | "running" | "failed" | "unchanged" | "succeeded";
|
||||
|
||||
export interface ProviderUpdateToastView {
|
||||
readonly phase: ProviderUpdateToastPhase;
|
||||
readonly type: ProviderUpdateToastType;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly dismissAfterVisibleMs?: number;
|
||||
}
|
||||
|
||||
export type ProviderUpdateSidebarPillTone = "loading" | "warning" | "error" | "success";
|
||||
|
||||
export interface ProviderUpdateSidebarPillView {
|
||||
readonly key: string;
|
||||
readonly tone: ProviderUpdateSidebarPillTone;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly dismissible?: boolean;
|
||||
readonly dismissAfterVisibleMs?: number;
|
||||
}
|
||||
|
||||
interface ProviderUpdateSidebarPillOptions {
|
||||
readonly visibleAfterIso?: string;
|
||||
readonly dismissedKeys?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const PROVIDER_UPDATE_SUCCESS_VISIBLE_MS = 3_000;
|
||||
|
||||
function formatVersion(value: string): string {
|
||||
return value.startsWith("v") ? value : `v${value}`;
|
||||
}
|
||||
|
||||
function chooseRepresentativeProvider(
|
||||
current: ServerProvider | undefined,
|
||||
candidate: ServerProvider,
|
||||
): ServerProvider {
|
||||
if (!current) {
|
||||
return candidate;
|
||||
}
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(candidate.driver);
|
||||
if (candidate.instanceId === defaultInstanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (current.instanceId === defaultInstanceId) {
|
||||
return current;
|
||||
}
|
||||
return candidate.checkedAt.localeCompare(current.checkedAt) >= 0 ? candidate : current;
|
||||
}
|
||||
|
||||
function dedupeProvidersByDriver<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {
|
||||
const latestProviderByDriver = new Map<ProviderDriverKind, T>();
|
||||
|
||||
for (const provider of providers) {
|
||||
latestProviderByDriver.set(
|
||||
provider.driver,
|
||||
chooseRepresentativeProvider(latestProviderByDriver.get(provider.driver), provider) as T,
|
||||
);
|
||||
}
|
||||
|
||||
return [...latestProviderByDriver.values()];
|
||||
}
|
||||
|
||||
function dedupeProvidersByInstanceId<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {
|
||||
const latestProviderByInstanceId = new Map<ProviderInstanceId, T>();
|
||||
|
||||
for (const provider of providers) {
|
||||
const current = latestProviderByInstanceId.get(provider.instanceId);
|
||||
if (!current || provider.checkedAt.localeCompare(current.checkedAt) >= 0) {
|
||||
latestProviderByInstanceId.set(provider.instanceId, provider);
|
||||
}
|
||||
}
|
||||
|
||||
return [...latestProviderByInstanceId.values()];
|
||||
}
|
||||
|
||||
function getProviderUpdatedTitle(provider: Pick<ServerProvider, "driver" | "version">): string {
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
return provider.version
|
||||
? `${providerName} updated: ${formatVersion(provider.version)}`
|
||||
: `${providerName} updated`;
|
||||
}
|
||||
|
||||
function getProviderUpdatedDescription(providerCount: number): string {
|
||||
return providerCount === 1
|
||||
? "New sessions will use the updated provider."
|
||||
: "New sessions will use the updated providers.";
|
||||
}
|
||||
|
||||
function getProviderFailedUpdateTitle(
|
||||
provider: Pick<ServerProvider, "driver" | "versionAdvisory">,
|
||||
): string {
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
const attemptedVersion = provider.versionAdvisory?.latestVersion;
|
||||
return attemptedVersion
|
||||
? `${providerName} ${formatVersion(attemptedVersion)} update failed`
|
||||
: `${providerName} update failed`;
|
||||
}
|
||||
|
||||
export function isProviderUpdateCandidate(
|
||||
provider: ServerProvider,
|
||||
): provider is ProviderUpdateCandidate {
|
||||
return (
|
||||
provider.enabled &&
|
||||
provider.versionAdvisory?.status === "behind_latest" &&
|
||||
provider.versionAdvisory.latestVersion !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function isProviderUpdateActive(provider: Pick<ServerProvider, "updateState">): boolean {
|
||||
return provider.updateState?.status === "queued" || provider.updateState?.status === "running";
|
||||
}
|
||||
|
||||
export function collectProviderUpdateCandidates(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ProviderUpdateCandidate[] {
|
||||
return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));
|
||||
}
|
||||
|
||||
export function hasOneClickUpdateProviderCandidate(
|
||||
candidate: ProviderUpdateCandidate,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): boolean {
|
||||
if (
|
||||
candidate.versionAdvisory.canUpdate !== true ||
|
||||
candidate.versionAdvisory.updateCommand === null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const driverProviders = providers.filter((provider) => provider.driver === candidate.driver);
|
||||
if (driverProviders.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const updateCommands = new Set<string>();
|
||||
for (const provider of driverProviders) {
|
||||
if (!isProviderUpdateCandidate(provider)) {
|
||||
continue;
|
||||
}
|
||||
const advisory = provider.versionAdvisory;
|
||||
if (!advisory || advisory.canUpdate !== true || advisory.updateCommand === null) {
|
||||
return false;
|
||||
}
|
||||
updateCommands.add(advisory.updateCommand);
|
||||
}
|
||||
|
||||
return updateCommands.size === 1;
|
||||
}
|
||||
|
||||
export function canOneClickUpdateProviderCandidate(
|
||||
candidate: ProviderUpdateCandidate,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): boolean {
|
||||
return (
|
||||
!isProviderUpdateActive(candidate) && hasOneClickUpdateProviderCandidate(candidate, providers)
|
||||
);
|
||||
}
|
||||
|
||||
export function providerUpdateNotificationKey(
|
||||
providers: ReadonlyArray<ProviderUpdateCandidate>,
|
||||
): string | null {
|
||||
const parts = dedupeProvidersByDriver(providers)
|
||||
.map((provider) => {
|
||||
const advisory = provider.versionAdvisory;
|
||||
return [provider.driver, advisory.latestVersion].join(":");
|
||||
})
|
||||
.toSorted();
|
||||
|
||||
return parts.length > 0 ? parts.join("|") : null;
|
||||
}
|
||||
|
||||
export function providerUpdateCandidateKey(provider: ProviderUpdateCandidate): string {
|
||||
return providerUpdateNotificationKey([provider])!;
|
||||
}
|
||||
|
||||
export function formatProviderList(providers: ReadonlyArray<Pick<ServerProvider, "driver">>) {
|
||||
const names = providers.map(
|
||||
(provider) => PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver,
|
||||
);
|
||||
if (names.length <= 2) {
|
||||
return names.join(" and ");
|
||||
}
|
||||
return `${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]}`;
|
||||
}
|
||||
|
||||
export function getProviderUpdateInitialToastView(input: {
|
||||
readonly updateProviders: ReadonlyArray<ProviderUpdateCandidate>;
|
||||
readonly oneClickProviders: ReadonlyArray<ProviderUpdateCandidate>;
|
||||
}): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "initial",
|
||||
type: "warning",
|
||||
title: getProviderUpdateInitialToastTitle(input.updateProviders),
|
||||
description:
|
||||
input.oneClickProviders.length > 0
|
||||
? "Install the update now or review provider settings."
|
||||
: `${formatProviderList(input.updateProviders)} can be updated from provider settings.`,
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateRunningToastView(providerCount: number): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "running",
|
||||
type: "loading",
|
||||
title: providerCount === 1 ? "Updating provider" : "Updating providers",
|
||||
description: "Running provider update command.",
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateRejectedToastView(
|
||||
providerCount: number,
|
||||
message: string,
|
||||
): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: providerCount === 1 ? "Provider update failed" : "Provider updates failed",
|
||||
description: message,
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateProgressToastView(input: {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly providerCount: number;
|
||||
}): ProviderUpdateToastView {
|
||||
const providers = dedupeProvidersByDriver(input.providers);
|
||||
const failedProviders = providers.filter((provider) => provider.updateState?.status === "failed");
|
||||
if (failedProviders.length > 0) {
|
||||
return {
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: failedProviders.length === 1 ? "Provider update failed" : "Provider updates failed",
|
||||
description: getFailedProviderUpdateDescription(failedProviders),
|
||||
};
|
||||
}
|
||||
|
||||
const unchangedProviders = providers.filter(
|
||||
(provider) => provider.updateState?.status === "unchanged",
|
||||
);
|
||||
if (unchangedProviders.length > 0) {
|
||||
return {
|
||||
phase: "unchanged",
|
||||
type: "warning",
|
||||
title:
|
||||
unchangedProviders.length === 1
|
||||
? "Provider still needs an update"
|
||||
: "Providers still need updates",
|
||||
description: `${formatProviderList(unchangedProviders)} ${
|
||||
unchangedProviders.length === 1 ? "still appears" : "still appear"
|
||||
} outdated. Check provider settings for details.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (providers.some(isProviderUpdateActive)) {
|
||||
return getProviderUpdateRunningToastView(input.providerCount);
|
||||
}
|
||||
|
||||
const hasCompleteProviderSnapshots = providers.length >= input.providerCount;
|
||||
const allProvidersUpdated =
|
||||
hasCompleteProviderSnapshots &&
|
||||
providers.every(
|
||||
(provider) =>
|
||||
provider.updateState?.status === "succeeded" || !isProviderUpdateCandidate(provider),
|
||||
);
|
||||
if (allProvidersUpdated) {
|
||||
return {
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: input.providerCount === 1 ? "Provider updated" : "Provider updates finished",
|
||||
description: getProviderUpdatedDescription(input.providerCount),
|
||||
dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,
|
||||
};
|
||||
}
|
||||
|
||||
return getProviderUpdateRunningToastView(input.providerCount);
|
||||
}
|
||||
|
||||
export function getSingleProviderUpdateProgressToastView(
|
||||
provider: ServerProvider,
|
||||
): ProviderUpdateToastView {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [provider],
|
||||
providerCount: 1,
|
||||
});
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
|
||||
switch (view.phase) {
|
||||
case "running":
|
||||
return {
|
||||
...view,
|
||||
title: `Updating ${providerName}`,
|
||||
};
|
||||
case "failed":
|
||||
return {
|
||||
...view,
|
||||
title: getProviderFailedUpdateTitle(provider),
|
||||
};
|
||||
case "unchanged":
|
||||
return {
|
||||
...view,
|
||||
title: `${providerName} still needs an update`,
|
||||
};
|
||||
case "succeeded":
|
||||
return {
|
||||
...view,
|
||||
title: getProviderUpdatedTitle(provider),
|
||||
};
|
||||
default:
|
||||
return view;
|
||||
}
|
||||
}
|
||||
|
||||
export function collectUpdatedProviderSnapshots(input: {
|
||||
readonly results: ReadonlyArray<
|
||||
PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>
|
||||
>;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
}): ServerProvider[] {
|
||||
const matchedProviders: ServerProvider[] = [];
|
||||
|
||||
for (const result of input.results) {
|
||||
if (result.status !== "fulfilled") {
|
||||
continue;
|
||||
}
|
||||
for (const provider of result.value.providers) {
|
||||
if (input.providerInstanceIds.has(provider.instanceId)) {
|
||||
matchedProviders.push(provider);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeProvidersByInstanceId(matchedProviders);
|
||||
}
|
||||
|
||||
export function firstRejectedProviderUpdateMessage(
|
||||
results: ReadonlyArray<PromiseSettledResult<unknown>>,
|
||||
): string | null {
|
||||
const rejected = results.find((result) => result.status === "rejected");
|
||||
if (!rejected) {
|
||||
return null;
|
||||
}
|
||||
return rejected.reason instanceof Error ? rejected.reason.message : "Provider update failed.";
|
||||
}
|
||||
|
||||
function getUpdateFinishedAt(provider: ServerProvider): string | null {
|
||||
return provider.updateState?.finishedAt ?? null;
|
||||
}
|
||||
|
||||
function isRecentTerminalProvider(
|
||||
provider: ServerProvider,
|
||||
visibleAfterIso: string | undefined,
|
||||
): boolean {
|
||||
const status = provider.updateState?.status;
|
||||
if (status !== "failed" && status !== "unchanged" && status !== "succeeded") {
|
||||
return false;
|
||||
}
|
||||
if (visibleAfterIso === undefined) {
|
||||
return true;
|
||||
}
|
||||
const finishedAt = getUpdateFinishedAt(provider);
|
||||
return finishedAt !== null && finishedAt >= visibleAfterIso;
|
||||
}
|
||||
|
||||
function latestFinishedAtForProviders(providers: ReadonlyArray<ServerProvider>): string | null {
|
||||
return providers.reduce<string | null>((latest, provider) => {
|
||||
const finishedAt = getUpdateFinishedAt(provider);
|
||||
if (finishedAt === null) {
|
||||
return latest;
|
||||
}
|
||||
return latest === null || finishedAt > latest ? finishedAt : latest;
|
||||
}, null);
|
||||
}
|
||||
|
||||
export function getProviderUpdateSidebarPillView(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
options?: ProviderUpdateSidebarPillOptions,
|
||||
): ProviderUpdateSidebarPillView | null {
|
||||
const dedupedProviders = dedupeProvidersByDriver(providers);
|
||||
const activeProviders = dedupedProviders.filter(isProviderUpdateActive);
|
||||
if (activeProviders.length > 0) {
|
||||
const activeProvider = activeProviders[0]!;
|
||||
const activeProviderName =
|
||||
PROVIDER_DISPLAY_NAMES[activeProvider.driver] ?? activeProvider.driver;
|
||||
return {
|
||||
key: `loading:${activeProviders
|
||||
.map((provider) => `${provider.driver}:${provider.updateState?.status ?? "idle"}`)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "loading",
|
||||
title:
|
||||
activeProviders.length === 1
|
||||
? `Updating ${activeProviderName}`
|
||||
: `Updating ${activeProviders.length} providers`,
|
||||
description:
|
||||
activeProviders.length === 1
|
||||
? `${formatProviderList(activeProviders)} update in progress.`
|
||||
: `${formatProviderList(activeProviders)} updates are in progress.`,
|
||||
};
|
||||
}
|
||||
|
||||
const recentTerminalProviders = dedupedProviders.filter((provider) =>
|
||||
isRecentTerminalProvider(provider, options?.visibleAfterIso),
|
||||
);
|
||||
const terminalCandidates: ProviderUpdateSidebarPillView[] = [];
|
||||
|
||||
const failedProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "failed",
|
||||
);
|
||||
if (failedProviders.length > 0) {
|
||||
const failedProvider = failedProviders[0]!;
|
||||
terminalCandidates.push({
|
||||
key: `failed:${failedProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "error",
|
||||
title:
|
||||
failedProviders.length === 1
|
||||
? getProviderFailedUpdateTitle(failedProvider)
|
||||
: `${failedProviders.length} provider updates failed`,
|
||||
description: getFailedProviderUpdateDescription(failedProviders),
|
||||
dismissible: true,
|
||||
});
|
||||
}
|
||||
|
||||
const unchangedProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "unchanged",
|
||||
);
|
||||
if (unchangedProviders.length > 0) {
|
||||
const unchangedProvider = unchangedProviders[0]!;
|
||||
const unchangedProviderName =
|
||||
PROVIDER_DISPLAY_NAMES[unchangedProvider.driver] ?? unchangedProvider.driver;
|
||||
terminalCandidates.push({
|
||||
key: `unchanged:${unchangedProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "warning",
|
||||
title:
|
||||
unchangedProviders.length === 1
|
||||
? `${unchangedProviderName} still needs an update`
|
||||
: `${unchangedProviders.length} providers still need updates`,
|
||||
description: `${formatProviderList(unchangedProviders)} ${
|
||||
unchangedProviders.length === 1 ? "still appears" : "still appear"
|
||||
} outdated. Review provider settings for details.`,
|
||||
dismissible: true,
|
||||
});
|
||||
}
|
||||
|
||||
const succeededProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "succeeded",
|
||||
);
|
||||
if (succeededProviders.length > 0) {
|
||||
const succeededProvider = succeededProviders[0]!;
|
||||
terminalCandidates.push({
|
||||
key: `succeeded:${succeededProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "success",
|
||||
title:
|
||||
succeededProviders.length === 1
|
||||
? getProviderUpdatedTitle(succeededProvider)
|
||||
: `${succeededProviders.length} providers updated`,
|
||||
description: getProviderUpdatedDescription(succeededProviders.length),
|
||||
dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
terminalCandidates
|
||||
.toSorted((left, right) => {
|
||||
const leftProviders =
|
||||
left.tone === "error"
|
||||
? failedProviders
|
||||
: left.tone === "warning"
|
||||
? unchangedProviders
|
||||
: succeededProviders;
|
||||
const rightProviders =
|
||||
right.tone === "error"
|
||||
? failedProviders
|
||||
: right.tone === "warning"
|
||||
? unchangedProviders
|
||||
: succeededProviders;
|
||||
const leftFinishedAt = latestFinishedAtForProviders(leftProviders) ?? "";
|
||||
const rightFinishedAt = latestFinishedAtForProviders(rightProviders) ?? "";
|
||||
return rightFinishedAt.localeCompare(leftFinishedAt);
|
||||
})
|
||||
.find((candidate) => !options?.dismissedKeys?.has(candidate.key)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function getProviderUpdateInitialToastTitle(
|
||||
providers: ReadonlyArray<ProviderUpdateCandidate>,
|
||||
): string {
|
||||
if (providers.length === 1) {
|
||||
const provider = providers[0]!;
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
return `Update Available: ${providerName} ${formatVersion(provider.versionAdvisory.latestVersion)}`;
|
||||
}
|
||||
return `Updates Available: ${providers.length} providers`;
|
||||
}
|
||||
|
||||
function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvider>): string {
|
||||
if (providers.length === 1) {
|
||||
const provider = providers[0]!;
|
||||
if (provider.updateState?.message) {
|
||||
return provider.updateState.message;
|
||||
}
|
||||
}
|
||||
return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { ensureLocalApi } from "../localApi";
|
||||
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
|
||||
import { useServerProviders } from "../rpc/serverState";
|
||||
import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectUpdatedProviderSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateRunningToastView,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateToastView,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
|
||||
const seenProviderUpdateNotificationKeys = new Set<string>();
|
||||
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
type ActiveProviderUpdateToast =
|
||||
| { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
|
||||
| {
|
||||
readonly kind: "update";
|
||||
readonly key: string;
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
readonly providerCount: number;
|
||||
};
|
||||
|
||||
function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
|
||||
|
||||
if (!ProviderIcon) {
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<ProviderIcon aria-hidden="true" className="size-4" />
|
||||
<span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
|
||||
<DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function updateProviderUpdateToast(input: {
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly view: ProviderUpdateToastView;
|
||||
readonly openSettings: () => void;
|
||||
}) {
|
||||
if (input.view.type === "loading" || input.view.type === "success") {
|
||||
toastManager.update(input.toastId, {
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.update(
|
||||
input.toastId,
|
||||
stackedThreadToast({
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
actionProps: {
|
||||
children: "Settings",
|
||||
onClick: input.openSettings,
|
||||
},
|
||||
actionVariant: "outline",
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
|
||||
return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
|
||||
}
|
||||
|
||||
export function ProviderUpdateLaunchNotification() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
|
||||
const { dismissedNotificationKeys, dismissNotificationKey } =
|
||||
useDismissedProviderUpdateNotificationKeys();
|
||||
|
||||
const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
|
||||
const notificationKey = useMemo(
|
||||
() => providerUpdateNotificationKey(updateProviders),
|
||||
[updateProviders],
|
||||
);
|
||||
const oneClickProviders = useMemo(
|
||||
() =>
|
||||
updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
|
||||
[providers, updateProviders],
|
||||
);
|
||||
|
||||
const openProviderSettings = useCallback(
|
||||
(toastId?: ProviderUpdateToastId) => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (toastId !== undefined) {
|
||||
toastManager.close(toastId);
|
||||
} else if (activeToast) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
}
|
||||
if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
void navigate({ to: "/settings/providers" });
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind !== "update") {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeProviders = providers.filter((provider) =>
|
||||
activeToast.providerInstanceIds.has(provider.instanceId),
|
||||
);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: activeProviders,
|
||||
providerCount: activeToast.providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId: activeToast.toastId,
|
||||
view,
|
||||
openSettings: () => openProviderSettings(activeToast.toastId),
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
}, [providers, openProviderSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
|
||||
if (
|
||||
!notificationKey ||
|
||||
dismissedNotificationKeys.has(notificationKey) ||
|
||||
seenProviderUpdateNotificationKeys.has(notificationKey) ||
|
||||
activeToastRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
seenProviderUpdateNotificationKeys.add(notificationKey);
|
||||
|
||||
const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
|
||||
|
||||
let toastId!: ProviderUpdateToastId;
|
||||
let updateStarted = false;
|
||||
const openSettings = () => openProviderSettings(toastId);
|
||||
const dismissPrompt = () => {
|
||||
dismissNotificationKey(notificationKey);
|
||||
};
|
||||
|
||||
const runUpdates = () => {
|
||||
if (updateStarted || oneClickProviders.length === 0) {
|
||||
return;
|
||||
}
|
||||
updateStarted = true;
|
||||
|
||||
const providerCount = oneClickProviders.length;
|
||||
const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
|
||||
activeToastRef.current = {
|
||||
kind: "update",
|
||||
key: notificationKey,
|
||||
toastId,
|
||||
providerInstanceIds,
|
||||
providerCount,
|
||||
};
|
||||
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRunningToastView(providerCount),
|
||||
openSettings,
|
||||
});
|
||||
|
||||
void Promise.allSettled(
|
||||
oneClickProviders.map(async (provider) =>
|
||||
ensureLocalApi().server.updateProvider({
|
||||
provider: provider.driver,
|
||||
instanceId: provider.instanceId,
|
||||
}),
|
||||
),
|
||||
).then((results) => {
|
||||
const activeUpdateToast = activeToastRef.current;
|
||||
if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
|
||||
if (rejectedMessage) {
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRejectedToastView(providerCount, rejectedMessage),
|
||||
openSettings,
|
||||
});
|
||||
activeToastRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
|
||||
results,
|
||||
providerInstanceIds,
|
||||
});
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: updatedProviderSnapshots,
|
||||
providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view,
|
||||
openSettings,
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
toastId = toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: initialView.type,
|
||||
title: initialView.title,
|
||||
description: initialView.description,
|
||||
timeout: 0,
|
||||
actionProps:
|
||||
oneClickProviders.length > 0
|
||||
? {
|
||||
children: "Update",
|
||||
onClick: runUpdates,
|
||||
}
|
||||
: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
|
||||
data: {
|
||||
leadingIcon:
|
||||
updateProviders.length === 1 ? (
|
||||
<ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
|
||||
) : undefined,
|
||||
hideCopyButton: true,
|
||||
onClose: dismissPrompt,
|
||||
...(oneClickProviders.length > 0
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
secondaryActionVariant: "outline" as const,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
|
||||
}, [
|
||||
dismissNotificationKey,
|
||||
dismissedNotificationKeys,
|
||||
notificationKey,
|
||||
oneClickProviders,
|
||||
openProviderSettings,
|
||||
updateProviders,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -185,6 +185,7 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
@@ -2434,6 +2435,7 @@ const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
|
||||
return (
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarProviderUpdatePill />
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
|
||||
@@ -87,6 +87,8 @@ interface TimelineRowSharedState {
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
|
||||
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Props (public API)
|
||||
@@ -261,8 +263,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
maintainVisibleContentPosition
|
||||
onScroll={handleScroll}
|
||||
className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
|
||||
ListHeaderComponent={<div className="h-3 sm:h-4" />}
|
||||
ListFooterComponent={<div className="h-3 sm:h-4" />}
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
</TimelineRowCtx.Provider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildKeybindingRows,
|
||||
buildKeybindingCommandOptions,
|
||||
buildWhenVariableOptions,
|
||||
commandLabel,
|
||||
keybindingConflictLabels,
|
||||
keybindingFromKeyboardEvent,
|
||||
parseWhenExpressionDraft,
|
||||
shortcutToKeybindingInput,
|
||||
unknownWhenVariables,
|
||||
whenAstToExpression,
|
||||
} from "./KeybindingsSettings.logic";
|
||||
|
||||
describe("KeybindingsSettings.logic", () => {
|
||||
it("builds searchable rows with readable key and when values", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"terminal",
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
command: "terminal.toggle",
|
||||
key: "mod+j",
|
||||
when: "!terminalFocus",
|
||||
defaultKey: "mod+j",
|
||||
defaultWhen: "",
|
||||
source: "Custom",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures platform-specific mod shortcuts", () => {
|
||||
expect(
|
||||
keybindingFromKeyboardEvent(
|
||||
{ key: "K", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true },
|
||||
"MacIntel",
|
||||
),
|
||||
).toBe("mod+shift+k");
|
||||
expect(
|
||||
keybindingFromKeyboardEvent(
|
||||
{ key: "K", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true },
|
||||
"Win32",
|
||||
),
|
||||
).toBe("mod+shift+k");
|
||||
});
|
||||
|
||||
it("serializes shortcuts and when expressions for upserts", () => {
|
||||
expect(
|
||||
shortcutToKeybindingInput({
|
||||
key: " ",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: true,
|
||||
shiftKey: false,
|
||||
}),
|
||||
).toBe("mod+alt+space");
|
||||
|
||||
expect(
|
||||
whenAstToExpression({
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "editorFocus" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
}),
|
||||
).toBe("editorFocus && !terminalFocus");
|
||||
|
||||
expect(parseWhenExpressionDraft("editorFocus && (!terminalFocus || modelPickerOpen)")).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "editorFocus" },
|
||||
right: {
|
||||
type: "or",
|
||||
left: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
right: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
|
||||
ok: false,
|
||||
message: "Use variables with !, &&, ||, and parentheses.",
|
||||
});
|
||||
|
||||
expect(parseWhenExpressionDraft("!(terminalFocus || modelPickerOpen)")).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
type: "not",
|
||||
node: {
|
||||
type: "or",
|
||||
left: { type: "identifier", name: "terminalFocus" },
|
||||
right: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("formats static and project script command labels", () => {
|
||||
expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle");
|
||||
expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db");
|
||||
});
|
||||
|
||||
it("builds known when variable options from defaults without frontend labels", () => {
|
||||
const options = buildWhenVariableOptions();
|
||||
|
||||
expect(options).toEqual(
|
||||
expect.arrayContaining(["terminalFocus", "terminalOpen", "modelPickerOpen", "true", "false"]),
|
||||
);
|
||||
expect(options).not.toContain("customModeActive");
|
||||
});
|
||||
|
||||
it("builds command options from defaults and resolved project bindings", () => {
|
||||
const options = buildKeybindingCommandOptions([
|
||||
{
|
||||
command: "script.setup-db.run",
|
||||
shortcut: {
|
||||
key: "r",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig);
|
||||
|
||||
expect(options).toEqual(expect.arrayContaining(["chat.new", "script.setup-db.run"]));
|
||||
});
|
||||
|
||||
it("reports unknown when variables without rejecting parseable expressions", () => {
|
||||
const parsed = parseWhenExpressionDraft("!terminalFocus && terminalFoc");
|
||||
|
||||
expect(parsed.ok).toBe(true);
|
||||
expect(unknownWhenVariables(parsed.ok ? parsed.value : undefined)).toEqual(["terminalFoc"]);
|
||||
});
|
||||
|
||||
it("marks each default shortcut for multi-binding commands as default", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "o",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"",
|
||||
);
|
||||
|
||||
expect(rows.map((row) => row.source)).toEqual(["Default", "Default"]);
|
||||
});
|
||||
|
||||
it("reports conflicting shortcuts that share an active when context", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "chat.newLocal",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"",
|
||||
);
|
||||
|
||||
expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]);
|
||||
expect(
|
||||
keybindingConflictLabels(rows, {
|
||||
rowId: rows[0]?.id ?? "",
|
||||
key: "mod+n",
|
||||
when: "",
|
||||
}),
|
||||
).toEqual(["Chat: New Local"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingRule,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
parseKeybindingWhenExpression,
|
||||
} from "@t3tools/shared/keybindings";
|
||||
|
||||
import { isMacPlatform } from "../../lib/utils";
|
||||
|
||||
export type KeybindingSource = "Default" | "Custom" | "Project";
|
||||
|
||||
export interface KeybindingRow {
|
||||
readonly id: string;
|
||||
readonly command: KeybindingCommand;
|
||||
readonly key: string;
|
||||
readonly when: string;
|
||||
readonly source: KeybindingSource;
|
||||
readonly defaultKey: string | null;
|
||||
readonly defaultWhen: string;
|
||||
readonly binding: ResolvedKeybindingRule;
|
||||
readonly conflicts: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export type WhenVariableOption = string;
|
||||
export type KeybindingCommandOption = KeybindingCommand;
|
||||
|
||||
const CORE_WHEN_VARIABLES = ["terminalFocus", "terminalOpen", "true", "false"] as const;
|
||||
|
||||
const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
|
||||
for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
|
||||
collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
|
||||
}
|
||||
|
||||
export const DEFAULT_WHEN_VARIABLE =
|
||||
[...DEFAULT_WHEN_VARIABLES].find(
|
||||
(identifier) => identifier !== "true" && identifier !== "false",
|
||||
) ?? "terminalFocus";
|
||||
const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
|
||||
|
||||
export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
|
||||
const parts: string[] = [];
|
||||
if (shortcut.modKey) parts.push("mod");
|
||||
if (shortcut.metaKey) parts.push("meta");
|
||||
if (shortcut.ctrlKey) parts.push("ctrl");
|
||||
if (shortcut.altKey) parts.push("alt");
|
||||
if (shortcut.shiftKey) parts.push("shift");
|
||||
parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
|
||||
if (!node) return "";
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
return node.name;
|
||||
case "not":
|
||||
return `!${wrapWhenExpression(node.node)}`;
|
||||
case "and":
|
||||
return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
|
||||
case "or":
|
||||
return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function wrapWhenExpression(node: KeybindingWhenNode): string {
|
||||
if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
|
||||
return `(${whenAstToExpression(node)})`;
|
||||
}
|
||||
|
||||
export function parseWhenExpressionDraft(
|
||||
expression: string,
|
||||
): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
|
||||
const trimmed = expression.trim();
|
||||
if (trimmed.length === 0) return { ok: true, value: undefined };
|
||||
|
||||
const ast = parseKeybindingWhenExpression(trimmed);
|
||||
if (!ast) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Use variables with !, &&, ||, and parentheses.",
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, value: ast };
|
||||
}
|
||||
|
||||
function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
|
||||
if (String(binding.command).startsWith("script.")) {
|
||||
return "Project";
|
||||
}
|
||||
|
||||
const bindingKey = shortcutToKeybindingInput(binding.shortcut);
|
||||
const bindingWhen = whenAstToExpression(binding.whenAst);
|
||||
const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
|
||||
(entry) =>
|
||||
entry.command === binding.command &&
|
||||
shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
|
||||
whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
);
|
||||
|
||||
return isDefault ? "Default" : "Custom";
|
||||
}
|
||||
|
||||
function defaultBindingForBinding(
|
||||
binding: ResolvedKeybindingRule,
|
||||
): ResolvedKeybindingRule | undefined {
|
||||
const bindingKey = shortcutToKeybindingInput(binding.shortcut);
|
||||
const bindingWhen = whenAstToExpression(binding.whenAst);
|
||||
|
||||
return (
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find(
|
||||
(entry) =>
|
||||
entry.command === binding.command &&
|
||||
shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
|
||||
whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
) ??
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find(
|
||||
(entry) =>
|
||||
entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
) ??
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
|
||||
);
|
||||
}
|
||||
|
||||
function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
|
||||
return `${command}\u0000${key}\u0000${when}`;
|
||||
}
|
||||
|
||||
function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
|
||||
return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
|
||||
}
|
||||
|
||||
export function keybindingConflictLabels(
|
||||
rows: ReadonlyArray<KeybindingRow>,
|
||||
input: { readonly rowId: string; readonly key: string; readonly when: string },
|
||||
): ReadonlyArray<string> {
|
||||
if (input.key.trim().length === 0) return [];
|
||||
const conflicts = rows
|
||||
.filter(
|
||||
(candidate) =>
|
||||
candidate.id !== input.rowId &&
|
||||
candidate.key === input.key &&
|
||||
conflictsWithWhen(candidate.when, input.when),
|
||||
)
|
||||
.map((candidate) => commandLabel(candidate.command));
|
||||
return [...new Set(conflicts)].toSorted();
|
||||
}
|
||||
|
||||
export function buildKeybindingRows(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
query: string,
|
||||
): ReadonlyArray<KeybindingRow> {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const rows = keybindings.map((binding, index) => {
|
||||
const defaultBinding = defaultBindingForBinding(binding);
|
||||
const key = shortcutToKeybindingInput(binding.shortcut);
|
||||
const when = whenAstToExpression(binding.whenAst);
|
||||
return {
|
||||
id: `${keybindingRowId(binding.command, key, when)}\u0000${index}`,
|
||||
command: binding.command,
|
||||
key,
|
||||
when,
|
||||
source: sourceForBinding(binding),
|
||||
defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
|
||||
defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
|
||||
binding,
|
||||
conflicts: [],
|
||||
} satisfies KeybindingRow;
|
||||
});
|
||||
|
||||
const rowsWithConflicts = rows.map((row) => {
|
||||
const conflicts = keybindingConflictLabels(rows, {
|
||||
rowId: row.id,
|
||||
key: row.key,
|
||||
when: row.when,
|
||||
});
|
||||
return conflicts.length > 0
|
||||
? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
|
||||
: row;
|
||||
});
|
||||
|
||||
rowsWithConflicts.sort((left, right) => {
|
||||
const commandCompare = left.command.localeCompare(right.command);
|
||||
if (commandCompare !== 0) return commandCompare;
|
||||
return left.key.localeCompare(right.key);
|
||||
});
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return rowsWithConflicts;
|
||||
}
|
||||
|
||||
return rowsWithConflicts.filter((row) => {
|
||||
return (
|
||||
row.command.toLowerCase().includes(normalizedQuery) ||
|
||||
row.key.toLowerCase().includes(normalizedQuery) ||
|
||||
row.when.toLowerCase().includes(normalizedQuery) ||
|
||||
row.source.toLowerCase().includes(normalizedQuery)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function collectWhenIdentifiersFromNode(
|
||||
node: KeybindingWhenNode | undefined,
|
||||
identifiers: Set<string>,
|
||||
): void {
|
||||
if (!node) return;
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
identifiers.add(node.name);
|
||||
return;
|
||||
case "not":
|
||||
collectWhenIdentifiersFromNode(node.node, identifiers);
|
||||
return;
|
||||
case "and":
|
||||
case "or":
|
||||
collectWhenIdentifiersFromNode(node.left, identifiers);
|
||||
collectWhenIdentifiersFromNode(node.right, identifiers);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function isKnownWhenVariable(identifier: string): boolean {
|
||||
return KNOWN_WHEN_VARIABLES.has(identifier);
|
||||
}
|
||||
|
||||
export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
|
||||
const identifiers = new Set<string>();
|
||||
collectWhenIdentifiersFromNode(node, identifiers);
|
||||
return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
|
||||
}
|
||||
|
||||
export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
|
||||
return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
|
||||
const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
|
||||
const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
|
||||
right as (typeof CORE_WHEN_VARIABLES)[number],
|
||||
);
|
||||
if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
|
||||
return (
|
||||
(leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
|
||||
(rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
|
||||
);
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
});
|
||||
}
|
||||
|
||||
export function buildKeybindingCommandOptions(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
): ReadonlyArray<KeybindingCommandOption> {
|
||||
const commands = new Set<KeybindingCommand>();
|
||||
for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
|
||||
commands.add(binding.command);
|
||||
}
|
||||
for (const binding of keybindings) {
|
||||
commands.add(binding.command);
|
||||
}
|
||||
return [...commands].toSorted((left, right) =>
|
||||
commandLabel(left).localeCompare(commandLabel(right)),
|
||||
);
|
||||
}
|
||||
|
||||
export function commandLabel(command: KeybindingCommand): string {
|
||||
const raw = String(command);
|
||||
if (raw.startsWith("script.") && raw.endsWith(".run")) {
|
||||
return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
|
||||
}
|
||||
return raw.split(".").map(titleCaseCommandSegment).join(": ");
|
||||
}
|
||||
|
||||
function titleCaseCommandSegment(segment: string): string {
|
||||
return segment
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.split(/[-_\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (/^f\d{1,2}$/.test(normalized)) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function keybindingFromKeyboardEvent(
|
||||
event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
|
||||
platform: string,
|
||||
): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDownIcon, PlusIcon, Trash2Icon, XIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowUpCircleIcon,
|
||||
ChevronDownIcon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
@@ -13,12 +22,15 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
|
||||
import { normalizeProviderAccentColor } from "../../providerInstances";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import type { DriverOption } from "./providerDriverMeta";
|
||||
import { ProviderSettingsForm } from "./ProviderSettingsForm";
|
||||
@@ -26,6 +38,7 @@ import { ProviderModelsSection } from "./ProviderModelsSection";
|
||||
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import {
|
||||
getProviderVersionAdvisoryPresentation,
|
||||
PROVIDER_STATUS_STYLES,
|
||||
getProviderSummary,
|
||||
getProviderVersionLabel,
|
||||
@@ -405,6 +418,8 @@ interface ProviderInstanceCardProps {
|
||||
readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onRunUpdate?: (() => void) | undefined;
|
||||
readonly isUpdating?: boolean | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,6 +462,8 @@ export function ProviderInstanceCard({
|
||||
onHiddenModelsChange,
|
||||
onFavoriteModelsChange,
|
||||
onModelOrderChange,
|
||||
onRunUpdate,
|
||||
isUpdating = false,
|
||||
}: ProviderInstanceCardProps) {
|
||||
const enabled = instance.enabled ?? true;
|
||||
// The server-reported status wins when present; otherwise fall back to
|
||||
@@ -464,10 +481,30 @@ export function ProviderInstanceCard({
|
||||
: null;
|
||||
const summary = rawSummary;
|
||||
const versionLabel = getProviderVersionLabel(liveProvider?.version);
|
||||
const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
|
||||
const updateCommand = versionAdvisory?.updateCommand ?? null;
|
||||
const FallbackIconComponent = driverOption?.icon;
|
||||
const displayName =
|
||||
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
|
||||
const accentColor = normalizeProviderAccentColor(instance.accentColor);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
|
||||
onCopy: ({ providerName }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `${providerName} update command copied`,
|
||||
description: "Run it in a terminal when you are ready to update.",
|
||||
});
|
||||
},
|
||||
onError: (error, { providerName }) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not copy ${providerName} update command`,
|
||||
description: error.message,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// Narrow `instance.driver` for callers that key on the closed
|
||||
// `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
|
||||
@@ -535,97 +572,203 @@ export function ProviderInstanceCard({
|
||||
);
|
||||
};
|
||||
|
||||
const titleIconNode = driverKind ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={displayName}
|
||||
accentColor={accentColor}
|
||||
showBadge={Boolean(accentColor)}
|
||||
statusDotClassName={statusStyle.dot}
|
||||
className="size-5"
|
||||
iconClassName="size-4 text-foreground/80"
|
||||
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
|
||||
/>
|
||||
) : FallbackIconComponent ? (
|
||||
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
|
||||
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
|
||||
statusStyle.dot,
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
|
||||
);
|
||||
|
||||
const titleHeadNode = (
|
||||
<>
|
||||
{titleIconNode}
|
||||
<h3 className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
|
||||
{displayName}
|
||||
</h3>
|
||||
{String(instanceId) !== String(instance.driver) ? (
|
||||
<code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
|
||||
{instanceId}
|
||||
</code>
|
||||
) : null}
|
||||
{driverOption?.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm" className="shrink-0">
|
||||
{driverOption.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
const titleTailNode = (
|
||||
<>
|
||||
{headerAction ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
{headerAction}
|
||||
</span>
|
||||
) : null}
|
||||
{onDelete ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
aria-label={`Delete provider instance ${instanceId}`}
|
||||
>
|
||||
<Trash2Icon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Delete instance</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
const authRowNode = (
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{hasAuthenticatedEmail ? (
|
||||
<>
|
||||
<span>Authenticated as</span>
|
||||
<ProviderAuthEmail email={authEmail} />
|
||||
{authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{summary.headline}</span>
|
||||
<ProviderAuthEmail email={authEmail} separator prefix="Email" />
|
||||
</>
|
||||
)}
|
||||
{summary.detail ? <span>- {summary.detail}</span> : null}
|
||||
</p>
|
||||
);
|
||||
|
||||
const versionCodeNode = versionLabel ? (
|
||||
<code className="text-xs text-muted-foreground">{versionLabel}</code>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="border-t border-border first:border-t-0">
|
||||
<div className="px-4 py-4 sm:px-5">
|
||||
<div className="border-t border-border/60 first:border-t-0">
|
||||
<div className="px-4 py-3.5 sm:px-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
{driverKind ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={displayName}
|
||||
accentColor={accentColor}
|
||||
showBadge={Boolean(accentColor)}
|
||||
statusDotClassName={statusStyle.dot}
|
||||
className="size-5"
|
||||
iconClassName="size-4 text-foreground/80"
|
||||
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
|
||||
/>
|
||||
) : FallbackIconComponent ? (
|
||||
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
|
||||
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
|
||||
statusStyle.dot,
|
||||
)}
|
||||
aria-hidden
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
{titleHeadNode}
|
||||
{versionCodeNode}
|
||||
{versionAdvisory ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-5 rounded-sm p-0",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning hover:text-warning"
|
||||
: "text-primary hover:text-primary",
|
||||
)}
|
||||
aria-label="Update available — view details"
|
||||
>
|
||||
<ArrowUpCircleIcon className="size-3.5 [animation:bounce_2.4s_ease-in-out_infinite] motion-reduce:animate-none" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
|
||||
)}
|
||||
<h3 className="truncate text-sm font-medium text-foreground">{displayName}</h3>
|
||||
{String(instanceId) !== String(instance.driver) ? (
|
||||
// Hide the id chip on a default slot whose id === the
|
||||
// driver slug — it's redundant with the driver icon +
|
||||
// label. Custom instances (and any instance the user has
|
||||
// since renamed) keep the chip so their slug stays
|
||||
// visible for copy/paste + disambiguation.
|
||||
<code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
|
||||
{instanceId}
|
||||
</code>
|
||||
) : null}
|
||||
{driverOption?.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm" className="shrink-0">
|
||||
{driverOption.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
{versionLabel ? (
|
||||
<code className="text-xs text-muted-foreground">{versionLabel}</code>
|
||||
) : null}
|
||||
{headerAction ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
{headerAction}
|
||||
</span>
|
||||
) : null}
|
||||
{onDelete ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
aria-label={`Delete provider instance ${instanceId}`}
|
||||
<PopoverPopup side="bottom" align="start" className="w-84">
|
||||
<div className="grid gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
Update available
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xs leading-snug",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<Trash2Icon className="size-3" />
|
||||
{versionAdvisory.detail}
|
||||
</p>
|
||||
</div>
|
||||
{onRunUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={isUpdating}
|
||||
onClick={onRunUpdate}
|
||||
>
|
||||
{isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
|
||||
{isUpdating ? "Updating" : "Update now"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Delete instance</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
) : null}
|
||||
{onRunUpdate && updateCommand ? (
|
||||
<div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
or, update manually using
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
) : null}
|
||||
{updateCommand ? (
|
||||
<div className="flex items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[11px] text-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{updateCommand}
|
||||
</code>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
copyToClipboard(updateCommand, {
|
||||
providerName: displayName,
|
||||
})
|
||||
}
|
||||
aria-label="Copy update command"
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Copy command</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
) : null}
|
||||
{titleTailNode}
|
||||
</div>
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{hasAuthenticatedEmail ? (
|
||||
<>
|
||||
<span>Authenticated as</span>
|
||||
<ProviderAuthEmail email={authEmail} />
|
||||
{authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{summary.headline}</span>
|
||||
<ProviderAuthEmail email={authEmail} separator prefix="Email" />
|
||||
</>
|
||||
)}
|
||||
{summary.detail ? <span>- {summary.detail}</span> : null}
|
||||
</p>
|
||||
{authRowNode}
|
||||
</div>
|
||||
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
|
||||
<Button
|
||||
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
type DesktopUpdateChannel,
|
||||
type DesktopUpdateState,
|
||||
type LocalApi,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerConfig,
|
||||
type ServerProvider,
|
||||
type SourceControlDiscoveryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Option } from "effect";
|
||||
@@ -23,7 +26,7 @@ import { AppAtomRegistryProvider, resetAppAtomRegistryForTests } from "../../rpc
|
||||
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
|
||||
import { useUiStateStore } from "../../uiStateStore";
|
||||
import { ConnectionsSettings } from "./ConnectionsSettings";
|
||||
import { GeneralSettingsPanel } from "./SettingsPanels";
|
||||
import { GeneralSettingsPanel, ProviderSettingsPanel } from "./SettingsPanels";
|
||||
import { SourceControlSettingsPanel } from "./SourceControlSettings";
|
||||
|
||||
const authAccessHarness = vi.hoisted(() => {
|
||||
@@ -207,6 +210,31 @@ function createBaseServerConfig(): ServerConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function createOutdatedProvider(driver: string): ServerProvider {
|
||||
return {
|
||||
instanceId: ProviderInstanceId.make(driver),
|
||||
driver: ProviderDriverKind.make(driver),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-05-04T10:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: "1.1.0",
|
||||
message: "Update available.",
|
||||
checkedAt: "2026-05-04T10:00:00.000Z",
|
||||
updateCommand: "npm install -g openai/codex@latest",
|
||||
canUpdate: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeUtc(value: string) {
|
||||
return DateTime.makeUnsafe(Date.parse(value));
|
||||
}
|
||||
@@ -1016,7 +1044,7 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
@@ -1031,6 +1059,41 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
await expect.element(page.getByText("Server password")).toBeInTheDocument();
|
||||
await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("runs one-click provider updates from the provider card", async () => {
|
||||
const updateProvider = vi.fn<LocalApi["server"]["updateProvider"]>().mockResolvedValue({
|
||||
providers: [createOutdatedProvider("codex")],
|
||||
});
|
||||
window.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: vi.fn().mockResolvedValue(null),
|
||||
setClientSettings: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
server: {
|
||||
updateProvider,
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
providers: [createOutdatedProvider("codex")],
|
||||
});
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Update available — view details" }).click();
|
||||
await expect.element(page.getByRole("button", { name: "Update now" })).toBeInTheDocument();
|
||||
await page.getByRole("button", { name: "Update now" }).click();
|
||||
|
||||
expect(updateProvider).toHaveBeenCalledWith({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("SourceControlSettingsPanel discovery states", () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
type DesktopUpdateChannel,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceId,
|
||||
@@ -56,6 +57,13 @@ import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
hasOneClickUpdateProviderCandidate,
|
||||
isProviderUpdateActive,
|
||||
type ProviderUpdateCandidate,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { ProviderInstanceCard } from "./ProviderInstanceCard";
|
||||
import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
|
||||
import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";
|
||||
@@ -69,7 +77,6 @@ import {
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerKeybindingsConfigPath,
|
||||
useServerObservability,
|
||||
useServerProviders,
|
||||
} from "../../rpc/serverState";
|
||||
@@ -345,37 +352,12 @@ function AboutVersionSection() {
|
||||
export function useSettingsRestore(onRestored?: () => void) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { resetSettings } = useUpdateSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
// A provider surface is "dirty" if either the legacy per-kind
|
||||
// `settings.providers[kind]` struct differs from defaults (for users
|
||||
// on pre-migration data) or the new `settings.providerInstances` map
|
||||
// has any entries (every edit to a default slot promotes it into an
|
||||
// explicit entry, so any key in that map represents user intent to
|
||||
// diverge from factory defaults). Checking both keeps the Restore
|
||||
// Defaults chip accurate throughout the legacy→instance migration.
|
||||
const areProviderSettingsDirty =
|
||||
PROVIDER_SETTINGS.some((providerSettings) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const currentProviders = settings.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const currentSettings = currentProviders[providerSettings.provider];
|
||||
const defaultSettings = defaultProviders[providerSettings.provider];
|
||||
return !Equal.equals(currentSettings, defaultSettings);
|
||||
}) ||
|
||||
Object.keys(settings.providerInstances ?? {}).length > 0 ||
|
||||
Object.keys(settings.providerModelPreferences ?? {}).length > 0 ||
|
||||
(settings.favorites ?? []).length > 0;
|
||||
|
||||
const changedSettingLabels = useMemo(
|
||||
() => [
|
||||
@@ -408,10 +390,8 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(areProviderSettingsDirty ? ["Providers"] : []),
|
||||
],
|
||||
[
|
||||
areProviderSettingsDirty,
|
||||
isGitWritingModelDirty,
|
||||
settings.autoOpenPlanSidebar,
|
||||
settings.confirmThreadArchive,
|
||||
@@ -437,9 +417,20 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
if (!confirmed) return;
|
||||
|
||||
setTheme("system");
|
||||
resetSettings();
|
||||
updateSettings({
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
|
||||
textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
|
||||
});
|
||||
onRestored?.();
|
||||
}, [changedSettingLabels, onRestored, resetSettings, setTheme]);
|
||||
}, [changedSettingLabels, onRestored, setTheme, updateSettings]);
|
||||
|
||||
return {
|
||||
changedSettingLabels,
|
||||
@@ -452,50 +443,14 @@ export function GeneralSettingsPanel() {
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const [openingPathByTarget, setOpeningPathByTarget] = useState({
|
||||
keybindings: false,
|
||||
logsDirectory: false,
|
||||
});
|
||||
const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState<
|
||||
Partial<Record<"keybindings" | "logsDirectory", string | null>>
|
||||
Partial<Record<"logsDirectory", string | null>>
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
|
||||
// Collapsible state per provider-instance card, keyed by the instance id.
|
||||
// `Record<string, boolean>` so we don't need to preseed an entry for every
|
||||
// configured instance — an absent key reads as collapsed. Default-slot
|
||||
// rows share this state: their id is the driver slug
|
||||
// (`defaultInstanceIdForDriver(driver)`), which is also `ProviderDriverKind` at
|
||||
// runtime, so a pre-existing open key for e.g. "codex" persists across
|
||||
// the legacy/unified render swap.
|
||||
const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
|
||||
const refreshingRef = useRef(false);
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureLocalApi()
|
||||
.server.refreshProviders()
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
.finally(() => {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const keybindingsConfigPath = useServerKeybindingsConfigPath();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const observability = useServerObservability();
|
||||
const serverProviders = useServerProviders();
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
),
|
||||
);
|
||||
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
|
||||
const diagnosticsDescription = (() => {
|
||||
const exports: string[] = [];
|
||||
@@ -533,7 +488,7 @@ export function GeneralSettingsPanel() {
|
||||
);
|
||||
|
||||
const openInPreferredEditor = useCallback(
|
||||
(target: "keybindings" | "logsDirectory", path: string | null, failureMessage: string) => {
|
||||
(target: "logsDirectory", path: string | null, failureMessage: string) => {
|
||||
if (!path) return;
|
||||
setOpenPathErrorByTarget((existing) => ({ ...existing, [target]: null }));
|
||||
setOpeningPathByTarget((existing) => ({ ...existing, [target]: true }));
|
||||
@@ -563,234 +518,13 @@ export function GeneralSettingsPanel() {
|
||||
[availableEditors],
|
||||
);
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
openInPreferredEditor("keybindings", keybindingsConfigPath, "Unable to open keybindings file.");
|
||||
}, [keybindingsConfigPath, openInPreferredEditor]);
|
||||
|
||||
const openLogsDirectory = useCallback(() => {
|
||||
openInPreferredEditor("logsDirectory", logsDirectoryPath, "Unable to open logs folder.");
|
||||
}, [logsDirectoryPath, openInPreferredEditor]);
|
||||
|
||||
const openKeybindingsError = openPathErrorByTarget.keybindings ?? null;
|
||||
const openDiagnosticsError = openPathErrorByTarget.logsDirectory ?? null;
|
||||
const isOpeningKeybindings = openingPathByTarget.keybindings;
|
||||
const isOpeningLogsDirectory = openingPathByTarget.logsDirectory;
|
||||
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
(latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
|
||||
serverProviders[0]!.checkedAt,
|
||||
)
|
||||
: null;
|
||||
|
||||
/**
|
||||
* Build the list of rows to render, one per configured instance. Each
|
||||
* row carries enough context to drive `ProviderInstanceCard` without
|
||||
* threading storage concerns: whether it's a built-in default slot (in
|
||||
* which case `isDefault` is true, deletion is gated off, and the
|
||||
* effective envelope may have been synthesized from legacy just for
|
||||
* this render), the driver kind narrow for the in-card model-slug
|
||||
* normalization, and whether a reset-to-factory action is warranted.
|
||||
*
|
||||
* Ordering mirrors the prior split: visible built-in default slots
|
||||
* first (one per visible kind), then user-authored custom instances
|
||||
* grouped by driver after their default sibling, then orphan instances
|
||||
* whose driver isn't in the visible-defaults set.
|
||||
*/
|
||||
interface InstanceRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
readonly driver: ProviderDriverKind;
|
||||
/** True for the slot whose id is `defaultInstanceIdForDriver(driver)`. */
|
||||
readonly isDefault: boolean;
|
||||
/**
|
||||
* True when this default slot differs from the factory defaults —
|
||||
* either through an explicit `providerInstances[defaultId]` entry,
|
||||
* or through a non-default legacy `settings.providers[kind]` struct
|
||||
* that we're still bridging. Used to show the reset-to-factory
|
||||
* affordance. Undefined for custom rows (they have a delete button
|
||||
* instead; "factory defaults" isn't meaningful).
|
||||
*/
|
||||
readonly isDirty?: boolean;
|
||||
}
|
||||
|
||||
const instancesByDriver = new Map<
|
||||
ProviderDriverKind,
|
||||
Array<[ProviderInstanceId, ProviderInstanceConfig]>
|
||||
>();
|
||||
for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
|
||||
const driver = instance.driver;
|
||||
const list = instancesByDriver.get(driver) ?? [];
|
||||
list.push([rawId as ProviderInstanceId, instance]);
|
||||
instancesByDriver.set(driver, list);
|
||||
}
|
||||
|
||||
const defaultSlotIdsBySource = new Set<string>(
|
||||
visibleProviderSettings.map((providerSettings) =>
|
||||
String(defaultInstanceIdForDriver(providerSettings.provider)),
|
||||
),
|
||||
);
|
||||
|
||||
const rows: InstanceRow[] = [];
|
||||
const visibleDriverKinds = new Set<ProviderDriverKind>(
|
||||
visibleProviderSettings.map((providerSettings) => providerSettings.provider),
|
||||
);
|
||||
|
||||
for (const providerSettings of visibleProviderSettings) {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings
|
||||
>;
|
||||
const driver = providerSettings.provider;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driver);
|
||||
// Prefer an explicit `providerInstances[defaultId]` entry when one
|
||||
// exists (every edit via this UI promotes the default slot into
|
||||
// that map); fall back to synthesizing one from the legacy
|
||||
// `settings.providers[kind]` struct so first-time viewers still see
|
||||
// their persisted config.
|
||||
const explicitInstance = settings.providerInstances?.[defaultInstanceId];
|
||||
const legacyConfig = legacyProviders[providerSettings.provider]!;
|
||||
const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;
|
||||
const effectiveInstance: ProviderInstanceConfig =
|
||||
explicitInstance ??
|
||||
({
|
||||
driver,
|
||||
enabled: legacyConfig.enabled,
|
||||
config: legacyConfig,
|
||||
} satisfies ProviderInstanceConfig);
|
||||
const isDirty =
|
||||
explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
|
||||
rows.push({
|
||||
instanceId: defaultInstanceId,
|
||||
instance: effectiveInstance,
|
||||
driver,
|
||||
isDefault: true,
|
||||
isDirty,
|
||||
});
|
||||
// Non-default customs for this driver kind follow their default.
|
||||
for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
|
||||
if (id === defaultInstanceId) continue;
|
||||
rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
|
||||
}
|
||||
}
|
||||
// Orphan instances: drivers the visible-defaults list doesn't cover
|
||||
// (e.g. Cursor when the server hasn't reported it but the user has
|
||||
// authored a Cursor instance anyway, or fork drivers not shipped by
|
||||
// this build). Preserve insertion order within each driver.
|
||||
for (const [driver, list] of instancesByDriver) {
|
||||
if (visibleDriverKinds.has(driver)) continue;
|
||||
for (const [id, instance] of list) {
|
||||
const isDefaultSlot = defaultSlotIdsBySource.has(String(id));
|
||||
rows.push({
|
||||
instanceId: id,
|
||||
instance,
|
||||
driver: instance.driver,
|
||||
isDefault: isDefaultSlot,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const updateProviderInstance = (
|
||||
row: InstanceRow,
|
||||
next: ProviderInstanceConfig,
|
||||
options?: {
|
||||
readonly textGenerationModelSelection?: Parameters<
|
||||
typeof buildProviderInstanceUpdatePatch
|
||||
>[0]["textGenerationModelSelection"];
|
||||
},
|
||||
) => {
|
||||
updateSettings(
|
||||
buildProviderInstanceUpdatePatch({
|
||||
settings,
|
||||
instanceId: row.instanceId,
|
||||
instance: next,
|
||||
driver: row.driver,
|
||||
isDefault: row.isDefault,
|
||||
textGenerationModelSelection: options?.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const deleteProviderInstance = (id: ProviderInstanceId) => {
|
||||
updateSettings({
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
|
||||
providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderModelPreferences = (
|
||||
instanceId: ProviderInstanceId,
|
||||
next: {
|
||||
readonly hiddenModels: ReadonlyArray<string>;
|
||||
readonly modelOrder: ReadonlyArray<string>;
|
||||
},
|
||||
) => {
|
||||
const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
|
||||
const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
|
||||
const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
|
||||
updateSettings({
|
||||
providerModelPreferences:
|
||||
hiddenModels.length === 0 && modelOrder.length === 0
|
||||
? rest
|
||||
: {
|
||||
...rest,
|
||||
[instanceId]: {
|
||||
hiddenModels,
|
||||
modelOrder,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderFavoriteModels = (
|
||||
instanceId: ProviderInstanceId,
|
||||
nextFavoriteModels: ReadonlyArray<string>,
|
||||
) => {
|
||||
const favoriteModels = [
|
||||
...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),
|
||||
];
|
||||
updateSettings({
|
||||
favorites: [
|
||||
...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
|
||||
...favoriteModels.map((model) => ({ provider: instanceId, model })),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset a built-in default slot back to factory defaults. Clears both
|
||||
* the legacy `settings.providers[kind]` struct and any explicit
|
||||
* `providerInstances[defaultId]` entry that has promoted legacy into
|
||||
* the new map, so hydration re-synthesizes a clean envelope on next
|
||||
* load. Safe to call on drivers that have never been edited.
|
||||
*/
|
||||
const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
|
||||
const defaultLegacyProvider = defaultLegacyProviders[driverKind];
|
||||
if (defaultLegacyProvider === undefined) return;
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
[driverKind]: defaultLegacyProvider,
|
||||
} as typeof settings.providers,
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
|
||||
providerModelPreferences: withoutProviderInstanceKey(
|
||||
settings.providerModelPreferences,
|
||||
defaultInstanceId,
|
||||
),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
@@ -1168,6 +902,308 @@ export function GeneralSettingsPanel() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="About">
|
||||
{isElectron ? (
|
||||
<AboutVersionSection />
|
||||
) : (
|
||||
<SettingsRow
|
||||
title={<AboutVersionTitle />}
|
||||
description="Current version of the application."
|
||||
/>
|
||||
)}
|
||||
<SettingsRow
|
||||
title="Diagnostics"
|
||||
description={diagnosticsDescription}
|
||||
status={
|
||||
<>
|
||||
<span className="block break-all font-mono text-[11px] text-foreground">
|
||||
{logsDirectoryPath ?? "Resolving logs directory..."}
|
||||
</span>
|
||||
{openDiagnosticsError ? (
|
||||
<span className="mt-1 block text-destructive">{openDiagnosticsError}</span>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
control={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!logsDirectoryPath || isOpeningLogsDirectory}
|
||||
onClick={openLogsDirectory}
|
||||
>
|
||||
{isOpeningLogsDirectory ? "Opening..." : "Open logs folder"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProviderSettingsPanel() {
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const serverProviders = useServerProviders();
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
|
||||
const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
|
||||
ReadonlySet<ProviderDriverKind>
|
||||
>(() => new Set());
|
||||
const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
|
||||
const refreshingRef = useRef(false);
|
||||
|
||||
const providerUpdateCandidates = useMemo(
|
||||
() => collectProviderUpdateCandidates(serverProviders),
|
||||
[serverProviders],
|
||||
);
|
||||
const providerUpdateCandidateByInstanceId = useMemo(
|
||||
() => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
|
||||
[providerUpdateCandidates],
|
||||
);
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
),
|
||||
);
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
(latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
|
||||
serverProviders[0]!.checkedAt,
|
||||
)
|
||||
: null;
|
||||
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureLocalApi()
|
||||
.server.refreshProviders()
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
.finally(() => {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const runProviderUpdate = useCallback(async (candidate: ProviderUpdateCandidate) => {
|
||||
let started = false;
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (previous.has(candidate.driver)) {
|
||||
return previous;
|
||||
}
|
||||
started = true;
|
||||
const next = new Set(previous);
|
||||
next.add(candidate.driver);
|
||||
return next;
|
||||
});
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureLocalApi().server.updateProvider({
|
||||
provider: candidate.driver,
|
||||
instanceId: candidate.instanceId,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The provider update command could not be started.",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (!previous.has(candidate.driver)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Set(previous);
|
||||
next.delete(candidate.driver);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
interface InstanceRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly isDefault: boolean;
|
||||
readonly isDirty?: boolean;
|
||||
}
|
||||
|
||||
const instancesByDriver = new Map<
|
||||
ProviderDriverKind,
|
||||
Array<[ProviderInstanceId, ProviderInstanceConfig]>
|
||||
>();
|
||||
for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
|
||||
const driver = instance.driver;
|
||||
const list = instancesByDriver.get(driver) ?? [];
|
||||
list.push([rawId as ProviderInstanceId, instance]);
|
||||
instancesByDriver.set(driver, list);
|
||||
}
|
||||
|
||||
const defaultSlotIdsBySource = new Set<string>(
|
||||
visibleProviderSettings.map((providerSettings) =>
|
||||
String(defaultInstanceIdForDriver(providerSettings.provider)),
|
||||
),
|
||||
);
|
||||
|
||||
const rows: InstanceRow[] = [];
|
||||
const visibleDriverKinds = new Set<ProviderDriverKind>(
|
||||
visibleProviderSettings.map((providerSettings) => providerSettings.provider),
|
||||
);
|
||||
|
||||
for (const providerSettings of visibleProviderSettings) {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings
|
||||
>;
|
||||
const driver = providerSettings.provider;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driver);
|
||||
const explicitInstance = settings.providerInstances?.[defaultInstanceId];
|
||||
const legacyConfig = legacyProviders[providerSettings.provider]!;
|
||||
const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;
|
||||
const effectiveInstance: ProviderInstanceConfig =
|
||||
explicitInstance ??
|
||||
({
|
||||
driver,
|
||||
enabled: legacyConfig.enabled,
|
||||
config: legacyConfig,
|
||||
} satisfies ProviderInstanceConfig);
|
||||
const isDirty =
|
||||
explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
|
||||
rows.push({
|
||||
instanceId: defaultInstanceId,
|
||||
instance: effectiveInstance,
|
||||
driver,
|
||||
isDefault: true,
|
||||
isDirty,
|
||||
});
|
||||
for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
|
||||
if (id === defaultInstanceId) continue;
|
||||
rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
|
||||
}
|
||||
}
|
||||
for (const [driver, list] of instancesByDriver) {
|
||||
if (visibleDriverKinds.has(driver)) continue;
|
||||
for (const [id, instance] of list) {
|
||||
rows.push({
|
||||
instanceId: id,
|
||||
instance,
|
||||
driver: instance.driver,
|
||||
isDefault: defaultSlotIdsBySource.has(String(id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const updateProviderInstance = (
|
||||
row: InstanceRow,
|
||||
next: ProviderInstanceConfig,
|
||||
options?: {
|
||||
readonly textGenerationModelSelection?: Parameters<
|
||||
typeof buildProviderInstanceUpdatePatch
|
||||
>[0]["textGenerationModelSelection"];
|
||||
},
|
||||
) => {
|
||||
updateSettings(
|
||||
buildProviderInstanceUpdatePatch({
|
||||
settings,
|
||||
instanceId: row.instanceId,
|
||||
instance: next,
|
||||
driver: row.driver,
|
||||
isDefault: row.isDefault,
|
||||
textGenerationModelSelection: options?.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const deleteProviderInstance = (id: ProviderInstanceId) => {
|
||||
updateSettings({
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
|
||||
providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderModelPreferences = (
|
||||
instanceId: ProviderInstanceId,
|
||||
next: {
|
||||
readonly hiddenModels: ReadonlyArray<string>;
|
||||
readonly modelOrder: ReadonlyArray<string>;
|
||||
},
|
||||
) => {
|
||||
const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
|
||||
const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
|
||||
const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
|
||||
updateSettings({
|
||||
providerModelPreferences:
|
||||
hiddenModels.length === 0 && modelOrder.length === 0
|
||||
? rest
|
||||
: {
|
||||
...rest,
|
||||
[instanceId]: {
|
||||
hiddenModels,
|
||||
modelOrder,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderFavoriteModels = (
|
||||
instanceId: ProviderInstanceId,
|
||||
nextFavoriteModels: ReadonlyArray<string>,
|
||||
) => {
|
||||
const favoriteModels = [
|
||||
...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),
|
||||
];
|
||||
updateSettings({
|
||||
favorites: [
|
||||
...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
|
||||
...favoriteModels.map((model) => ({ provider: instanceId, model })),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
|
||||
const defaultLegacyProvider = defaultLegacyProviders[driverKind];
|
||||
if (defaultLegacyProvider === undefined) return;
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
[driverKind]: defaultLegacyProvider,
|
||||
} as typeof settings.providers,
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
|
||||
providerModelPreferences: withoutProviderInstanceKey(
|
||||
settings.providerModelPreferences,
|
||||
defaultInstanceId,
|
||||
),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection
|
||||
title="Providers"
|
||||
headerAction={
|
||||
@@ -1218,6 +1254,23 @@ export function GeneralSettingsPanel() {
|
||||
const liveProvider = serverProviders.find(
|
||||
(candidate) => candidate.instanceId === row.instanceId,
|
||||
);
|
||||
const updateCandidate = liveProvider
|
||||
? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
|
||||
: undefined;
|
||||
const isDriverUpdateRunning =
|
||||
updateCandidate !== undefined &&
|
||||
(updatingProviderDrivers.has(updateCandidate.driver) ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
|
||||
));
|
||||
const showInlineUpdateButton =
|
||||
updateCandidate !== undefined &&
|
||||
hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
|
||||
const canRunInlineUpdate =
|
||||
updateCandidate !== undefined &&
|
||||
canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
|
||||
!updatingProviderDrivers.has(updateCandidate.driver);
|
||||
const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
|
||||
hiddenModels: [],
|
||||
modelOrder: [],
|
||||
@@ -1248,13 +1301,6 @@ export function GeneralSettingsPanel() {
|
||||
}))
|
||||
}
|
||||
onUpdate={(next) => {
|
||||
// When the user disables the exact instance the text-gen
|
||||
// selection points at, fall back to the global default so we
|
||||
// don't leave the selection dangling on a disabled instance.
|
||||
// Prior kind-level behavior cleared on any kind-matching
|
||||
// disable; instance-level addressing makes this narrower and
|
||||
// more accurate (other instances of the same kind stay
|
||||
// untouched).
|
||||
const wasEnabled = row.instance.enabled ?? true;
|
||||
const isDisabling = next.enabled === false && wasEnabled;
|
||||
const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
|
||||
@@ -1287,6 +1333,17 @@ export function GeneralSettingsPanel() {
|
||||
modelOrder,
|
||||
})
|
||||
}
|
||||
onRunUpdate={
|
||||
showInlineUpdateButton && updateCandidate
|
||||
? () => {
|
||||
if (!canRunInlineUpdate) {
|
||||
return;
|
||||
}
|
||||
void runProviderUpdate(updateCandidate);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -1296,70 +1353,6 @@ export function GeneralSettingsPanel() {
|
||||
open={isAddInstanceDialogOpen}
|
||||
onOpenChange={setIsAddInstanceDialogOpen}
|
||||
/>
|
||||
|
||||
<SettingsSection title="Advanced">
|
||||
<SettingsRow
|
||||
title="Keybindings"
|
||||
description="Open the persisted `keybindings.json` file to edit advanced bindings directly."
|
||||
status={
|
||||
<>
|
||||
<span className="block break-all font-mono text-[11px] text-foreground">
|
||||
{keybindingsConfigPath ?? "Resolving keybindings path..."}
|
||||
</span>
|
||||
{openKeybindingsError ? (
|
||||
<span className="mt-1 block text-destructive">{openKeybindingsError}</span>
|
||||
) : (
|
||||
<span className="mt-1 block">Opens in your preferred editor.</span>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
control={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!keybindingsConfigPath || isOpeningKeybindings}
|
||||
onClick={openKeybindingsFile}
|
||||
>
|
||||
{isOpeningKeybindings ? "Opening..." : "Open file"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="About">
|
||||
{isElectron ? (
|
||||
<AboutVersionSection />
|
||||
) : (
|
||||
<SettingsRow
|
||||
title={<AboutVersionTitle />}
|
||||
description="Current version of the application."
|
||||
/>
|
||||
)}
|
||||
<SettingsRow
|
||||
title="Diagnostics"
|
||||
description={diagnosticsDescription}
|
||||
status={
|
||||
<>
|
||||
<span className="block break-all font-mono text-[11px] text-foreground">
|
||||
{logsDirectoryPath ?? "Resolving logs directory..."}
|
||||
</span>
|
||||
{openDiagnosticsError ? (
|
||||
<span className="mt-1 block text-destructive">{openDiagnosticsError}</span>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
control={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!logsDirectoryPath || isOpeningLogsDirectory}
|
||||
onClick={openLogsDirectory}
|
||||
>
|
||||
{isOpeningLogsDirectory ? "Opening..." : "Open logs folder"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useCallback, type ComponentType } from "react";
|
||||
import { ArchiveIcon, ArrowLeftIcon, GitBranchIcon, Link2Icon, Settings2Icon } from "lucide-react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
BotIcon,
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
Settings2Icon,
|
||||
} from "lucide-react";
|
||||
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import {
|
||||
@@ -15,6 +23,8 @@ import {
|
||||
|
||||
export type SettingsSectionPath =
|
||||
| "/settings/general"
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/source-control"
|
||||
| "/settings/connections"
|
||||
| "/settings/archived";
|
||||
@@ -25,6 +35,8 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { ServerProvider, ServerProviderVersionAdvisory } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Visual treatment for each server-reported provider status. Centralized so
|
||||
@@ -89,3 +89,29 @@ export function getProviderVersionLabel(version: string | null | undefined) {
|
||||
if (!version) return null;
|
||||
return version.startsWith("v") ? version : `v${version}`;
|
||||
}
|
||||
|
||||
export function getProviderVersionAdvisoryPresentation(
|
||||
advisory: ServerProviderVersionAdvisory | undefined,
|
||||
): {
|
||||
readonly detail: string;
|
||||
readonly updateCommand: string | null;
|
||||
readonly emphasis: "normal" | "strong";
|
||||
} | null {
|
||||
if (!advisory || advisory.status === "current" || advisory.status === "unknown") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = "Update available";
|
||||
const version = advisory.latestVersion;
|
||||
const versionLabel = getProviderVersionLabel(version);
|
||||
|
||||
return {
|
||||
detail:
|
||||
advisory.message ??
|
||||
(versionLabel
|
||||
? `${label}: install ${versionLabel}.`
|
||||
: `${label}: install the latest provider version.`),
|
||||
updateCommand: advisory.updateCommand,
|
||||
emphasis: "normal" as const,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Undo2Icon } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { type ComponentPropsWithoutRef, type ReactNode, useEffect, useState } from "react";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -20,15 +20,17 @@ export function SettingsSection({
|
||||
icon,
|
||||
headerAction,
|
||||
children,
|
||||
}: {
|
||||
className,
|
||||
...sectionProps
|
||||
}: ComponentPropsWithoutRef<"section"> & {
|
||||
title: string;
|
||||
icon?: ReactNode;
|
||||
headerAction?: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-2.5">
|
||||
<div className="flex h-5 items-center justify-between px-1">
|
||||
<section {...sectionProps} className={cn("space-y-2.5", className)}>
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<h2 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/50">
|
||||
<span className="inline-block h-px w-3 bg-border" aria-hidden />
|
||||
{icon}
|
||||
@@ -62,7 +64,7 @@ export function SettingsRow({
|
||||
<div
|
||||
className={cn(
|
||||
"border-t border-border/60 px-4 first:border-t-0 sm:px-5",
|
||||
children ? "pt-4 pb-0" : "py-4",
|
||||
children ? "pt-3.5 pb-0" : "py-3.5",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
@@ -75,7 +77,7 @@ export function SettingsRow({
|
||||
{resetAction}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground/80">{description}</p>
|
||||
<p className="text-xs text-muted-foreground/80">{description}</p>
|
||||
{status ? <div className="pt-0.5 text-[11px] text-muted-foreground">{status}</div> : null}
|
||||
</div>
|
||||
{control ? (
|
||||
@@ -113,10 +115,18 @@ export function SettingResetButton({ label, onClick }: { label: string; onClick:
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPageContainer({ children }: { children: ReactNode }) {
|
||||
export function SettingsPageContainer({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-6 sm:p-8">
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-8">{children}</div>
|
||||
<div className={cn("mx-auto flex w-full max-w-3xl flex-col gap-8", className)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useState, type CSSProperties } from "react";
|
||||
|
||||
import { useServerProviders } from "../../rpc/serverState";
|
||||
import {
|
||||
getProviderUpdateSidebarPillView,
|
||||
type ProviderUpdateSidebarPillView,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
const PROVIDER_UPDATE_PILL_STYLES = {
|
||||
loading:
|
||||
"bg-primary/15 text-primary group-has-[button.provider-update-main:hover]/provider-update:bg-primary/22",
|
||||
success:
|
||||
"bg-success/12 text-success group-has-[button.provider-update-main:hover]/provider-update:bg-success/18",
|
||||
warning:
|
||||
"bg-warning/12 text-warning group-has-[button.provider-update-main:hover]/provider-update:bg-warning/18",
|
||||
error:
|
||||
"bg-destructive/12 text-destructive group-has-[button.provider-update-main:hover]/provider-update:bg-destructive/18",
|
||||
} as const;
|
||||
|
||||
const PROVIDER_UPDATE_PILL_PROGRESS_STYLES = {
|
||||
success: "bg-success/18",
|
||||
warning: "bg-warning/14",
|
||||
error: "bg-destructive/14",
|
||||
} as const;
|
||||
|
||||
function latestProviderCheckedAt(
|
||||
providers: ReadonlyArray<Pick<ServerProvider, "checkedAt">>,
|
||||
): string | undefined {
|
||||
return providers.reduce<string | undefined>(
|
||||
(latest, provider) =>
|
||||
latest === undefined || provider.checkedAt > latest ? provider.checkedAt : latest,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function SidebarProviderUpdatePill() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(null);
|
||||
const [pendingView, setPendingView] = useState<ProviderUpdateSidebarPillView | null>(null);
|
||||
const [exitingKey, setExitingKey] = useState<string | null>(null);
|
||||
const [dismissAfterExitKey, setDismissAfterExitKey] = useState<string | null>(null);
|
||||
const [visibleAfterIso, setVisibleAfterIso] = useState<string | undefined>();
|
||||
const effectiveVisibleAfterIso = visibleAfterIso ?? latestProviderCheckedAt(providers);
|
||||
const view = getProviderUpdateSidebarPillView(providers, {
|
||||
...(effectiveVisibleAfterIso !== undefined
|
||||
? { visibleAfterIso: effectiveVisibleAfterIso }
|
||||
: {}),
|
||||
dismissedKeys,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (visibleAfterIso === undefined && effectiveVisibleAfterIso !== undefined) {
|
||||
setVisibleAfterIso(effectiveVisibleAfterIso);
|
||||
}
|
||||
}, [effectiveVisibleAfterIso, visibleAfterIso]);
|
||||
|
||||
const openProviderSettings = useCallback(() => {
|
||||
void navigate({ to: "/settings/providers" });
|
||||
}, [navigate]);
|
||||
const displayedView = renderedView ?? view;
|
||||
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
|
||||
const viewKey = displayedView?.key ?? null;
|
||||
const showDismissProgress =
|
||||
dismissAfterVisibleMs !== undefined &&
|
||||
displayedView?.tone !== "loading" &&
|
||||
exitingKey !== viewKey;
|
||||
|
||||
const startExit = useCallback(
|
||||
(key: string, nextView: ProviderUpdateSidebarPillView | null, dismissKey?: string) => {
|
||||
if (exitingKey === key) {
|
||||
return;
|
||||
}
|
||||
setPendingView(nextView);
|
||||
setExitingKey(key);
|
||||
setDismissAfterExitKey(dismissKey ?? null);
|
||||
},
|
||||
[exitingKey],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (exitingKey !== null) {
|
||||
return;
|
||||
}
|
||||
if (!renderedView) {
|
||||
if (view) {
|
||||
setRenderedView(view);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!view) {
|
||||
startExit(renderedView.key, null);
|
||||
return;
|
||||
}
|
||||
if (view.key !== renderedView.key) {
|
||||
startExit(renderedView.key, view);
|
||||
return;
|
||||
}
|
||||
}, [exitingKey, renderedView, startExit, view]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dismissAfterVisibleMs || !viewKey) {
|
||||
return;
|
||||
}
|
||||
if (exitingKey === viewKey) {
|
||||
return;
|
||||
}
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
startExit(viewKey, null, viewKey);
|
||||
}, dismissAfterVisibleMs);
|
||||
|
||||
return () => window.clearTimeout(timeoutId);
|
||||
}, [dismissAfterVisibleMs, exitingKey, startExit, viewKey]);
|
||||
|
||||
if (!displayedView) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group/provider-update relative flex h-7 w-full items-center overflow-hidden rounded-lg text-xs font-medium transform-gpu transition-all duration-180 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform ${
|
||||
PROVIDER_UPDATE_PILL_STYLES[displayedView.tone]
|
||||
} ${
|
||||
exitingKey === displayedView.key
|
||||
? "pointer-events-none translate-y-1.5 opacity-0"
|
||||
: "translate-y-0 opacity-100"
|
||||
}`}
|
||||
onTransitionEnd={(event) => {
|
||||
if (event.target !== event.currentTarget) {
|
||||
return;
|
||||
}
|
||||
if (!displayedView || exitingKey !== displayedView.key) {
|
||||
return;
|
||||
}
|
||||
if (dismissAfterExitKey === displayedView.key) {
|
||||
setDismissedKeys((previous) => new Set(previous).add(displayedView.key));
|
||||
}
|
||||
setRenderedView(pendingView);
|
||||
setPendingView(null);
|
||||
setExitingKey(null);
|
||||
setDismissAfterExitKey(null);
|
||||
}}
|
||||
>
|
||||
{showDismissProgress ? (
|
||||
<div
|
||||
key={displayedView.key}
|
||||
aria-hidden="true"
|
||||
className={`provider-update-pill-progress pointer-events-none absolute inset-y-0 left-0 w-full origin-left border-r border-current/15 shadow-[inset_0_1px_0_rgb(255_255_255_/_0.08)] ${
|
||||
PROVIDER_UPDATE_PILL_PROGRESS_STYLES[displayedView.tone]
|
||||
}`}
|
||||
style={
|
||||
{
|
||||
"--provider-update-pill-dismiss-ms": `${dismissAfterVisibleMs}ms`,
|
||||
} as CSSProperties
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<div className="pointer-events-none absolute inset-0 rounded-lg transition-colors" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={displayedView.description}
|
||||
className="provider-update-main relative z-[1] flex h-full flex-1 items-center gap-2 px-2 text-left"
|
||||
onClick={openProviderSettings}
|
||||
>
|
||||
{displayedView.tone === "loading" ? (
|
||||
<LoaderIcon className="size-3.5 animate-spin" />
|
||||
) : displayedView.tone === "success" ? (
|
||||
<CircleCheckIcon className="size-3.5" />
|
||||
) : displayedView.tone === "error" ? (
|
||||
<TriangleAlertIcon className="size-3.5" />
|
||||
) : (
|
||||
<DownloadIcon className="size-3.5" />
|
||||
)}
|
||||
<span>{displayedView.title}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{displayedView.description}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{displayedView.dismissible && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss provider update notice"
|
||||
className="relative z-[1] mr-1 inline-flex size-5 items-center justify-center rounded-md opacity-70 transition-opacity hover:opacity-100"
|
||||
onClick={() => startExit(displayedView.key, null, displayedView.key)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Dismiss until provider status changes</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,11 +10,13 @@ function ScrollArea({
|
||||
scrollFade = false,
|
||||
scrollbarGutter = false,
|
||||
hideScrollbars = false,
|
||||
chainVerticalScroll = false,
|
||||
...props
|
||||
}: ScrollAreaPrimitive.Root.Props & {
|
||||
scrollFade?: boolean;
|
||||
scrollbarGutter?: boolean;
|
||||
hideScrollbars?: boolean;
|
||||
chainVerticalScroll?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
@@ -23,7 +25,8 @@ function ScrollArea({
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
className={cn(
|
||||
"h-full max-h-[inherit] overflow-y-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
|
||||
"h-full max-h-[inherit] overflow-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
|
||||
chainVerticalScroll && "overscroll-y-auto",
|
||||
scrollFade &&
|
||||
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
|
||||
scrollbarGutter && "[scrollbar-gutter:stable]",
|
||||
|
||||
@@ -105,20 +105,24 @@ function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
||||
|
||||
function SelectPopup({
|
||||
className,
|
||||
popupClassName,
|
||||
children,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
align = "start",
|
||||
alignOffset = 0,
|
||||
alignItemWithTrigger = true,
|
||||
matchTriggerWidth = true,
|
||||
anchor,
|
||||
...props
|
||||
}: SelectPrimitive.Popup.Props & {
|
||||
popupClassName?: string;
|
||||
side?: SelectPrimitive.Positioner.Props["side"];
|
||||
sideOffset?: SelectPrimitive.Positioner.Props["sideOffset"];
|
||||
align?: SelectPrimitive.Positioner.Props["align"];
|
||||
alignOffset?: SelectPrimitive.Positioner.Props["alignOffset"];
|
||||
alignItemWithTrigger?: SelectPrimitive.Positioner.Props["alignItemWithTrigger"];
|
||||
matchTriggerWidth?: boolean;
|
||||
anchor?: SelectPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
return (
|
||||
@@ -144,7 +148,13 @@ function SelectPopup({
|
||||
>
|
||||
<ChevronUpIcon className="relative size-4.5 sm:size-4" />
|
||||
</SelectPrimitive.ScrollUpArrow>
|
||||
<div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
|
||||
<div
|
||||
className={cn(
|
||||
"relative h-full rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
matchTriggerWidth && "min-w-(--anchor-width)",
|
||||
popupClassName,
|
||||
)}
|
||||
>
|
||||
<SelectPrimitive.List
|
||||
className={cn("max-h-(--available-height) overflow-y-auto p-1", className)}
|
||||
data-slot="select-list"
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useMemo,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type ComponentPropsWithoutRef,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
@@ -38,9 +39,20 @@ import {
|
||||
export type ThreadToastData = {
|
||||
threadRef?: ScopedThreadRef | null;
|
||||
threadId?: ThreadId | null;
|
||||
leadingIcon?: ReactNode;
|
||||
tooltipStyle?: boolean;
|
||||
onClose?: (() => void) | undefined;
|
||||
dismissAfterVisibleMs?: number;
|
||||
hideCopyButton?: boolean;
|
||||
secondaryActionProps?: ComponentPropsWithoutRef<"button">;
|
||||
secondaryActionVariant?:
|
||||
| "default"
|
||||
| "destructive"
|
||||
| "destructive-outline"
|
||||
| "ghost"
|
||||
| "link"
|
||||
| "outline"
|
||||
| "secondary";
|
||||
/** Optional extra body shown after toggling “Show details” (e.g. a list of pending RPCs). */
|
||||
expandableContent?: ReactNode;
|
||||
expandableLabels?: { expand?: string; collapse?: string };
|
||||
@@ -90,6 +102,15 @@ const toastCornerOrbClass = cn(
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
);
|
||||
|
||||
function handleToastDismissClick(
|
||||
manager: typeof toastManager | typeof anchoredToastManager,
|
||||
toastId: ToastId,
|
||||
onClose: (() => void) | undefined,
|
||||
) {
|
||||
onClose?.();
|
||||
manager.close(toastId);
|
||||
}
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
@@ -232,6 +253,7 @@ interface ToastBodyDescriptor {
|
||||
readonly Icon: ToastIconComponent | null | undefined;
|
||||
readonly stackedActionLayout: boolean;
|
||||
readonly actionVariant: NonNullable<ThreadToastData["actionVariant"]>;
|
||||
readonly secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]>;
|
||||
readonly copyErrorText: string | null;
|
||||
readonly hasTrailingControls: boolean;
|
||||
readonly inlineContentEndPad: string;
|
||||
@@ -248,16 +270,21 @@ function deriveToastBodyDescriptor(toast: {
|
||||
toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end";
|
||||
const actionVariant: NonNullable<ThreadToastData["actionVariant"]> =
|
||||
toast.data?.actionVariant ?? "default";
|
||||
const secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]> =
|
||||
toast.data?.secondaryActionVariant ?? "outline";
|
||||
const copyErrorText =
|
||||
toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton
|
||||
? toast.description
|
||||
: null;
|
||||
const hasTrailingControls = copyErrorText !== null || toast.actionProps !== undefined;
|
||||
const hasSecondaryAction = toast.data?.secondaryActionProps !== undefined;
|
||||
const hasTrailingControls =
|
||||
copyErrorText !== null || toast.actionProps !== undefined || hasSecondaryAction;
|
||||
const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10";
|
||||
return {
|
||||
Icon,
|
||||
stackedActionLayout,
|
||||
actionVariant,
|
||||
secondaryActionVariant,
|
||||
copyErrorText,
|
||||
hasTrailingControls,
|
||||
inlineContentEndPad,
|
||||
@@ -277,22 +304,35 @@ function ToastBodyContent({
|
||||
copyErrorText,
|
||||
actionProps,
|
||||
actionVariant,
|
||||
secondaryActionVariant,
|
||||
hasTrailingControls,
|
||||
toastData,
|
||||
toastDescription,
|
||||
toastType,
|
||||
}: ToastBodyContentProps) {
|
||||
const secondaryActionProps = toastData?.secondaryActionProps;
|
||||
const leadingIcon = toastData?.leadingIcon;
|
||||
const { className: secondaryActionClassName, ...secondaryActionRest } =
|
||||
secondaryActionProps ?? {};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={cn("flex min-w-0 gap-2", !stackedActionLayout && "flex-1")}>
|
||||
{Icon && (
|
||||
{leadingIcon ? (
|
||||
<div
|
||||
className="flex h-lh w-4 shrink-0 items-center justify-center"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
{leadingIcon}
|
||||
</div>
|
||||
) : Icon ? (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 min-w-0 flex-1 flex-col gap-0.5",
|
||||
@@ -315,6 +355,16 @@ function ToastBodyContent({
|
||||
)}
|
||||
>
|
||||
{copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
|
||||
{secondaryActionProps ? (
|
||||
<button
|
||||
{...secondaryActionRest}
|
||||
className={cn(
|
||||
buttonVariants({ size: "xs", variant: secondaryActionVariant }),
|
||||
secondaryActionClassName,
|
||||
)}
|
||||
type="button"
|
||||
/>
|
||||
) : null}
|
||||
{actionProps ? (
|
||||
<Toast.Action
|
||||
className={cn(buttonVariants({ size: "xs", variant: actionVariant }), "shrink-0")}
|
||||
@@ -579,7 +629,9 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
aria-label="Dismiss notification"
|
||||
className={toastCornerOrbClass}
|
||||
data-slot="toast-close"
|
||||
onClick={() => toastManager.close(toast.id)}
|
||||
onClick={() =>
|
||||
handleToastDismissClick(toastManager, toast.id, toast.data?.onClose)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<XIcon className="size-3" strokeWidth={2.25} />
|
||||
@@ -670,7 +722,13 @@ function AnchoredToasts() {
|
||||
aria-label="Dismiss notification"
|
||||
className={toastCornerOrbClass}
|
||||
data-slot="toast-close"
|
||||
onClick={() => anchoredToastManager.close(toast.id)}
|
||||
onClick={() =>
|
||||
handleToastDismissClick(
|
||||
anchoredToastManager,
|
||||
toast.id,
|
||||
toast.data?.onClose,
|
||||
)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<XIcon className="size-3" strokeWidth={2.25} />
|
||||
|
||||
@@ -22,14 +22,14 @@ function createTestClient() {
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
},
|
||||
})),
|
||||
subscribeConfig: (listener: (event: any) => void) => {
|
||||
subscribeConfig: vi.fn((listener: (event: any) => void) => {
|
||||
configListeners.add(listener);
|
||||
return () => configListeners.delete(listener);
|
||||
},
|
||||
subscribeLifecycle: (listener: (event: any) => void) => {
|
||||
}),
|
||||
subscribeLifecycle: vi.fn((listener: (event: any) => void) => {
|
||||
lifecycleListeners.add(listener);
|
||||
return () => lifecycleListeners.delete(listener);
|
||||
},
|
||||
}),
|
||||
subscribeAuthAccess: () => () => undefined,
|
||||
refreshProviders: vi.fn(async () => undefined),
|
||||
upsertKeybinding: vi.fn(async () => undefined),
|
||||
@@ -237,4 +237,33 @@ describe("createEnvironmentConnection", () => {
|
||||
|
||||
await connection.dispose();
|
||||
});
|
||||
|
||||
it("skips primary lifecycle/config subscriptions when no handlers are registered", async () => {
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
const { client } = createTestClient();
|
||||
|
||||
const connection = createEnvironmentConnection({
|
||||
kind: "primary",
|
||||
knownEnvironment: {
|
||||
id: "env-1",
|
||||
label: "Local env",
|
||||
source: "manual",
|
||||
target: {
|
||||
httpBaseUrl: "http://example.test",
|
||||
wsBaseUrl: "ws://example.test",
|
||||
},
|
||||
environmentId,
|
||||
},
|
||||
client,
|
||||
applyShellEvent: vi.fn(),
|
||||
syncShellSnapshot: vi.fn(),
|
||||
applyTerminalEvent: vi.fn(),
|
||||
});
|
||||
|
||||
expect(client.server.subscribeLifecycle).not.toHaveBeenCalled();
|
||||
expect(client.server.subscribeConfig).not.toHaveBeenCalled();
|
||||
expect(client.orchestration.subscribeShell).toHaveBeenCalledOnce();
|
||||
|
||||
await connection.dispose();
|
||||
});
|
||||
});
|
||||
@@ -83,6 +83,8 @@ export function createEnvironmentConnection(
|
||||
|
||||
let disposed = false;
|
||||
const bootstrapGate = createBootstrapGate();
|
||||
const shouldObserveLifecycle = input.kind === "saved" || input.onWelcome !== undefined;
|
||||
const shouldObserveConfig = input.kind === "saved" || input.onConfigSnapshot !== undefined;
|
||||
|
||||
const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
|
||||
if (environmentId !== nextEnvironmentId) {
|
||||
@@ -92,28 +94,35 @@ export function createEnvironmentConnection(
|
||||
}
|
||||
};
|
||||
|
||||
const unsubLifecycle = input.client.server.subscribeLifecycle(
|
||||
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
|
||||
if (event.type !== "welcome") {
|
||||
return;
|
||||
}
|
||||
observeEnvironmentIdentity(
|
||||
event.payload.environment.environmentId,
|
||||
"server lifecycle welcome",
|
||||
);
|
||||
input.onWelcome?.(event.payload);
|
||||
},
|
||||
);
|
||||
const unsubLifecycle = shouldObserveLifecycle
|
||||
? input.client.server.subscribeLifecycle(
|
||||
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
|
||||
if (event.type !== "welcome") {
|
||||
return;
|
||||
}
|
||||
observeEnvironmentIdentity(
|
||||
event.payload.environment.environmentId,
|
||||
"server lifecycle welcome",
|
||||
);
|
||||
input.onWelcome?.(event.payload);
|
||||
},
|
||||
)
|
||||
: () => undefined;
|
||||
|
||||
const unsubConfig = input.client.server.subscribeConfig(
|
||||
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
|
||||
if (event.type !== "snapshot") {
|
||||
return;
|
||||
}
|
||||
observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
|
||||
input.onConfigSnapshot?.(event.config);
|
||||
},
|
||||
);
|
||||
const unsubConfig = shouldObserveConfig
|
||||
? input.client.server.subscribeConfig(
|
||||
(event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
|
||||
if (event.type !== "snapshot") {
|
||||
return;
|
||||
}
|
||||
observeEnvironmentIdentity(
|
||||
event.config.environment.environmentId,
|
||||
"server config snapshot",
|
||||
);
|
||||
input.onConfigSnapshot?.(event.config);
|
||||
},
|
||||
)
|
||||
: () => undefined;
|
||||
|
||||
const unsubShell = input.client.orchestration.subscribeShell(
|
||||
(item: Parameters<Parameters<WsRpcClient["orchestration"]["subscribeShell"]>[0]>[0]) => {
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockCreateEnvironmentConnection = vi.fn();
|
||||
const mockCreateWsRpcClient = vi.fn();
|
||||
const mockFetchRemoteSessionState = vi.fn();
|
||||
const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
|
||||
const mockListSavedEnvironmentRecords = vi.fn();
|
||||
const mockSavedEnvironmentRegistrySubscribe = vi.fn();
|
||||
const mockReadSavedEnvironmentBearerToken = vi.fn();
|
||||
const mockGetSavedEnvironmentRecord = vi.fn();
|
||||
|
||||
function MockWsTransport() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
vi.mock("../primary", () => ({
|
||||
getPrimaryKnownEnvironment: vi.fn(() => ({
|
||||
id: "env-1",
|
||||
label: "Primary environment",
|
||||
source: "window-origin",
|
||||
target: {
|
||||
httpBaseUrl: "http://127.0.0.1:3000/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3000/",
|
||||
},
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../remote/api", () => ({
|
||||
bootstrapRemoteBearerSession: vi.fn(),
|
||||
fetchRemoteEnvironmentDescriptor: vi.fn(),
|
||||
fetchRemoteSessionState: mockFetchRemoteSessionState,
|
||||
resolveRemoteWebSocketConnectionUrl: vi.fn(() => "ws://remote.example.test"),
|
||||
}));
|
||||
|
||||
vi.mock("./catalog", () => ({
|
||||
getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
|
||||
hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
|
||||
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
|
||||
persistSavedEnvironmentRecord: vi.fn(),
|
||||
readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
|
||||
removeSavedEnvironmentBearerToken: vi.fn(),
|
||||
useSavedEnvironmentRegistryStore: {
|
||||
subscribe: mockSavedEnvironmentRegistrySubscribe,
|
||||
getState: () => ({
|
||||
upsert: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
markConnected: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
}),
|
||||
},
|
||||
useSavedEnvironmentRuntimeStore: {
|
||||
getState: () => ({
|
||||
ensure: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}),
|
||||
},
|
||||
waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
|
||||
writeSavedEnvironmentBearerToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./connection", () => ({
|
||||
createEnvironmentConnection: mockCreateEnvironmentConnection,
|
||||
}));
|
||||
|
||||
vi.mock("../../rpc/wsRpcClient", () => ({
|
||||
createWsRpcClient: mockCreateWsRpcClient,
|
||||
}));
|
||||
|
||||
vi.mock("../../rpc/wsTransport", () => ({
|
||||
WsTransport: MockWsTransport,
|
||||
}));
|
||||
|
||||
vi.mock("~/composerDraftStore", () => ({
|
||||
markPromotedDraftThreadByRef: vi.fn(),
|
||||
markPromotedDraftThreadsByRef: vi.fn(),
|
||||
useComposerDraftStore: {
|
||||
getState: () => ({
|
||||
getDraftThreadByRef: vi.fn(() => null),
|
||||
clearDraftThread: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: vi.fn(() => ({
|
||||
persistence: {
|
||||
setSavedEnvironmentRegistry: vi.fn(async () => undefined),
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("~/lib/terminalStateCleanup", () => ({
|
||||
collectActiveTerminalThreadIds: vi.fn(() => []),
|
||||
}));
|
||||
|
||||
vi.mock("~/orchestrationEventEffects", () => ({
|
||||
deriveOrchestrationBatchEffects: vi.fn(() => ({
|
||||
promotedThreadRefs: [],
|
||||
invalidatedProviderState: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("~/lib/projectReactQuery", () => ({
|
||||
projectQueryKeys: {
|
||||
all: ["projects"],
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/lib/providerReactQuery", () => ({
|
||||
providerQueryKeys: {
|
||||
all: ["providers"],
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/store", () => ({
|
||||
useStore: {
|
||||
getState: () => ({
|
||||
syncServerShellSnapshot: vi.fn(),
|
||||
syncServerThreadDetail: vi.fn(),
|
||||
removeServerThreadDetail: vi.fn(),
|
||||
applyServerShellEvent: vi.fn(),
|
||||
}),
|
||||
},
|
||||
selectProjectsAcrossEnvironments: vi.fn(() => []),
|
||||
selectSidebarThreadSummaryByRef: vi.fn(() => null),
|
||||
selectThreadByRef: vi.fn(() => null),
|
||||
selectThreadsAcrossEnvironments: vi.fn(() => []),
|
||||
}));
|
||||
|
||||
vi.mock("~/terminalStateStore", () => ({
|
||||
useTerminalStateStore: {
|
||||
getState: () => ({
|
||||
applyTerminalEvent: vi.fn(),
|
||||
removeTerminalState: vi.fn(),
|
||||
clearTerminalSelection: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/uiStateStore", () => ({
|
||||
useUiStateStore: {
|
||||
getState: () => ({
|
||||
clearThreadUi: vi.fn(),
|
||||
syncPromotedDraftThreadRefs: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const savedRecord = {
|
||||
environmentId: EnvironmentId.make("env-saved"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.test/",
|
||||
wsBaseUrl: "wss://remote.example.test/",
|
||||
};
|
||||
|
||||
const configSnapshot = {
|
||||
environment: {
|
||||
environmentId: savedRecord.environmentId,
|
||||
label: "Remote environment",
|
||||
},
|
||||
};
|
||||
|
||||
function createClient() {
|
||||
return {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
server: {
|
||||
getConfig: vi.fn(async () => configSnapshot),
|
||||
subscribeConfig: vi.fn(() => () => undefined),
|
||||
subscribeLifecycle: vi.fn(() => () => undefined),
|
||||
subscribeAuthAccess: vi.fn(() => () => undefined),
|
||||
refreshProviders: vi.fn(async () => undefined),
|
||||
upsertKeybinding: vi.fn(async () => undefined),
|
||||
getSettings: vi.fn(async () => undefined),
|
||||
updateSettings: vi.fn(async () => undefined),
|
||||
},
|
||||
orchestration: {
|
||||
subscribeShell: vi.fn(() => () => undefined),
|
||||
subscribeThread: vi.fn(() => () => undefined),
|
||||
dispatchCommand: vi.fn(async () => undefined),
|
||||
getTurnDiff: vi.fn(async () => undefined),
|
||||
getFullThreadDiff: vi.fn(async () => undefined),
|
||||
},
|
||||
terminal: {
|
||||
open: vi.fn(async () => undefined),
|
||||
write: vi.fn(async () => undefined),
|
||||
resize: vi.fn(async () => undefined),
|
||||
clear: vi.fn(async () => undefined),
|
||||
restart: vi.fn(async () => undefined),
|
||||
close: vi.fn(async () => undefined),
|
||||
onEvent: vi.fn(() => () => undefined),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: vi.fn(async () => []),
|
||||
writeFile: vi.fn(async () => undefined),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(async () => undefined),
|
||||
},
|
||||
git: {
|
||||
pull: vi.fn(async () => undefined),
|
||||
refreshStatus: vi.fn(async () => undefined),
|
||||
onStatus: vi.fn(() => () => undefined),
|
||||
runStackedAction: vi.fn(async () => ({})),
|
||||
listBranches: vi.fn(async () => []),
|
||||
createWorktree: vi.fn(async () => undefined),
|
||||
removeWorktree: vi.fn(async () => undefined),
|
||||
createBranch: vi.fn(async () => undefined),
|
||||
checkout: vi.fn(async () => undefined),
|
||||
init: vi.fn(async () => undefined),
|
||||
resolvePullRequest: vi.fn(async () => undefined),
|
||||
preparePullRequestThread: vi.fn(async () => undefined),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("saved environment startup", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockFetchRemoteSessionState.mockResolvedValue({
|
||||
authenticated: true,
|
||||
role: "owner",
|
||||
});
|
||||
mockGetSavedEnvironmentRecord.mockImplementation((environmentId: EnvironmentId) =>
|
||||
environmentId === savedRecord.environmentId ? savedRecord : null,
|
||||
);
|
||||
mockListSavedEnvironmentRecords.mockReturnValue([savedRecord]);
|
||||
mockSavedEnvironmentRegistrySubscribe.mockReturnValue(() => undefined);
|
||||
mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
|
||||
mockReadSavedEnvironmentBearerToken.mockResolvedValue("saved-bearer-token");
|
||||
mockCreateWsRpcClient.mockImplementation(() => createClient());
|
||||
mockCreateEnvironmentConnection.mockImplementation((input) => {
|
||||
if (input.kind === "saved") {
|
||||
queueMicrotask(() => {
|
||||
input.onConfigSnapshot?.(configSnapshot);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
kind: input.kind,
|
||||
environmentId: input.knownEnvironment.environmentId,
|
||||
knownEnvironment: input.knownEnvironment,
|
||||
client: input.client,
|
||||
ensureBootstrapped: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
dispose: vi.fn(async () => undefined),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
const { resetEnvironmentServiceForTests } = await import("./service");
|
||||
await resetEnvironmentServiceForTests();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("uses the initial config snapshot instead of issuing an extra getConfig call", async () => {
|
||||
const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
|
||||
await import("./service");
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
const savedConnectionCall = mockCreateEnvironmentConnection.mock.calls.find(
|
||||
([input]) => input.kind === "saved",
|
||||
);
|
||||
expect(savedConnectionCall).toBeDefined();
|
||||
|
||||
const savedClient = savedConnectionCall?.[0]?.client;
|
||||
expect(savedClient.server.getConfig).not.toHaveBeenCalled();
|
||||
expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("coalesces hydration and registry sync so the initial saved connection only starts once", async () => {
|
||||
let finishHydration!: () => void;
|
||||
let finishTokenRead!: (token: string) => void;
|
||||
|
||||
mockWaitForSavedEnvironmentRegistryHydration.mockImplementation(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
finishHydration = () => resolve();
|
||||
}),
|
||||
);
|
||||
mockReadSavedEnvironmentBearerToken.mockImplementation(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
finishTokenRead = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
|
||||
await import("./service");
|
||||
|
||||
const stop = startEnvironmentConnectionService(new QueryClient());
|
||||
const registryListener = mockSavedEnvironmentRegistrySubscribe.mock.calls[0]?.[0];
|
||||
expect(registryListener).toBeTypeOf("function");
|
||||
|
||||
registryListener?.();
|
||||
finishHydration();
|
||||
await vi.waitFor(() => {
|
||||
expect(mockReadSavedEnvironmentBearerToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
finishTokenRead("saved-bearer-token");
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
const savedConnectionCalls = mockCreateEnvironmentConnection.mock.calls.filter(
|
||||
([input]) => input.kind === "saved",
|
||||
);
|
||||
expect(savedConnectionCalls).toHaveLength(1);
|
||||
expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
|
||||
|
||||
stop();
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
});
|
||||
@@ -369,7 +369,9 @@ describe("retainThreadDetailSubscription", () => {
|
||||
listEnvironmentConnections().some((connection) => connection.environmentId === environmentId),
|
||||
).toBe(false);
|
||||
|
||||
await reconnectSavedEnvironment(environmentId);
|
||||
const reconnectPromise = reconnectSavedEnvironment(environmentId);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
await reconnectPromise;
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(3);
|
||||
expect(mockSubscribeThread).toHaveBeenCalledTimes(2);
|
||||
|
||||
@@ -139,9 +139,70 @@ let lastBrowserResumeReconnectAt = Number.NEGATIVE_INFINITY;
|
||||
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
|
||||
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
|
||||
const BROWSER_RESUME_RECONNECT_COOLDOWN_MS = 2_000;
|
||||
const INITIAL_SERVER_CONFIG_SNAPSHOT_WAIT_MS = 150;
|
||||
const NOOP = () => undefined;
|
||||
const SSH_HTTP_STATUS_RE = /^\[ssh_http:(\d+)\]\s/u;
|
||||
|
||||
function createDeferredPromise<T>() {
|
||||
let resolve: ((value: T) => void) | null = null;
|
||||
const promise = new Promise<T>((nextResolve) => {
|
||||
resolve = nextResolve;
|
||||
});
|
||||
|
||||
return {
|
||||
promise,
|
||||
resolve: (value: T) => {
|
||||
resolve?.(value);
|
||||
resolve = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForConfigSnapshot(
|
||||
promise: Promise<ServerConfig>,
|
||||
timeoutMs: number,
|
||||
): Promise<ServerConfig | null> {
|
||||
return await new Promise<ServerConfig | null>((resolve) => {
|
||||
const timeoutId = globalThis.setTimeout(() => resolve(null), timeoutMs);
|
||||
promise.then(
|
||||
(config) => {
|
||||
clearTimeout(timeoutId);
|
||||
resolve(config);
|
||||
},
|
||||
() => {
|
||||
clearTimeout(timeoutId);
|
||||
resolve(null);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function createSavedEnvironmentSyncScheduler() {
|
||||
let activeSync: Promise<void> | null = null;
|
||||
let queued = false;
|
||||
|
||||
const run = async (): Promise<void> => {
|
||||
do {
|
||||
queued = false;
|
||||
await syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
|
||||
} while (queued);
|
||||
};
|
||||
|
||||
return () => {
|
||||
if (activeSync) {
|
||||
queued = true;
|
||||
return activeSync;
|
||||
}
|
||||
|
||||
activeSync = run()
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
activeSync = null;
|
||||
});
|
||||
|
||||
return activeSync;
|
||||
};
|
||||
}
|
||||
function compareAppliedProjectionVersion(
|
||||
left: { readonly sequence: number; readonly updatedAt: string | null },
|
||||
right: { readonly sequence: number; readonly updatedAt: string | null },
|
||||
@@ -233,7 +294,6 @@ function markAppliedProjectionEvent(environmentId: EnvironmentId, sequence: numb
|
||||
updatedAt: currentVersion?.updatedAt ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
function getThreadDetailSubscriptionKey(environmentId: EnvironmentId, threadId: ThreadId): string {
|
||||
return scopedThreadKey(scopeThreadRef(environmentId, threadId));
|
||||
}
|
||||
@@ -1284,6 +1344,7 @@ async function ensureSavedEnvironmentConnection(
|
||||
const client =
|
||||
options?.client ??
|
||||
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
|
||||
const initialConfigSnapshot = createDeferredPromise<ServerConfig>();
|
||||
const knownEnvironment = createKnownEnvironment({
|
||||
id: activeRecord.environmentId,
|
||||
label: activeRecord.label,
|
||||
@@ -1308,6 +1369,7 @@ async function ensureSavedEnvironmentConnection(
|
||||
);
|
||||
},
|
||||
onConfigSnapshot: (config) => {
|
||||
initialConfigSnapshot.resolve(config);
|
||||
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
|
||||
descriptor: config.environment,
|
||||
serverConfig: config,
|
||||
@@ -1323,12 +1385,18 @@ async function ensureSavedEnvironmentConnection(
|
||||
|
||||
try {
|
||||
try {
|
||||
const initialServerConfig =
|
||||
options?.serverConfig ??
|
||||
(await waitForConfigSnapshot(
|
||||
initialConfigSnapshot.promise,
|
||||
INITIAL_SERVER_CONFIG_SNAPSHOT_WAIT_MS,
|
||||
));
|
||||
await refreshSavedEnvironmentMetadata(
|
||||
activeRecord.environmentId,
|
||||
activeBearerToken,
|
||||
client,
|
||||
roleHint,
|
||||
options?.serverConfig ?? null,
|
||||
initialServerConfig,
|
||||
);
|
||||
} catch (error) {
|
||||
const isAuthError = activeRecord.desktopSsh
|
||||
@@ -1699,6 +1767,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
trailing: true,
|
||||
},
|
||||
);
|
||||
const requestSavedEnvironmentSync = createSavedEnvironmentSyncScheduler();
|
||||
|
||||
maybeCreatePrimaryEnvironmentConnection();
|
||||
|
||||
@@ -1706,11 +1775,11 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
if (!hasSavedEnvironmentRegistryHydrated()) {
|
||||
return;
|
||||
}
|
||||
void syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
|
||||
void requestSavedEnvironmentSync();
|
||||
});
|
||||
|
||||
void waitForSavedEnvironmentRegistryHydration()
|
||||
.then(() => syncSavedEnvironmentConnections(listSavedEnvironmentRecords()))
|
||||
.then(() => requestSavedEnvironmentSync())
|
||||
.catch(() => undefined);
|
||||
|
||||
const unsubscribeBrowserResumeReconnects = subscribeBrowserResumeReconnects();
|
||||
|
||||
@@ -26,6 +26,7 @@ import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
let clientSettingsHydrated = false;
|
||||
let clientSettingsHydrationPromise: Promise<void> | null = null;
|
||||
@@ -36,6 +37,12 @@ function emitClientSettingsChange() {
|
||||
}
|
||||
}
|
||||
|
||||
function emitClientSettingsHydrationChange() {
|
||||
for (const listener of clientSettingsHydrationListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function getClientSettingsSnapshot(): ClientSettings {
|
||||
return clientSettingsSnapshot;
|
||||
}
|
||||
@@ -45,6 +52,14 @@ function replaceClientSettingsSnapshot(settings: ClientSettings): void {
|
||||
emitClientSettingsChange();
|
||||
}
|
||||
|
||||
function setClientSettingsHydrated(nextHydrated: boolean): void {
|
||||
if (clientSettingsHydrated === nextHydrated) {
|
||||
return;
|
||||
}
|
||||
clientSettingsHydrated = nextHydrated;
|
||||
emitClientSettingsHydrationChange();
|
||||
}
|
||||
|
||||
function subscribeClientSettings(listener: () => void): () => void {
|
||||
clientSettingsListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
@@ -53,6 +68,18 @@ function subscribeClientSettings(listener: () => void): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
function getClientSettingsHydratedSnapshot(): boolean {
|
||||
return clientSettingsHydrated;
|
||||
}
|
||||
|
||||
function subscribeClientSettingsHydration(listener: () => void): () => void {
|
||||
clientSettingsHydrationListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
return () => {
|
||||
clientSettingsHydrationListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async function hydrateClientSettings(): Promise<void> {
|
||||
if (clientSettingsHydrated) {
|
||||
return;
|
||||
@@ -70,7 +97,7 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
} catch (error) {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
|
||||
} finally {
|
||||
clientSettingsHydrated = true;
|
||||
setClientSettingsHydrated(true);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -132,6 +159,14 @@ export function getClientSettings(): ClientSettings {
|
||||
return getClientSettingsSnapshot();
|
||||
}
|
||||
|
||||
export function useClientSettingsHydrated(): boolean {
|
||||
return useSyncExternalStore(
|
||||
subscribeClientSettingsHydration,
|
||||
getClientSettingsHydratedSnapshot,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
|
||||
const serverSettings = useServerSettings();
|
||||
const clientSettings = useSyncExternalStore(
|
||||
@@ -193,4 +228,5 @@ export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationPromise = null;
|
||||
clientSettingsListeners.clear();
|
||||
clientSettingsHydrationListeners.clear();
|
||||
}
|
||||
@@ -485,6 +485,19 @@ label:has(> select#reasoning-effort) select {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
@keyframes provider-update-pill-countdown {
|
||||
from {
|
||||
transform: scaleX(1);
|
||||
}
|
||||
to {
|
||||
transform: scaleX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.provider-update-pill-progress {
|
||||
animation: provider-update-pill-countdown var(--provider-update-pill-dismiss-ms) linear forwards;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
|
||||
@@ -85,6 +85,7 @@ const rpcClientMock = {
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
refreshProviders: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
upsertKeybinding: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
@@ -514,6 +515,34 @@ describe("wsApi", () => {
|
||||
expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("forwards provider updates directly to the RPC client", async () => {
|
||||
const nextProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
...defaultProviders[0]!,
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: "2026-01-03T00:00:00.000Z",
|
||||
finishedAt: "2026-01-03T00:00:01.000Z",
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
},
|
||||
];
|
||||
rpcClientMock.server.updateProvider.mockResolvedValue({ providers: nextProviders });
|
||||
const { createLocalApi } = await import("./localApi");
|
||||
|
||||
const api = createLocalApi(rpcClientMock as never);
|
||||
|
||||
await expect(
|
||||
api.server.updateProvider({ provider: ProviderDriverKind.make("codex") }),
|
||||
).resolves.toEqual({
|
||||
providers: nextProviders,
|
||||
});
|
||||
expect(rpcClientMock.server.updateProvider).toHaveBeenCalledWith({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards server settings updates directly to the RPC client", async () => {
|
||||
const nextSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
@@ -573,6 +602,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
@@ -634,6 +664,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
|
||||
@@ -125,10 +125,18 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
|
||||
rpcClient
|
||||
? rpcClient.server.refreshProviders()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
updateProvider: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.updateProvider(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
upsertKeybinding: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.upsertKeybinding(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
removeKeybinding: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.removeKeybinding(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
getSettings: () =>
|
||||
rpcClient ? rpcClient.server.getSettings() : Promise.reject(unavailableLocalBackendError()),
|
||||
updateSettings: (patch) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { removeLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import {
|
||||
dismissProviderUpdateNotification,
|
||||
isProviderUpdateNotificationDismissed,
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
} from "./providerUpdateDismissal";
|
||||
|
||||
describe("providerUpdateDismissal", () => {
|
||||
beforeEach(() => {
|
||||
removeLocalStorageItem(PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY);
|
||||
});
|
||||
|
||||
it("persists provider update dismissals by notification key", () => {
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(false);
|
||||
|
||||
dismissProviderUpdateNotification("opencode:1.14.33");
|
||||
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(true);
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.34")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
|
||||
|
||||
export const PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY = "t3code:provider-update-dismissals:v1";
|
||||
|
||||
const ProviderUpdateDismissalsSchema = Schema.Struct({
|
||||
keys: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
type ProviderUpdateDismissals = typeof ProviderUpdateDismissalsSchema.Type;
|
||||
|
||||
function readProviderUpdateDismissals(): ProviderUpdateDismissals {
|
||||
try {
|
||||
return (
|
||||
getLocalStorageItem(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
ProviderUpdateDismissalsSchema,
|
||||
) ?? {
|
||||
keys: [],
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
return { keys: [] };
|
||||
}
|
||||
}
|
||||
|
||||
function writeProviderUpdateDismissals(document: ProviderUpdateDismissals): void {
|
||||
try {
|
||||
setLocalStorageItem(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
document,
|
||||
ProviderUpdateDismissalsSchema,
|
||||
);
|
||||
} catch {
|
||||
// Dismissal state is best-effort UI state; a storage failure should not block the toast.
|
||||
}
|
||||
}
|
||||
|
||||
export function isProviderUpdateNotificationDismissed(
|
||||
dismissalKey: string | null | undefined,
|
||||
): boolean {
|
||||
if (!dismissalKey) {
|
||||
return false;
|
||||
}
|
||||
return readProviderUpdateDismissals().keys.includes(dismissalKey);
|
||||
}
|
||||
|
||||
export function dismissProviderUpdateNotification(dismissalKey: string | null | undefined): void {
|
||||
const trimmedKey = dismissalKey?.trim();
|
||||
if (!trimmedKey) {
|
||||
return;
|
||||
}
|
||||
const document = readProviderUpdateDismissals();
|
||||
if (document.keys.includes(trimmedKey)) {
|
||||
return;
|
||||
}
|
||||
writeProviderUpdateDismissals({
|
||||
keys: [...document.keys, trimmedKey],
|
||||
});
|
||||
}
|
||||
|
||||
export function useDismissedProviderUpdateNotificationKeys() {
|
||||
const [dismissals, setDismissals] = useLocalStorage(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
{ keys: [] },
|
||||
ProviderUpdateDismissalsSchema,
|
||||
);
|
||||
const dismissedKeys = dismissals.keys;
|
||||
|
||||
const dismissedKeySet = useMemo(() => new Set(dismissedKeys), [dismissedKeys]);
|
||||
|
||||
const dismissNotificationKey = useCallback(
|
||||
(key: string) => {
|
||||
const trimmedKey = key.trim();
|
||||
if (trimmedKey.length === 0 || dismissedKeySet.has(trimmedKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDismissals({
|
||||
keys: [...dismissedKeys, trimmedKey],
|
||||
});
|
||||
},
|
||||
[dismissedKeySet, dismissedKeys, setDismissals],
|
||||
);
|
||||
|
||||
return {
|
||||
dismissedNotificationKeys: dismissedKeySet,
|
||||
dismissNotificationKey,
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
|
||||
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
|
||||
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
@@ -44,6 +46,16 @@ const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
|
||||
path: '/source-control',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
|
||||
id: '/providers',
|
||||
path: '/providers',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({
|
||||
id: '/keybindings',
|
||||
path: '/keybindings',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
|
||||
id: '/general',
|
||||
path: '/general',
|
||||
@@ -78,6 +90,8 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
@@ -88,6 +102,8 @@ export interface FileRoutesByTo {
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -101,6 +117,8 @@ export interface FileRoutesById {
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -115,6 +133,8 @@ export interface FileRouteTypes {
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/$environmentId/$threadId'
|
||||
| '/draft/$draftId'
|
||||
@@ -125,6 +145,8 @@ export interface FileRouteTypes {
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/'
|
||||
| '/$environmentId/$threadId'
|
||||
@@ -137,6 +159,8 @@ export interface FileRouteTypes {
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/_chat/'
|
||||
| '/_chat/$environmentId/$threadId'
|
||||
@@ -186,6 +210,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsSourceControlRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/providers': {
|
||||
id: '/settings/providers'
|
||||
path: '/providers'
|
||||
fullPath: '/settings/providers'
|
||||
preLoaderRoute: typeof SettingsProvidersRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/keybindings': {
|
||||
id: '/settings/keybindings'
|
||||
path: '/keybindings'
|
||||
fullPath: '/settings/keybindings'
|
||||
preLoaderRoute: typeof SettingsKeybindingsRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/general': {
|
||||
id: '/settings/general'
|
||||
path: '/general'
|
||||
@@ -242,6 +280,8 @@ interface SettingsRouteChildren {
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
|
||||
SettingsProvidersRoute: typeof SettingsProvidersRoute
|
||||
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
|
||||
}
|
||||
|
||||
@@ -249,6 +289,8 @@ const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
|
||||
SettingsProvidersRoute: SettingsProvidersRoute,
|
||||
SettingsSourceControlRoute: SettingsSourceControlRoute,
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { CommandPalette } from "../components/CommandPalette";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
|
||||
import {
|
||||
SlowRpcAckToastCoordinator,
|
||||
WebSocketConnectionCoordinator,
|
||||
@@ -136,6 +137,7 @@ function RootRouteView() {
|
||||
<SshPasswordPromptDialog />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <SlowRpcAckToastCoordinator /> : null}
|
||||
{primaryEnvironmentAuthenticated ? (
|
||||
@@ -286,6 +288,7 @@ function EventRouter() {
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
|
||||
const lastKeybindingsSuccessToastAtRef = useRef(0);
|
||||
const disposedRef = useRef(false);
|
||||
const serverConfig = useServerConfig();
|
||||
|
||||
@@ -352,6 +355,11 @@ function EventRouter() {
|
||||
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
const now = Date.now();
|
||||
if (now - lastKeybindingsSuccessToastAtRef.current < 2_000) {
|
||||
return;
|
||||
}
|
||||
lastKeybindingsSuccessToastAtRef.current = now;
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
|
||||
@@ -28,7 +28,7 @@ const DiffPanel = lazy(() => import("../components/DiffPanel"));
|
||||
const DIFF_INLINE_SIDEBAR_WIDTH_STORAGE_KEY = "chat_diff_sidebar_width";
|
||||
const DIFF_INLINE_DEFAULT_WIDTH = "clamp(24rem,34vw,36rem)";
|
||||
const DIFF_INLINE_SIDEBAR_MIN_WIDTH = 22 * 16;
|
||||
const DIFF_INLINE_SIDEBAR_MAX_WIDTH = 36 * 16;
|
||||
const DIFF_INLINE_SIDEBAR_MAX_WIDTH = 256 * 16;
|
||||
const COMPOSER_COMPACT_MIN_LEFT_CONTROLS_WIDTH_PX = 208;
|
||||
|
||||
const DiffLoadingFallback = (props: { mode: DiffPanelMode }) => {
|
||||
|
||||
@@ -2,6 +2,10 @@ import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { GeneralSettingsPanel } from "../components/settings/SettingsPanels";
|
||||
|
||||
function SettingsGeneralRoute() {
|
||||
return <GeneralSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/general")({
|
||||
component: GeneralSettingsPanel,
|
||||
component: SettingsGeneralRoute,
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { KeybindingsSettingsPanel } from "../components/settings/KeybindingsSettings";
|
||||
|
||||
export const Route = createFileRoute("/settings/keybindings")({
|
||||
component: KeybindingsSettingsPanel,
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { ProviderSettingsPanel } from "../components/settings/SettingsPanels";
|
||||
|
||||
function SettingsProvidersRoute() {
|
||||
return <ProviderSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/providers")({
|
||||
component: SettingsProvidersRoute,
|
||||
});
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user