Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 0593260f66 Format workspace entries duration cleanup
Co-authored-by: Julius Marminge <[email protected]>
2026-05-17 16:04:40 +00:00
Cursor AgentandJulius Marminge 9e8e6e9abd Use schema decoding for VCS project config
Co-authored-by: Julius Marminge <[email protected]>
2026-05-17 16:04:13 +00:00
12 changed files with 122 additions and 261 deletions

No files matched your search

@@ -1,6 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -61,16 +60,10 @@ describe("ProcessResourceMonitor", () => {
],
});
assert.deepStrictEqual(
samples.map((sample) => sample.pid),
[100, 101, 102],
);
assert.deepStrictEqual(
samples.map((sample) => sample.depth),
[0, 1, 2],
);
assert.equal(samples[0]?.isServerRoot, true);
assert.equal(samples[1]?.isServerRoot, false);
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
@@ -119,21 +112,18 @@ describe("ProcessResourceMonitor", () => {
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: Duration.toMillis(Duration.minutes(1)),
bucketMs: Duration.toMillis(Duration.seconds(10)),
lastError: Option.none(),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
assert.equal(Option.isNone(result.error), true);
assert.equal(result.topProcesses.length, 1);
assert.equal(result.topProcesses[0]?.avgCpuPercent, 20);
assert.equal(result.topProcesses[0]?.maxCpuPercent, 30);
assert.equal(result.topProcesses[0]?.cpuSecondsApprox, 2);
assert.equal(result.totalCpuSecondsApprox, 2);
assert.equal(
result.buckets.some((bucket) => bucket.maxCpuPercent === 30),
true,
);
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
@@ -182,15 +172,15 @@ describe("ProcessResourceMonitor", () => {
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: Duration.toMillis(Duration.minutes(1)),
bucketMs: Duration.toMillis(Duration.seconds(10)),
lastError: Option.none(),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
assert.equal(result.topProcesses.length, 1);
assert.equal(result.topProcesses[0]?.isServerRoot, true);
assert.equal(result.topProcesses[0]?.sampleCount, 2);
assert.equal(result.topProcesses[0]?.maxRssBytes, 2_000);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
@@ -229,35 +219,13 @@ describe("ProcessResourceMonitor", () => {
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: Duration.toMillis(Duration.minutes(1)),
bucketMs: Duration.toMillis(Duration.seconds(10)),
lastError: Option.none(),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
assert.equal(result.topProcesses.length, 36);
assert.equal(
result.topProcesses.some((process) => process.command === "worker 34"),
true,
);
}),
);
it.effect("maps the latest sampling error option into the response", () =>
Effect.sync(() => {
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const result = aggregateProcessResourceHistory({
samples: [],
readAt,
readAtMs: DateTime.toEpochMillis(readAt),
windowMs: Duration.toMillis(Duration.minutes(1)),
bucketMs: Duration.toMillis(Duration.seconds(10)),
lastError: Option.some("ps failed"),
});
if (Option.isNone(result.error)) {
assert.fail("Expected response error");
}
assert.deepStrictEqual(result.error.value, { message: "ps failed" });
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
});
@@ -6,12 +6,10 @@ import type {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -21,11 +19,8 @@ import {
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL = Duration.seconds(5);
const RETENTION = Duration.minutes(60);
const MIN_HISTORY_DURATION = Duration.seconds(1);
const SAMPLE_INTERVAL_MS = Duration.toMillis(SAMPLE_INTERVAL);
const RETENTION_MS = Duration.toMillis(RETENTION);
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
@@ -43,7 +38,7 @@ export interface ProcessResourceSample {
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: Option.Option<string>;
readonly lastError: string | null;
}
export interface ProcessResourceMonitorShape {
@@ -65,11 +60,8 @@ function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): Option.Option<ProcessRow> {
return Option.fromUndefinedOr(rows.find((row) => row.pid === serverPid));
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
@@ -83,16 +75,16 @@ export function collectMonitoredSamples(input: {
const descendants = buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (Option.isSome(root)) {
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root.value),
pid: root.value.pid,
ppid: root.value.ppid,
command: root.value.command,
cpuPercent: root.value.cpuPercent,
rssBytes: root.value.rssBytes,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
@@ -174,12 +166,11 @@ function summarizeProcesses(
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly window: Duration.Duration;
readonly bucket: Duration.Duration;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Duration.toMillis(Duration.max(MIN_HISTORY_DURATION, input.bucket));
const windowMs = Duration.toMillis(input.window);
const windowStartMs = input.nowMs - windowMs;
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
@@ -229,12 +220,10 @@ export function aggregateProcessResourceHistory(input: {
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: Option.Option<string>;
readonly lastError: string | null;
}): ServerProcessResourceHistoryResult {
const window = Duration.max(MIN_HISTORY_DURATION, Duration.millis(input.windowMs));
const bucket = Duration.max(MIN_HISTORY_DURATION, Duration.millis(input.bucketMs));
const windowMs = Duration.toMillis(window);
const bucketMs = Duration.toMillis(bucket);
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
@@ -250,15 +239,15 @@ export function aggregateProcessResourceHistory(input: {
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, window, bucket }),
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: Option.map(input.lastError, (message) => ({ message })),
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: Option.none() });
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
@@ -274,20 +263,20 @@ export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: Option.none(),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: Option.some(
error instanceof Error ? error.message : "Failed to sample process resources.",
),
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* sampleOnce.pipe(Effect.repeat(Schedule.spaced(SAMPLE_INTERVAL)), Effect.forkScoped);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
Effect.gen(function* () {
+21 -2
View File
@@ -41,8 +41,7 @@ describe("VcsProjectConfig", () => {
yield* fileSystem.makeDirectory(nested, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ vcs: { kind: "jj" } }),
'{"vcs":{"kind":"jj"}}',
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
@@ -53,6 +52,26 @@ describe("VcsProjectConfig", () => {
);
});
it.layer(TestLayer)("ignores malformed .t3code/vcs.json files", (it) => {
it.effect("falls back to auto", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{ not-json");
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
+16 -25
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -15,16 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
const ProjectVcsConfigJson = Schema.fromJsonString(ProjectVcsConfig);
const decodeProjectVcsConfig = Schema.decodeUnknownOption(ProjectVcsConfigJson);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
type ProjectVcsConfigFile = Schema.Schema.Type<typeof ProjectVcsConfig>;
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -45,13 +40,8 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
function parseConfig(raw: string): Option.Option<ProjectVcsConfigFile> {
return decodeProjectVcsConfig(raw);
}
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
@@ -63,12 +53,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
while (true) {
const candidate = path.join(current, ".t3code", "vcs.json");
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return candidate;
return Option.some(candidate);
}
const parent = path.dirname(current);
if (parent === current) {
return null;
return Option.none<string>();
}
current = parent;
}
@@ -78,26 +68,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
configPath: string,
) {
const raw = yield* fileSystem.readFileString(configPath).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to read VCS project config", {
configPath,
error,
}).pipe(Effect.as(null)),
}).pipe(Effect.as(Option.none<string>())),
),
);
if (raw === null) {
if (Option.isNone(raw)) {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
const parsed = parseConfig(raw.value);
if (Option.isNone(parsed)) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
return configuredKind(parsed.value);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -108,11 +99,11 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
}
const configPath = yield* findConfigPath(input.cwd);
if (configPath === null) {
if (Option.isNone(configPath)) {
return "auto";
}
return yield* readConfiguredKind(configPath);
return yield* readConfiguredKind(configPath.value);
});
return VcsProjectConfig.of({
@@ -29,7 +29,7 @@ import {
} from "../Services/WorkspaceEntries.ts";
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
const WORKSPACE_CACHE_TTL_MS = 15_000;
const WORKSPACE_CACHE_TTL = Duration.seconds(15);
const WORKSPACE_CACHE_MAX_KEYS = 4;
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
@@ -402,8 +402,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
buildWorkspaceIndex,
{
capacity: WORKSPACE_CACHE_MAX_KEYS,
timeToLive: (exit) =>
Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero,
timeToLive: (exit) => (Exit.isSuccess(exit) ? WORKSPACE_CACHE_TTL : Duration.zero),
},
);
+4 -13
View File
@@ -727,16 +727,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
model: selectedModel,
models: selectedProviderModels,
prompt,
modelOptions: composerModelOptions?.[selectedInstanceId],
modelOptions: composerModelOptions?.[selectedProvider],
}),
[
composerModelOptions,
prompt,
selectedInstanceId,
selectedModel,
selectedProvider,
selectedProviderModels,
],
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
);
const selectedPromptEffort = composerProviderState.promptEffort;
@@ -1025,23 +1018,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const providerTraitsMenuContent = renderProviderTraitsMenuContent({
provider: selectedProvider,
instanceId: selectedInstanceId,
...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),
...(routeKind === "draft" && draftId ? { draftId } : {}),
model: selectedModel,
models: selectedProviderModels,
modelOptions: composerModelOptions?.[selectedInstanceId],
modelOptions: composerModelOptions?.[selectedProvider],
prompt,
onPromptChange: setPromptFromTraits,
});
const providerTraitsPicker = renderProviderTraitsPicker({
provider: selectedProvider,
instanceId: selectedInstanceId,
...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),
...(routeKind === "draft" && draftId ? { draftId } : {}),
model: selectedModel,
models: selectedProviderModels,
modelOptions: composerModelOptions?.[selectedInstanceId],
modelOptions: composerModelOptions?.[selectedProvider],
prompt,
onPromptChange: setPromptFromTraits,
});
@@ -1,6 +1,5 @@
import {
type ProviderDriverKind,
type ProviderInstanceId,
type ProviderOptionDescriptor,
type ProviderOptionSelection,
type ScopedThreadRef,
@@ -197,7 +196,6 @@ export function shouldRenderTraitsControls(input: {
export interface TraitsMenuContentProps {
provider: ProviderDriverKind;
instanceId?: ProviderInstanceId;
models: ReadonlyArray<ServerProviderModel>;
model: string | null | undefined;
prompt: string;
@@ -210,7 +208,6 @@ export interface TraitsMenuContentProps {
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
provider,
instanceId,
models,
model,
prompt,
@@ -231,12 +228,11 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
return;
}
setProviderModelOptions(threadTarget, provider, nextOptions, {
...(instanceId ? { instanceId } : {}),
model,
persistSticky: true,
});
},
[instanceId, model, persistence, provider, setProviderModelOptions],
[model, persistence, provider, setProviderModelOptions],
);
const {
descriptors,
@@ -347,7 +343,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
export const TraitsPicker = memo(function TraitsPicker({
provider,
instanceId,
models,
model,
prompt,
@@ -436,7 +431,6 @@ export const TraitsPicker = memo(function TraitsPicker({
<MenuPopup align="start">
<TraitsMenuContent
provider={provider}
{...(instanceId ? { instanceId } : {})}
models={models}
model={model}
prompt={prompt}
@@ -1,6 +1,5 @@
import {
type ProviderDriverKind,
type ProviderInstanceId,
type ProviderOptionSelection,
type ScopedThreadRef,
type ServerProviderModel,
@@ -36,7 +35,6 @@ export type ComposerProviderState = {
type TraitsRenderInput = {
provider: ProviderDriverKind;
instanceId?: ProviderInstanceId;
threadRef?: ScopedThreadRef;
draftId?: DraftId;
model: string;
@@ -78,17 +76,8 @@ function renderTraitsControl(
Component: typeof TraitsMenuContent | typeof TraitsPicker,
input: TraitsRenderInput,
): ReactNode {
const {
provider,
instanceId,
threadRef,
draftId,
model,
models,
modelOptions,
prompt,
onPromptChange,
} = input;
const { provider, threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } =
input;
const hasTarget = threadRef !== undefined || draftId !== undefined;
if (
!hasTarget ||
@@ -99,7 +88,6 @@ function renderTraitsControl(
return (
<Component
provider={provider}
{...(instanceId ? { instanceId } : {})}
models={models}
{...(threadRef ? { threadRef } : {})}
{...(draftId ? { draftId } : {})}
-38
View File
@@ -21,7 +21,6 @@ import { createModelSelection } from "@t3tools/shared/model";
// `stickyModelSelectionByProvider` maps are keyed by `ProviderInstanceId`
// in production; these aliases keep the legacy-key migration tests concise.
const CODEX_INSTANCE = ProviderInstanceId.make("codex");
const CODEX_SECONDARY_INSTANCE = ProviderInstanceId.make("codex_secondary");
const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");
const CURSOR_INSTANCE = ProviderInstanceId.make("cursor");
const CODEX_DRIVER = ProviderDriverKind.make("codex");
@@ -1202,43 +1201,6 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("stores provider option changes on a selected custom instance", () => {
const store = useComposerDraftStore.getState();
store.setProviderModelOptions(
threadRef,
CODEX_DRIVER,
toSelections({ reasoningEffort: "low" }),
{
instanceId: CODEX_SECONDARY_INSTANCE,
model: "gpt-5-codex",
persistSticky: true,
},
);
expect(
draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_SECONDARY_INSTANCE],
).toEqual(
expect.objectContaining({
instanceId: CODEX_SECONDARY_INSTANCE,
options: [{ id: "reasoningEffort", value: "low" }],
}),
);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.activeProvider).toBe(CODEX_SECONDARY_INSTANCE);
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe(CODEX_SECONDARY_INSTANCE);
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toBe(
undefined,
);
expect(
useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_SECONDARY_INSTANCE],
).toEqual(
expect.objectContaining({
instanceId: CODEX_SECONDARY_INSTANCE,
options: [{ id: "reasoningEffort", value: "low" }],
}),
);
});
it("updates only the draft when sticky persistence is disabled", () => {
const store = useComposerDraftStore.getState();
+2 -6
View File
@@ -371,7 +371,6 @@ interface ComposerDraftStoreState {
provider: ProviderDriverKind,
nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
options?: {
instanceId?: ProviderInstanceId | null | undefined;
model?: string | null | undefined;
persistSticky?: boolean;
},
@@ -2457,7 +2456,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
if (normalizedProvider === null) {
return;
}
const instanceKey = options?.instanceId ?? defaultInstanceIdForDriver(normalizedProvider);
const instanceKey = defaultInstanceIdForDriver(normalizedProvider);
const fallbackModel =
normalizeModelSlug(options?.model, normalizedProvider) ??
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??
@@ -2502,9 +2501,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const { options: _, ...rest } = stickyBase;
nextStickyMap[instanceKey] = rest as ModelSelection;
}
nextStickyActiveProvider = options.instanceId
? instanceKey
: (base.activeProvider ?? instanceKey);
nextStickyActiveProvider = base.activeProvider ?? instanceKey;
}
if (
@@ -2517,7 +2514,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const nextDraft: ComposerThreadDraftState = {
...base,
...(options?.instanceId ? { activeProvider: instanceKey } : {}),
modelSelectionByProvider: nextMap,
};
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { it } from "@effect/vitest";
import { describe, expect } from "vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -46,12 +47,12 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
assert.equal(yield* Deferred.isDone(drained), false);
expect(yield* Deferred.isDone(drained)).toBe(false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
@@ -89,28 +90,7 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.await(secondProcessed);
yield* worker.drainKey("terminal-1");
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
}),
),
);
it.live("treats an undefined value as present queued work", () =>
Effect.scoped(
Effect.gen(function* () {
const processed: Array<string | undefined> = [];
const worker = yield* makeKeyedCoalescingWorker<string, string | undefined, never, never>({
merge: (_current, next) => next,
process: (_key, value) =>
Effect.sync(() => {
processed.push(value);
}),
});
yield* worker.enqueue("terminal-1", undefined);
yield* worker.drainKey("terminal-1");
assert.deepStrictEqual(processed, [undefined]);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
+15 -31
View File
@@ -9,7 +9,6 @@
*/
import * as Scope from "effect/Scope";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as TxQueue from "effect/TxQueue";
import * as TxRef from "effect/TxRef";
@@ -24,9 +23,6 @@ interface KeyedCoalescingWorkerState<K, V> {
readonly activeKeys: Set<K>;
}
const getMapValue = <K, V>(map: ReadonlyMap<K, V>, key: K): Option.Option<V> =>
map.has(key) ? Option.some(map.get(key) as V) : Option.none();
export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
readonly merge: (current: V, next: V) => V;
readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
@@ -43,11 +39,11 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
options.process(key, value).pipe(
Effect.flatMap(() =>
TxRef.modify(stateRef, (state) => {
const nextValue = getMapValue(state.latestByKey, key);
if (Option.isNone(nextValue)) {
const nextValue = state.latestByKey.get(key);
if (nextValue === undefined) {
const activeKeys = new Set(state.activeKeys);
activeKeys.delete(key);
return [Option.none<V>(), { ...state, activeKeys }] as const;
return [null, { ...state, activeKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
@@ -56,10 +52,7 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
}).pipe(Effect.tx),
),
Effect.flatMap((nextValue) =>
Option.match(nextValue, {
onNone: () => Effect.void,
onSome: (value) => processKey(key, value),
}),
nextValue === null ? Effect.void : processKey(key, nextValue),
),
);
@@ -88,12 +81,9 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.delete(key);
const value = getMapValue(state.latestByKey, key);
if (Option.isNone(value)) {
return [
Option.none<{ readonly key: K; readonly value: V }>(),
{ ...state, queuedKeys },
] as const;
const value = state.latestByKey.get(key);
if (value === undefined) {
return [null, { ...state, queuedKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
@@ -102,17 +92,17 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
activeKeys.add(key);
return [
Option.some({ key, value: value.value }),
{ key, value } as const,
{ ...state, latestByKey, queuedKeys, activeKeys },
] as const;
}).pipe(Effect.tx),
),
Effect.flatMap((item) =>
Option.match(item, {
onNone: () => Effect.void,
onSome: ({ key, value }) =>
processKey(key, value).pipe(Effect.catchCause(() => cleanupFailedKey(key))),
}),
item === null
? Effect.void
: processKey(item.key, item.value).pipe(
Effect.catchCause(() => cleanupFailedKey(item.key)),
),
),
Effect.forever,
Effect.forkScoped,
@@ -121,14 +111,8 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
TxRef.modify(stateRef, (state) => {
const latestByKey = new Map(state.latestByKey);
const existing = getMapValue(latestByKey, key);
latestByKey.set(
key,
Option.match(existing, {
onNone: () => value,
onSome: (current) => options.merge(current, value),
}),
);
const existing = latestByKey.get(key);
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
return [false, { ...state, latestByKey }] as const;