Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
602ee516a0 | ||
|
|
390e1c31e6 |
No files matched your search
@@ -1,12 +1,21 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it, vi } from "@effect/vitest";
|
||||
import { ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
@@ -22,19 +31,31 @@ const defaultModelSelection = {
|
||||
model: "gpt-5-codex",
|
||||
} as const;
|
||||
|
||||
const TEST_NOW = DateTime.makeUnsafe("2026-04-14T00:30:00.000Z");
|
||||
const TEST_NOW_ISO = DateTime.formatIso(TEST_NOW);
|
||||
const STALE_LAST_SEEN_AT = DateTime.formatIso(
|
||||
DateTime.subtractDuration(TEST_NOW, Duration.seconds(2)),
|
||||
);
|
||||
const FRESH_LAST_SEEN_AT = DateTime.formatIso(
|
||||
DateTime.subtractDuration(TEST_NOW, Duration.millis(500)),
|
||||
);
|
||||
async function waitFor(
|
||||
predicate: () => boolean | Promise<boolean>,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<void> {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (await predicate()) {
|
||||
return;
|
||||
}
|
||||
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
|
||||
throw new Error("Timed out waiting for expectation.");
|
||||
}
|
||||
await Effect.runPromise(Effect.yieldNow);
|
||||
return poll();
|
||||
};
|
||||
|
||||
return poll();
|
||||
}
|
||||
|
||||
const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
|
||||
discard: true,
|
||||
});
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
|
||||
function makeReadModel(
|
||||
threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
@@ -49,11 +70,12 @@ function makeReadModel(
|
||||
} | null;
|
||||
}>,
|
||||
) {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const projectId = ProjectId.make("project-provider-session-reaper");
|
||||
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: projectId,
|
||||
@@ -61,8 +83,8 @@ function makeReadModel(
|
||||
workspaceRoot: "/tmp/provider-reaper-project",
|
||||
defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt: TEST_NOW_ISO,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
@@ -75,8 +97,8 @@ function makeReadModel(
|
||||
runtimeMode: "full-access" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: TEST_NOW_ISO,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -93,99 +115,113 @@ function makeReadModel(
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(input: {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThreshold: Duration.seconds(1),
|
||||
sweepInterval: Duration.seconds(60),
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(ProviderService)({
|
||||
stopSession,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
Option.fromNullishOr(input.readModel.threads.find((thread) => thread.id === threadId)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(TestClock.layer()),
|
||||
);
|
||||
|
||||
return { layer, stopSession, stoppedThreadIds };
|
||||
}
|
||||
|
||||
function seedSession(input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerName: "codex" | "claudeAgent";
|
||||
readonly status?: "starting" | "running" | "stopped" | "error";
|
||||
readonly lastSeenAt: string;
|
||||
readonly resumeOpaque: string;
|
||||
}) {
|
||||
return Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
yield* repository.upsert({
|
||||
threadId: input.threadId,
|
||||
providerName: input.providerName,
|
||||
providerInstanceId: null,
|
||||
adapterKey: input.providerName,
|
||||
runtimeMode: "full-access",
|
||||
status: input.status ?? "running",
|
||||
lastSeenAt: input.lastSeenAt,
|
||||
resumeCursor: {
|
||||
opaque: input.resumeOpaque,
|
||||
},
|
||||
runtimePayload: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const runInitialSweep = Effect.gen(function* () {
|
||||
const reaper = yield* ProviderSessionReaper;
|
||||
yield* reaper.start();
|
||||
yield* drainFibers;
|
||||
});
|
||||
|
||||
function runWithHarness<A, E, R>(
|
||||
harness: ReturnType<typeof createHarness>,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
yield* TestClock.setTime(TEST_NOW.epochMilliseconds);
|
||||
return yield* effect;
|
||||
}).pipe(Effect.scoped, Effect.provide(harness.layer));
|
||||
}
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
it.effect("reaps stale persisted sessions without active turns", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
async function createHarness(input: {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession,
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
getInstanceInfo: (instanceId) => {
|
||||
const driverKind = ProviderDriverKind.make(String(instanceId));
|
||||
return Effect.succeed({
|
||||
instanceId,
|
||||
driverKind,
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
continuationIdentity: {
|
||||
driverKind,
|
||||
continuationKey: `${driverKind}:instance:${instanceId}`,
|
||||
},
|
||||
});
|
||||
},
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => 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"),
|
||||
getFullThreadDiffContext: () => 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),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
return { stopSession, stoppedThreadIds };
|
||||
}
|
||||
|
||||
it("reaps stale persisted sessions without active turns", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stale");
|
||||
const harness = createHarness({
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
@@ -196,33 +232,46 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-stale",
|
||||
});
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.deepStrictEqual(harness.stopSession.mock.calls[0]?.[0], { threadId });
|
||||
assert.isTrue(harness.stoppedThreadIds.has(threadId));
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stale",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
|
||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
|
||||
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
|
||||
});
|
||||
|
||||
it.effect("skips stale sessions when the thread still has an active turn", () => {
|
||||
it("skips stale sessions when the thread still has an active turn", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-active-turn");
|
||||
const turnId = TurnId.make("turn-reaper-active");
|
||||
const harness = createHarness({
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
@@ -233,34 +282,45 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-active-turn",
|
||||
});
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||
const remaining = yield* repository.getByThreadId({ threadId });
|
||||
assert.isTrue(Option.isSome(remaining));
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-active-turn",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it.effect("does not reap sessions that are still within the inactivity threshold", () => {
|
||||
it("does not reap sessions that are still within the inactivity threshold", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-fresh");
|
||||
const harness = createHarness({
|
||||
const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
@@ -271,34 +331,45 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
lastSeenAt: FRESH_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-fresh",
|
||||
});
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||
const remaining = yield* repository.getByThreadId({ threadId });
|
||||
assert.isTrue(Option.isSome(remaining));
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor: {
|
||||
opaque: "resume-fresh",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it.effect("skips persisted sessions that are already marked stopped", () => {
|
||||
it("skips persisted sessions that are already marked stopped", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stopped");
|
||||
const harness = createHarness({
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
@@ -309,36 +380,46 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
status: "stopped",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-stopped",
|
||||
});
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.equal(harness.stopSession.mock.calls.length, 0);
|
||||
const remaining = yield* repository.getByThreadId({ threadId });
|
||||
assert.isTrue(Option.isSome(remaining));
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "stopped",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stopped",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it.effect("continues reaping other sessions when one stop attempt fails", () => {
|
||||
it("continues reaping other sessions when one stop attempt fails", async () => {
|
||||
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
|
||||
const harness = createHarness({
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: failedThreadId,
|
||||
@@ -349,7 +430,7 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -361,7 +442,7 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
@@ -375,37 +456,58 @@ describe("ProviderSessionReaper", () => {
|
||||
)
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId: failedThreadId,
|
||||
providerName: "claudeAgent",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-failure",
|
||||
});
|
||||
yield* seedSession({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-success",
|
||||
});
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.equal(harness.stopSession.mock.calls.length, 2);
|
||||
assert.deepStrictEqual(
|
||||
new Set(harness.stopSession.mock.calls.map(([request]) => request.threadId)),
|
||||
new Set([failedThreadId, reapedThreadId]),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: failedThreadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-failure",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-success",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
failedThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("continues reaping other sessions when one stop attempt defects", () => {
|
||||
it("continues reaping other sessions when one stop attempt defects", async () => {
|
||||
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
|
||||
const harness = createHarness({
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: defectThreadId,
|
||||
@@ -416,7 +518,7 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -428,7 +530,7 @@ describe("ProviderSessionReaper", () => {
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: TEST_NOW_ISO,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
@@ -437,30 +539,50 @@ describe("ProviderSessionReaper", () => {
|
||||
? Effect.die(new Error("simulated stop defect"))
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
return runWithHarness(
|
||||
harness,
|
||||
Effect.gen(function* () {
|
||||
yield* seedSession({
|
||||
threadId: defectThreadId,
|
||||
providerName: "claudeAgent",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-defect",
|
||||
});
|
||||
yield* seedSession({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
lastSeenAt: STALE_LAST_SEEN_AT,
|
||||
resumeOpaque: "resume-after-defect",
|
||||
});
|
||||
yield* runInitialSweep;
|
||||
|
||||
assert.equal(harness.stopSession.mock.calls.length, 2);
|
||||
assert.deepStrictEqual(
|
||||
new Set(harness.stopSession.mock.calls.map(([request]) => request.threadId)),
|
||||
new Set([defectThreadId, reapedThreadId]),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: defectThreadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-after-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
defectThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -13,17 +13,12 @@ import {
|
||||
} from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService } from "../Services/ProviderService.ts";
|
||||
|
||||
const MINIMUM_DURATION = Duration.millis(1);
|
||||
const DEFAULT_INACTIVITY_THRESHOLD = Duration.minutes(30);
|
||||
const DEFAULT_SWEEP_INTERVAL = Duration.minutes(5);
|
||||
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface ProviderSessionReaperLiveOptions {
|
||||
readonly inactivityThreshold?: Duration.Input;
|
||||
readonly sweepInterval?: Duration.Input;
|
||||
}
|
||||
|
||||
function normalizeDuration(input: Duration.Input | undefined, fallback: Duration.Duration) {
|
||||
return Duration.max(Duration.fromInputUnsafe(input ?? fallback), MINIMUM_DURATION);
|
||||
readonly inactivityThresholdMs?: number;
|
||||
readonly sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
@@ -32,15 +27,15 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const inactivityThreshold = normalizeDuration(
|
||||
options?.inactivityThreshold,
|
||||
DEFAULT_INACTIVITY_THRESHOLD,
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
|
||||
);
|
||||
const sweepInterval = normalizeDuration(options?.sweepInterval, DEFAULT_SWEEP_INTERVAL);
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = yield* DateTime.now;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
let reapedCount = 0;
|
||||
|
||||
for (const binding of bindings) {
|
||||
@@ -48,8 +43,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
continue;
|
||||
}
|
||||
|
||||
const lastSeen = DateTime.make(binding.lastSeenAt);
|
||||
if (Option.isNone(lastSeen)) {
|
||||
const lastSeenMs = Date.parse(binding.lastSeenAt);
|
||||
if (Number.isNaN(lastSeenMs)) {
|
||||
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
@@ -58,9 +53,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
continue;
|
||||
}
|
||||
|
||||
const idleDuration = DateTime.distance(lastSeen.value, now);
|
||||
const idleDurationMs = Duration.toMillis(idleDuration);
|
||||
if (Duration.isLessThan(idleDuration, inactivityThreshold)) {
|
||||
const idleDurationMs = now - lastSeenMs;
|
||||
if (idleDurationMs < inactivityThresholdMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -123,13 +117,13 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
defect,
|
||||
}),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced(sweepInterval)),
|
||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.logInfo("provider.session.reaper.started", {
|
||||
inactivityThresholdMs: Duration.toMillis(inactivityThreshold),
|
||||
sweepIntervalMs: Duration.toMillis(sweepInterval),
|
||||
inactivityThresholdMs,
|
||||
sweepIntervalMs,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,12 +5,26 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import {
|
||||
memo,
|
||||
useMemo,
|
||||
useState,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
type ChangeEvent,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { ModelListRow } from "./ModelListRow";
|
||||
import { ModelPickerSidebar } from "./ModelPickerSidebar";
|
||||
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import {
|
||||
buildModelPickerSearchText,
|
||||
normalizeModelPickerSearchQuery,
|
||||
scoreModelPickerSearch,
|
||||
} from "./modelPickerSearch";
|
||||
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox";
|
||||
import { ModelEsque } from "./providerIconUtils";
|
||||
import {
|
||||
@@ -43,6 +57,10 @@ type ModelPickerItem = {
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
|
||||
const MODEL_PICKER_SEARCH_ICON = (
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
);
|
||||
|
||||
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
|
||||
// can contain colons (e.g. some vendor model ids), so we only split on the
|
||||
// first colon — anything after that is the slug.
|
||||
@@ -57,6 +75,64 @@ function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; s
|
||||
};
|
||||
}
|
||||
|
||||
const ModelPickerSearchInput = memo(function ModelPickerSearchInput(props: {
|
||||
inputRef: RefObject<HTMLInputElement | null>;
|
||||
onNormalizedQueryChange: (query: string) => void;
|
||||
onRequestClose: (() => void) | undefined;
|
||||
onHighlightedModelSelect: () => boolean;
|
||||
}) {
|
||||
const { inputRef, onHighlightedModelSelect, onNormalizedQueryChange, onRequestClose } = props;
|
||||
const [rawSearchQuery, setRawSearchQuery] = useState("");
|
||||
const lastNormalizedSearchQueryRef = useRef("");
|
||||
|
||||
const handleSearchQueryChange = useCallback(
|
||||
(event: ChangeEvent<HTMLInputElement>) => {
|
||||
const nextRawSearchQuery = event.target.value;
|
||||
setRawSearchQuery(nextRawSearchQuery);
|
||||
|
||||
const nextNormalizedSearchQuery = normalizeModelPickerSearchQuery(nextRawSearchQuery);
|
||||
if (nextNormalizedSearchQuery === lastNormalizedSearchQueryRef.current) {
|
||||
return;
|
||||
}
|
||||
lastNormalizedSearchQueryRef.current = nextNormalizedSearchQuery;
|
||||
onNormalizedQueryChange(nextNormalizedSearchQuery);
|
||||
},
|
||||
[onNormalizedQueryChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComboboxInput
|
||||
ref={inputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={MODEL_PICKER_SEARCH_ICON}
|
||||
value={rawSearchQuery}
|
||||
onChange={handleSearchQueryChange}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onRequestClose?.();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter" && onHighlightedModelSelect()) {
|
||||
(event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onTouchStart={(event) => event.stopPropagation()}
|
||||
size="sm"
|
||||
unstyled
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
/** The instance currently selected in the composer (combobox "value"). */
|
||||
activeInstanceId: ProviderInstanceId;
|
||||
@@ -96,7 +172,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
getModelDisabledReason,
|
||||
onInstanceModelChange,
|
||||
} = props;
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [normalizedSearchQuery, setNormalizedSearchQuery] = useState("");
|
||||
const [showTopScrollFade, setShowTopScrollFade] = useState(false);
|
||||
const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -221,7 +297,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
}, [modelOptionsByInstance, entryByInstanceId, readyInstanceSet]);
|
||||
|
||||
const isLocked = props.lockedProvider !== null;
|
||||
const isSearching = searchQuery.trim().length > 0;
|
||||
const isSearching = normalizedSearchQuery.length > 0;
|
||||
const lockedDisabledInstanceIds = useMemo(() => {
|
||||
if (!isLocked) {
|
||||
return undefined;
|
||||
@@ -261,7 +337,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
let result = flatModels;
|
||||
|
||||
// Apply tokenized fuzzy search across the combined provider/model search fields.
|
||||
if (searchQuery.trim()) {
|
||||
if (normalizedSearchQuery) {
|
||||
const rankedMatches = result
|
||||
.map((model) => ({
|
||||
model,
|
||||
@@ -274,7 +350,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
providerDisplayName: model.instanceDisplayName,
|
||||
isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
|
||||
},
|
||||
searchQuery,
|
||||
normalizedSearchQuery,
|
||||
),
|
||||
isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
|
||||
tieBreaker: buildModelPickerSearchText({
|
||||
@@ -357,8 +433,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
flatModels,
|
||||
instanceOrder,
|
||||
matchesLockedProvider,
|
||||
normalizedSearchQuery,
|
||||
props.lockedProvider,
|
||||
searchQuery,
|
||||
selectedInstanceId,
|
||||
]);
|
||||
|
||||
@@ -385,6 +461,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
},
|
||||
[entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
|
||||
);
|
||||
const handleHighlightedModelSelect = useCallback(() => {
|
||||
const highlightedModelKey = highlightedModelKeyRef.current;
|
||||
if (!highlightedModelKey) {
|
||||
return false;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(highlightedModelKey);
|
||||
handleModelSelect(slug, instanceId);
|
||||
return true;
|
||||
}, [handleModelSelect]);
|
||||
|
||||
const toggleFavorite = useCallback(
|
||||
(instanceId: ProviderInstanceId, model: string) => {
|
||||
@@ -577,42 +662,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
props.onRequestClose?.();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && highlightedModelKeyRef.current) {
|
||||
(
|
||||
e as typeof e & { preventBaseUIHandler?: () => void }
|
||||
).preventBaseUIHandler?.();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const { instanceId, slug } = splitInstanceModelKey(
|
||||
highlightedModelKeyRef.current,
|
||||
);
|
||||
handleModelSelect(slug, instanceId);
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
size="sm"
|
||||
unstyled
|
||||
<ModelPickerSearchInput
|
||||
inputRef={searchInputRef}
|
||||
onNormalizedQueryChange={setNormalizedSearchQuery}
|
||||
onRequestClose={props.onRequestClose}
|
||||
onHighlightedModelSelect={handleHighlightedModelSelect}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import {
|
||||
buildModelPickerSearchText,
|
||||
normalizeModelPickerSearchQuery,
|
||||
scoreModelPickerSearch,
|
||||
} from "./modelPickerSearch";
|
||||
|
||||
describe("buildModelPickerSearchText", () => {
|
||||
it("builds provider-agnostic search text from generic fields", () => {
|
||||
@@ -15,6 +19,13 @@ describe("buildModelPickerSearchText", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeModelPickerSearchQuery", () => {
|
||||
it("collapses whitespace-only changes to the same semantic query", () => {
|
||||
expect(normalizeModelPickerSearchQuery(" ")).toBe("");
|
||||
expect(normalizeModelPickerSearchQuery(" Claude Opus ")).toBe("claude opus");
|
||||
});
|
||||
});
|
||||
|
||||
describe("scoreModelPickerSearch", () => {
|
||||
it("matches typo-tolerant multi-token queries", () => {
|
||||
expect(
|
||||
|
||||
@@ -52,13 +52,16 @@ export function buildModelPickerSearchText(model: ModelPickerSearchableModel): s
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeModelPickerSearchQuery(query: string): string {
|
||||
return normalizeSearchQuery(query).replace(/\s+/gu, " ");
|
||||
}
|
||||
|
||||
export function scoreModelPickerSearch(
|
||||
model: ModelPickerSearchableModel,
|
||||
query: string,
|
||||
): number | null {
|
||||
const tokens = normalizeSearchQuery(query)
|
||||
.split(/\s+/u)
|
||||
.filter((token) => token.length > 0);
|
||||
const normalizedQuery = normalizeModelPickerSearchQuery(query);
|
||||
const tokens = normalizedQuery.length > 0 ? normalizedQuery.split(" ") : [];
|
||||
|
||||
if (tokens.length === 0) {
|
||||
return 0;
|
||||
|
||||
Reference in new issue
Block a user