Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion apps/server/src/provider/ProviderRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,11 @@ const makeWorkspaceRescanHarness = Effect.gen(function* () {
const nextScan = Effect.fnUntraced(function* (cwd: string) {
const scan = yield* Queue.take(scans);
assert.equal(scan.cwd, cwd);
return (name: string) => Deferred.succeed(scan.result, snapshot(name));
return (name: string, workspaceModels?: ProviderWorkspaceSnapshot["workspaceModels"]) =>
Deferred.succeed(scan.result, {
...snapshot(name),
...(workspaceModels ? { workspaceModels } : {}),
});
});
const refresh = (cwd: string, fresh = false) =>
registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh });
Expand Down Expand Up @@ -2798,6 +2802,21 @@ it.layer(
}),
);

it.effect("stamps a rescan that changed only the directory's models", () =>
Effect.gen(function* () {
const h = yield* makeWorkspaceRescanHarness;
yield* h.seed("/barrier");
yield* h.seed("/workspace");
yield* Queue.offer(h.first.rescans, "/workspace");
const complete = yield* h.nextScan("/workspace");
yield* complete("initial", [
{ slug: "vendor/live", name: "Live", isCustom: false, capabilities: null },
]);
yield* h.drainRescans;
assert.isString(yield* h.rescannedAtOf);
}),
);

it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () =>
Effect.gen(function* () {
const h = yield* makeWorkspaceRescanHarness;
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/provider/ProviderRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,7 @@ export const layer = Layer.effect(
return input.rescan &&
!(
Equal.equals(rescanned?.skills, held?.skills) &&
Equal.equals(rescanned?.models, held?.models) &&
Equal.equals(rescanned?.slashCommands, held?.slashCommands)
)
? { ...scanned, workspaceRescannedAt: scannedAt }
Expand Down
2 changes: 1 addition & 1 deletion packages/provider-core/src/server/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export interface ProviderInstance {
cwd: string,
) => Effect.Effect<ProviderWorkspaceSnapshot, ProviderDriverError>;
/**
* Cwds whose workspace skills may have changed. The registry rescans only cwds already
* Cwds whose workspace skills or models may have changed. The registry rescans only cwds already
* requested. The stream must end when the instance is torn down.
*/
readonly workspaceRescans?: Stream.Stream<string>;
Expand Down
92 changes: 69 additions & 23 deletions packages/provider-opencode/src/server/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import * as Option from "effect/Option";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as HttpClient from "effect/http/HttpClient";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
Expand All @@ -38,6 +39,7 @@ import { loadOpenCode2Catalog, loadOpenCode2DirectoryCatalog } from "./openCode2
import {
checkOpenCodeProviderStatus,
loadOpenCode2Workspace,
makeOpenCode2CatalogWatch,
makeOpenCode2ModelLoader,
makePendingOpenCodeProvider,
openCode2CommandsToServerProviderSlashCommands,
Expand All @@ -47,6 +49,8 @@ import {
openCodeCommandsToServerProviderSlashCommands,
openCodeProviderModels,
readSettledOpenCode2Catalog,
withOpenCode2Catalog,
type OpenCode2Model,
} from "./status.ts";
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
Expand Down Expand Up @@ -397,11 +401,15 @@ export const OpenCodeDriver: ProviderDriver<
Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
),
});
const catalogWatch = yield* makeOpenCode2CatalogWatch();
const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
// An external server may not have the host's cwd; without a location it uses its own default.
openCode2Server.withConnection(({ client, external }) =>
loadOpenCode2Catalog(client, external ? undefined : host.paths.cwd),
),
openCode2Server.withConnection(({ client, events, external, url }) => {
const directory = external ? undefined : host.paths.cwd;
return catalogWatch
.follow(url, events, loadOpenCode2DirectoryCatalog(client, directory))
.pipe(Effect.andThen(loadOpenCode2Catalog(client, directory)));
}),
processEnv,
);
const listOpenCode2Workspace = (cwd: string) =>
Expand Down Expand Up @@ -661,17 +669,43 @@ export const OpenCodeDriver: ProviderDriver<
makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
checkUsageLimits,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
resolveMaintenance().pipe(
Effect.flatMap((maintenanceCapabilities) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
}),
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
let enriched = snapshot;
let catalog: ReadonlyArray<OpenCode2Model> | undefined;
// Each publication replaces the whole snapshot, so both sources publish their combination.
const publishing = Semaphore.makeUnsafe(1);
const publish = publishing.withPermit(
Effect.suspend(() =>
publishSnapshot(
catalog === undefined
? enriched
: withOpenCode2Catalog(enriched, effectiveConfig, catalog),
),
),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
);
return Effect.all(
[
resolveMaintenance().pipe(
Effect.flatMap((maintenanceCapabilities) =>
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
}),
),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
Effect.flatMap((enrichedSnapshot) => {
enriched = enrichedSnapshot;
return publish;
}),
),
Stream.runForEach(catalogWatch.changes, (listed) => {
catalog = listed;
return publish;
}),
],
{ concurrency: "unbounded", discard: true },
);
},
}).pipe(
Effect.mapError(
(cause) =>
Expand Down Expand Up @@ -713,18 +747,29 @@ export const OpenCodeDriver: ProviderDriver<
[
snapshot.getSnapshot,
// A project's opencode.jsonc can define its own providers.
readSettledOpenCode2Catalog(
openCode2Server.withConnection(({ client }) =>
loadOpenCode2DirectoryCatalog(client, cwd),
),
processEnv,
).pipe(
Effect.map(
Option.map((catalog) =>
openCode2ProviderModels(effectiveConfig, catalog),
openCode2Server
.withConnection(({ client, events, url }) => {
const read = loadOpenCode2DirectoryCatalog(client, cwd);
return readSettledOpenCode2Catalog(read, processEnv).pipe(
Effect.tap((settled) =>
catalogWatch.follow(url, events, read, {
cwd,
...Option.match(settled, {
onNone: () => ({}),
onSome: (catalog) => ({ settled: catalog }),
}),
}),
),
);
})
.pipe(
Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
Effect.map(
Option.map((catalog) =>
openCode2ProviderModels(effectiveConfig, catalog),
),
),
),
),
listOpenCode2Workspace(cwd).pipe(
// Leaves room for the reads around the scan wait, which uses the same override.
Effect.timeout(
Expand Down Expand Up @@ -784,6 +829,7 @@ export const OpenCodeDriver: ProviderDriver<
}),
),
),
workspaceRescans: catalogWatch.rescans,
invalidateCaches: openCode2Server.forget,
afterUpdate,
orchestrationAdapter,
Expand Down
4 changes: 2 additions & 2 deletions packages/provider-opencode/src/server/openCode2Catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ export const loadOpenCode2Catalog = (client: OpenCodeClient, directory: string |
listProviders(client, directory).pipe(Effect.orElseSucceed(() => [])),
);

/** Missing provider names would relabel every model, so a directory read needs them. */
/** Missing provider names would relabel every model, so a read nothing settles needs them. */
export const loadOpenCode2DirectoryCatalog = Effect.fn(
"OpenCodeRuntime.loadOpenCode2DirectoryCatalog",
)((client: OpenCodeClient, directory: string) =>
)((client: OpenCodeClient, directory: string | undefined) =>
readCatalog(client, directory, listProviders(client, directory)),
);
142 changes: 142 additions & 0 deletions packages/provider-opencode/src/server/status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import * as TestClock from "effect/testing/TestClock";
Expand All @@ -26,6 +28,7 @@ import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
import {
checkOpenCodeProviderStatus,
loadOpenCode2Workspace,
makeOpenCode2CatalogWatch,
makeOpenCode2ModelLoader,
type OpenCode2Model,
type OpenCode2Workspace,
Expand Down Expand Up @@ -1314,3 +1317,142 @@ it.effect("lists a catalog whose cold server start outlasts the settle budget",
NodeAssert.deepEqual(yield* Fiber.join(fiber), catalog);
}),
);

const model = (id: string): OpenCode2Model => ({
providerID: "github-copilot",
id,
name: id,
variants: [],
});

it.effect("publishes the catalog OpenCode lists after its startup snapshot had settled", () =>
Effect.gen(function* () {
const startup = [model("startup-only")];
const live = [model("live-only")];
let listed = startup;
const read = Effect.sync(() => listed);
const events = yield* Queue.unbounded<{ readonly type: string }>();
const watch = yield* makeOpenCode2CatalogWatch();
const seen: Array<ReadonlyArray<OpenCode2Model> | undefined> = [];
yield* Stream.runForEach(watch.changes, (catalog) =>
Effect.sync(() => seen.push(catalog)),
).pipe(Effect.forkScoped);
const load = yield* makeOpenCode2ModelLoader(
watch
.follow("server", Effect.succeed(Stream.fromQueue(events)), read)
.pipe(Effect.andThen(read)),
);
const check = yield* Effect.forkChild(load);
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(yield* Fiber.join(check), startup);

// Discovery ends long after two reads agreed, and only the event says so.
yield* TestClock.adjust("6 seconds");
listed = live;
yield* Queue.offer(events, { type: "session.updated" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(seen.at(-1), startup);
yield* Queue.offer(events, { type: "model.updated" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(seen.at(-1), live);
}),
);

it.effect("keeps the last listed catalog once its server has stopped", () =>
Effect.gen(function* () {
const live = [model("live-only")];
let running = true;
const read = Effect.suspend(() =>
running
? Effect.succeed(live)
: Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "model.list",
detail: "stopped",
}),
),
);
const events = yield* Queue.unbounded<{ readonly type: string }, "closed">();
const watch = yield* makeOpenCode2CatalogWatch();
const seen: Array<ReadonlyArray<OpenCode2Model> | undefined> = [];
yield* Stream.runForEach(watch.changes, (catalog) =>
Effect.sync(() => seen.push(catalog)),
).pipe(Effect.forkScoped);
const follow = watch.follow("server", Effect.succeed(Stream.fromQueue(events)), read);
yield* follow;
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(seen.at(-1), live);

running = false;
yield* Queue.offer(events, { type: "model.updated" });
yield* Queue.fail(events, "closed");
yield* TestClock.adjust("10 seconds");
NodeAssert.deepEqual(seen.at(-1), live);

// The next check's read follows the restarted server instead of the ended stream.
running = true;
const restarted = yield* Queue.unbounded<{ readonly type: string }>();
const next = [model("after-restart")];
yield* watch.follow(
"server",
Effect.succeed(Stream.fromQueue(restarted)),
Effect.succeed(next),
);
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(seen.at(-1), next);
}),
);

it.effect("rescans a directory whose catalog changes after its scan settled", () =>
Effect.gen(function* () {
const startup = [model("startup-only")];
const live = [model("live-only")];
let listed = startup;
const read = Effect.sync(() => listed);
const events = yield* Queue.unbounded<{ readonly type: string }>();
const watch = yield* makeOpenCode2CatalogWatch();
const rescans: Array<string> = [];
yield* Stream.runForEach(watch.rescans, (cwd) => Effect.sync(() => rescans.push(cwd))).pipe(
Effect.forkScoped,
);
const subscribe = Effect.succeed(Stream.fromQueue(events));
yield* watch.follow("server", subscribe, read, { cwd: "/project", settled: startup });
// A scan that never settled keeps what the watch last read, so it cannot rescan forever.
yield* watch.follow("server", subscribe, read, { cwd: "/unsettled" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(rescans, ["/unsettled"]);
yield* watch.follow("server", subscribe, read, { cwd: "/unsettled" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(rescans, ["/unsettled"]);

listed = live;
yield* Queue.offer(events, { type: "model.updated" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(rescans, ["/unsettled", "/project", "/unsettled"]);

// The rescan settles on the live catalog, and its own follow asks for nothing more.
yield* watch.follow("server", subscribe, read, { cwd: "/project", settled: live });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(rescans, ["/unsettled", "/project", "/unsettled"]);
}),
);

it.effect("reads later changes after a catalog read that never answered", () =>
Effect.gen(function* () {
const live = [model("live-only")];
let answering = false;
const read = Effect.suspend(() => (answering ? Effect.succeed(live) : Effect.never));
const events = yield* Queue.unbounded<{ readonly type: string }>();
const watch = yield* makeOpenCode2CatalogWatch();
const seen: Array<ReadonlyArray<OpenCode2Model> | undefined> = [];
yield* Stream.runForEach(watch.changes, (catalog) =>
Effect.sync(() => seen.push(catalog)),
).pipe(Effect.forkScoped);
yield* watch.follow("server", Effect.succeed(Stream.fromQueue(events)), read);
yield* TestClock.adjust("31 seconds");
answering = true;
yield* Queue.offer(events, { type: "model.updated" });
yield* TestClock.adjust("1 second");
NodeAssert.deepEqual(seen.at(-1), live);
}),
);
Loading
Loading