Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd57f3b461 | ||
|
|
4f0f24f055 |
No files matched your search
@@ -25,7 +25,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -76,8 +75,6 @@ export interface DesktopSshEnvironmentLayerOptions {
|
||||
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
|
||||
}
|
||||
|
||||
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
|
||||
|
||||
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
return discoverSshHosts(input ?? {});
|
||||
}
|
||||
@@ -86,7 +83,7 @@ export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError {
|
||||
return (
|
||||
isSshPasswordPromptError(error) &&
|
||||
error instanceof SshPasswordPromptError &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,13 +2,10 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopSshRemoteApi from "./DesktopSshRemoteApi.ts";
|
||||
|
||||
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
|
||||
|
||||
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
@@ -76,7 +73,7 @@ describe("DesktopSshRemoteApi", () => {
|
||||
|
||||
assert.instanceOf(error, DesktopSshRemoteApi.DesktopSshRemoteApiError);
|
||||
assert.equal(error.operation, "fetch-environment-descriptor");
|
||||
assert.equal(isSshHttpBridgeError(error.cause), false);
|
||||
assert.equal(error.cause instanceof SshHttpBridgeError, false);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, 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";
|
||||
|
||||
@@ -60,10 +61,16 @@ describe("ProcessResourceMonitor", () => {
|
||||
],
|
||||
});
|
||||
|
||||
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);
|
||||
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);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -112,18 +119,21 @@ describe("ProcessResourceMonitor", () => {
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
windowMs: Duration.toMillis(Duration.minutes(1)),
|
||||
bucketMs: Duration.toMillis(Duration.seconds(10)),
|
||||
lastError: Option.none(),
|
||||
});
|
||||
|
||||
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);
|
||||
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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -172,15 +182,15 @@ describe("ProcessResourceMonitor", () => {
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
windowMs: Duration.toMillis(Duration.minutes(1)),
|
||||
bucketMs: Duration.toMillis(Duration.seconds(10)),
|
||||
lastError: Option.none(),
|
||||
});
|
||||
|
||||
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);
|
||||
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);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -219,13 +229,35 @@ describe("ProcessResourceMonitor", () => {
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastError: null,
|
||||
windowMs: Duration.toMillis(Duration.minutes(1)),
|
||||
bucketMs: Duration.toMillis(Duration.seconds(10)),
|
||||
lastError: Option.none(),
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
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" });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,10 +6,12 @@ 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 {
|
||||
@@ -19,8 +21,11 @@ import {
|
||||
readProcessRows,
|
||||
} from "./ProcessDiagnostics.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
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 MAX_RETAINED_SAMPLES = 20_000;
|
||||
|
||||
export interface ProcessResourceSample {
|
||||
@@ -38,7 +43,7 @@ export interface ProcessResourceSample {
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastError: string | null;
|
||||
readonly lastError: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface ProcessResourceMonitorShape {
|
||||
@@ -60,8 +65,11 @@ function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
function findServerRootRow(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): Option.Option<ProcessRow> {
|
||||
return Option.fromUndefinedOr(rows.find((row) => row.pid === serverPid));
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
@@ -75,16 +83,16 @@ export function collectMonitoredSamples(input: {
|
||||
const descendants = buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
if (Option.isSome(root)) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(root),
|
||||
pid: root.pid,
|
||||
ppid: root.ppid,
|
||||
command: root.command,
|
||||
cpuPercent: root.cpuPercent,
|
||||
rssBytes: root.rssBytes,
|
||||
processKey: sampleKey(root.value),
|
||||
pid: root.value.pid,
|
||||
ppid: root.value.ppid,
|
||||
command: root.value.command,
|
||||
cpuPercent: root.value.cpuPercent,
|
||||
rssBytes: root.value.rssBytes,
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
});
|
||||
@@ -166,11 +174,12 @@ function summarizeProcesses(
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly window: Duration.Duration;
|
||||
readonly bucket: Duration.Duration;
|
||||
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const bucketMs = Duration.toMillis(Duration.max(MIN_HISTORY_DURATION, input.bucket));
|
||||
const windowMs = Duration.toMillis(input.window);
|
||||
const windowStartMs = input.nowMs - windowMs;
|
||||
const buckets: ServerProcessResourceHistoryBucket[] = [];
|
||||
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
|
||||
@@ -220,10 +229,12 @@ export function aggregateProcessResourceHistory(input: {
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastError: string | null;
|
||||
readonly lastError: Option.Option<string>;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
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 minSampledAtMs = input.readAtMs - windowMs;
|
||||
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
const topProcesses = summarizeProcesses(samples);
|
||||
@@ -239,15 +250,15 @@ export function aggregateProcessResourceHistory(input: {
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
retainedSampleCount: input.samples.length,
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, window, bucket }),
|
||||
topProcesses,
|
||||
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
|
||||
error: Option.map(input.lastError, (message) => ({ message })),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: Option.none() });
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
@@ -263,20 +274,20 @@ export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastError: null,
|
||||
lastError: Option.none(),
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
|
||||
lastError: Option.some(
|
||||
error instanceof Error ? error.message : "Failed to sample process resources.",
|
||||
),
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* sampleOnce.pipe(Effect.repeat(Schedule.spaced(SAMPLE_INTERVAL)), Effect.forkScoped);
|
||||
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -727,9 +727,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
modelOptions: composerModelOptions?.[selectedInstanceId],
|
||||
}),
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
|
||||
[
|
||||
composerModelOptions,
|
||||
prompt,
|
||||
selectedInstanceId,
|
||||
selectedModel,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
],
|
||||
);
|
||||
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
@@ -1018,21 +1025,23 @@ 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?.[selectedProvider],
|
||||
modelOptions: composerModelOptions?.[selectedInstanceId],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const providerTraitsPicker = renderProviderTraitsPicker({
|
||||
provider: selectedProvider,
|
||||
instanceId: selectedInstanceId,
|
||||
...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),
|
||||
...(routeKind === "draft" && draftId ? { draftId } : {}),
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
modelOptions: composerModelOptions?.[selectedInstanceId],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderOptionDescriptor,
|
||||
type ProviderOptionSelection,
|
||||
type ScopedThreadRef,
|
||||
@@ -196,6 +197,7 @@ export function shouldRenderTraitsControls(input: {
|
||||
|
||||
export interface TraitsMenuContentProps {
|
||||
provider: ProviderDriverKind;
|
||||
instanceId?: ProviderInstanceId;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
model: string | null | undefined;
|
||||
prompt: string;
|
||||
@@ -208,6 +210,7 @@ export interface TraitsMenuContentProps {
|
||||
|
||||
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
provider,
|
||||
instanceId,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
@@ -228,11 +231,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(threadTarget, provider, nextOptions, {
|
||||
...(instanceId ? { instanceId } : {}),
|
||||
model,
|
||||
persistSticky: true,
|
||||
});
|
||||
},
|
||||
[model, persistence, provider, setProviderModelOptions],
|
||||
[instanceId, model, persistence, provider, setProviderModelOptions],
|
||||
);
|
||||
const {
|
||||
descriptors,
|
||||
@@ -343,6 +347,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
instanceId,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
@@ -431,6 +436,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
<MenuPopup align="start">
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
{...(instanceId ? { instanceId } : {})}
|
||||
models={models}
|
||||
model={model}
|
||||
prompt={prompt}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderOptionSelection,
|
||||
type ScopedThreadRef,
|
||||
type ServerProviderModel,
|
||||
@@ -35,6 +36,7 @@ export type ComposerProviderState = {
|
||||
|
||||
type TraitsRenderInput = {
|
||||
provider: ProviderDriverKind;
|
||||
instanceId?: ProviderInstanceId;
|
||||
threadRef?: ScopedThreadRef;
|
||||
draftId?: DraftId;
|
||||
model: string;
|
||||
@@ -76,8 +78,17 @@ function renderTraitsControl(
|
||||
Component: typeof TraitsMenuContent | typeof TraitsPicker,
|
||||
input: TraitsRenderInput,
|
||||
): ReactNode {
|
||||
const { provider, threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } =
|
||||
input;
|
||||
const {
|
||||
provider,
|
||||
instanceId,
|
||||
threadRef,
|
||||
draftId,
|
||||
model,
|
||||
models,
|
||||
modelOptions,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
} = input;
|
||||
const hasTarget = threadRef !== undefined || draftId !== undefined;
|
||||
if (
|
||||
!hasTarget ||
|
||||
@@ -88,6 +99,7 @@ function renderTraitsControl(
|
||||
return (
|
||||
<Component
|
||||
provider={provider}
|
||||
{...(instanceId ? { instanceId } : {})}
|
||||
models={models}
|
||||
{...(threadRef ? { threadRef } : {})}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
|
||||
@@ -21,6 +21,7 @@ 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");
|
||||
@@ -1201,6 +1202,43 @@ 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();
|
||||
|
||||
|
||||
@@ -371,6 +371,7 @@ interface ComposerDraftStoreState {
|
||||
provider: ProviderDriverKind,
|
||||
nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
|
||||
options?: {
|
||||
instanceId?: ProviderInstanceId | null | undefined;
|
||||
model?: string | null | undefined;
|
||||
persistSticky?: boolean;
|
||||
},
|
||||
@@ -2456,7 +2457,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
const instanceKey = defaultInstanceIdForDriver(normalizedProvider);
|
||||
const instanceKey = options?.instanceId ?? defaultInstanceIdForDriver(normalizedProvider);
|
||||
const fallbackModel =
|
||||
normalizeModelSlug(options?.model, normalizedProvider) ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??
|
||||
@@ -2501,7 +2502,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
const { options: _, ...rest } = stickyBase;
|
||||
nextStickyMap[instanceKey] = rest as ModelSelection;
|
||||
}
|
||||
nextStickyActiveProvider = base.activeProvider ?? instanceKey;
|
||||
nextStickyActiveProvider = options.instanceId
|
||||
? instanceKey
|
||||
: (base.activeProvider ?? instanceKey);
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -2514,6 +2517,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
...(options?.instanceId ? { activeProvider: instanceKey } : {}),
|
||||
modelSelectionByProvider: nextMap,
|
||||
};
|
||||
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -47,12 +46,12 @@ describe("makeKeyedCoalescingWorker", () => {
|
||||
yield* Deferred.succeed(releaseFirst, undefined);
|
||||
yield* Deferred.await(secondStarted);
|
||||
|
||||
expect(yield* Deferred.isDone(drained)).toBe(false);
|
||||
assert.equal(yield* Deferred.isDone(drained), false);
|
||||
|
||||
yield* Deferred.succeed(releaseSecond, undefined);
|
||||
yield* Deferred.await(drained);
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -90,7 +89,28 @@ describe("makeKeyedCoalescingWorker", () => {
|
||||
yield* Deferred.await(secondProcessed);
|
||||
yield* worker.drainKey("terminal-1");
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
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]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
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";
|
||||
|
||||
@@ -23,6 +24,9 @@ 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>;
|
||||
@@ -39,11 +43,11 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
options.process(key, value).pipe(
|
||||
Effect.flatMap(() =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const nextValue = state.latestByKey.get(key);
|
||||
if (nextValue === undefined) {
|
||||
const nextValue = getMapValue(state.latestByKey, key);
|
||||
if (Option.isNone(nextValue)) {
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.delete(key);
|
||||
return [null, { ...state, activeKeys }] as const;
|
||||
return [Option.none<V>(), { ...state, activeKeys }] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
@@ -52,7 +56,10 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((nextValue) =>
|
||||
nextValue === null ? Effect.void : processKey(key, nextValue),
|
||||
Option.match(nextValue, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (value) => processKey(key, value),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -81,9 +88,12 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.delete(key);
|
||||
|
||||
const value = state.latestByKey.get(key);
|
||||
if (value === undefined) {
|
||||
return [null, { ...state, queuedKeys }] as const;
|
||||
const value = getMapValue(state.latestByKey, key);
|
||||
if (Option.isNone(value)) {
|
||||
return [
|
||||
Option.none<{ readonly key: K; readonly value: V }>(),
|
||||
{ ...state, queuedKeys },
|
||||
] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
@@ -92,17 +102,17 @@ export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
activeKeys.add(key);
|
||||
|
||||
return [
|
||||
{ key, value } as const,
|
||||
Option.some({ key, value: value.value }),
|
||||
{ ...state, latestByKey, queuedKeys, activeKeys },
|
||||
] as const;
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((item) =>
|
||||
item === null
|
||||
? Effect.void
|
||||
: processKey(item.key, item.value).pipe(
|
||||
Effect.catchCause(() => cleanupFailedKey(item.key)),
|
||||
),
|
||||
Option.match(item, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: ({ key, value }) =>
|
||||
processKey(key, value).pipe(Effect.catchCause(() => cleanupFailedKey(key))),
|
||||
}),
|
||||
),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
@@ -111,8 +121,14 @@ 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 = latestByKey.get(key);
|
||||
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
|
||||
const existing = getMapValue(latestByKey, key);
|
||||
latestByKey.set(
|
||||
key,
|
||||
Option.match(existing, {
|
||||
onNone: () => value,
|
||||
onSome: (current) => options.merge(current, value),
|
||||
}),
|
||||
);
|
||||
|
||||
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
|
||||
return [false, { ...state, latestByKey }] as const;
|
||||
|
||||
+38
-53
@@ -1,61 +1,46 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
export class SshHostDiscoveryError extends Schema.TaggedErrorClass<SshHostDiscoveryError>()(
|
||||
"SshHostDiscoveryError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.Defect,
|
||||
},
|
||||
) {}
|
||||
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshInvalidTargetError extends Schema.TaggedErrorClass<SshInvalidTargetError>()(
|
||||
"SshInvalidTargetError",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class SshCommandError extends Schema.TaggedErrorClass<SshCommandError>()("SshCommandError", {
|
||||
message: Schema.String,
|
||||
command: Schema.Array(Schema.String),
|
||||
exitCode: Schema.NullOr(Schema.Number),
|
||||
stderr: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
|
||||
readonly message: string;
|
||||
readonly command: readonly string[];
|
||||
readonly exitCode: number | null;
|
||||
readonly stderr: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshLaunchError extends Schema.TaggedErrorClass<SshLaunchError>()("SshLaunchError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshPairingError extends Schema.TaggedErrorClass<SshPairingError>()("SshPairingError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshHttpBridgeError extends Schema.TaggedErrorClass<SshHttpBridgeError>()(
|
||||
"SshHttpBridgeError",
|
||||
{
|
||||
message: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
|
||||
readonly message: string;
|
||||
readonly status?: number;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshReadinessError extends Schema.TaggedErrorClass<SshReadinessError>()(
|
||||
"SshReadinessError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshPasswordPromptError extends Schema.TaggedErrorClass<SshPasswordPromptError>()(
|
||||
"SshPasswordPromptError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
@@ -167,7 +167,6 @@ const RemoteHttpError = Schema.Struct({
|
||||
const decodeRemoteLaunchResult = Schema.decodeEffect(fromLenientJson(RemoteLaunchResult));
|
||||
const decodeRemotePairingResult = Schema.decodeEffect(fromLenientJson(RemotePairingResult));
|
||||
const decodeRemoteHttpError = Schema.decodeEffect(Schema.fromJsonString(RemoteHttpError));
|
||||
const isSshReadinessError = Schema.is(SshReadinessError);
|
||||
|
||||
const decodeRemoteJsonOutput = <A, E>(
|
||||
stdout: string,
|
||||
@@ -238,7 +237,7 @@ function applyScriptPlaceholders(
|
||||
}
|
||||
|
||||
export function describeReadinessCause(cause: unknown): unknown {
|
||||
if (isSshReadinessError(cause)) {
|
||||
if (cause instanceof SshReadinessError) {
|
||||
return {
|
||||
_tag: cause._tag,
|
||||
message: cause.message,
|
||||
@@ -926,7 +925,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isSshReadinessError(cause)
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
@@ -947,7 +946,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
|
||||
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isSshReadinessError(cause)
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -7,36 +7,24 @@ import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
export const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);
|
||||
export const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
|
||||
export const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
|
||||
export const TAILSCALE_STATUS_TIMEOUT_MS = Duration.toMillis(TAILSCALE_STATUS_TIMEOUT);
|
||||
export const TAILSCALE_SERVE_TIMEOUT_MS = Duration.toMillis(TAILSCALE_SERVE_TIMEOUT);
|
||||
export const TAILSCALE_PROBE_TIMEOUT_MS = Duration.toMillis(TAILSCALE_PROBE_TIMEOUT);
|
||||
export const TAILSCALE_STATUS_TIMEOUT_MS = 1_500;
|
||||
export const TAILSCALE_SERVE_TIMEOUT_MS = 10_000;
|
||||
export const TAILSCALE_PROBE_TIMEOUT_MS = 2_500;
|
||||
|
||||
export class TailscaleCommandError extends Schema.TaggedErrorClass<TailscaleCommandError>()(
|
||||
"TailscaleCommandError",
|
||||
{
|
||||
command: Schema.Array(Schema.String),
|
||||
message: Schema.String,
|
||||
exitCode: Schema.NullOr(Schema.Number),
|
||||
stderr: Schema.String,
|
||||
},
|
||||
) {}
|
||||
export class TailscaleCommandError extends Data.TaggedError("TailscaleCommandError")<{
|
||||
readonly command: readonly string[];
|
||||
readonly message: string;
|
||||
readonly exitCode: number | null;
|
||||
readonly stderr: string;
|
||||
}> {}
|
||||
|
||||
export class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(
|
||||
"TailscaleStatusParseError",
|
||||
{
|
||||
cause: Schema.Defect,
|
||||
},
|
||||
) {}
|
||||
export class TailscaleStatusParseError extends Data.TaggedError("TailscaleStatusParseError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
|
||||
"TailscaleUnavailableError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
},
|
||||
) {}
|
||||
export class TailscaleUnavailableError extends Data.TaggedError("TailscaleUnavailableError")<{
|
||||
readonly reason: string;
|
||||
}> {}
|
||||
|
||||
const TailscaleStatusSelf = Schema.Struct({
|
||||
DNSName: Schema.optional(Schema.Unknown),
|
||||
@@ -186,7 +174,7 @@ export const readTailscaleStatus: Effect.Effect<
|
||||
return yield* parseTailscaleStatus(stdout);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT),
|
||||
Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT_MS),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
@@ -218,7 +206,7 @@ const runTailscaleCommand = (
|
||||
readonly runMessage: string;
|
||||
readonly exitMessage: (exitCode: number) => string;
|
||||
readonly timeoutMessage: string;
|
||||
readonly timeout: Duration.Input;
|
||||
readonly timeoutMs: number;
|
||||
},
|
||||
): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.gen(function* () {
|
||||
@@ -255,7 +243,7 @@ const runTailscaleCommand = (
|
||||
}
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(input.timeout),
|
||||
Effect.timeoutOption(input.timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(tailscaleCommandError(args, input.timeoutMessage, null)),
|
||||
@@ -277,7 +265,7 @@ export const ensureTailscaleServe = (input: {
|
||||
runMessage: "Failed to run tailscale serve.",
|
||||
exitMessage: (exitCode) => `Tailscale serve exited with code ${exitCode}.`,
|
||||
timeoutMessage: "Tailscale serve timed out.",
|
||||
timeout: TAILSCALE_SERVE_TIMEOUT,
|
||||
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -293,13 +281,13 @@ export const disableTailscaleServe = (
|
||||
runMessage: "Failed to run tailscale serve off.",
|
||||
exitMessage: (exitCode) => `Tailscale serve off exited with code ${exitCode}.`,
|
||||
timeoutMessage: "Tailscale serve off timed out.",
|
||||
timeout: TAILSCALE_SERVE_TIMEOUT,
|
||||
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
|
||||
});
|
||||
});
|
||||
|
||||
export const probeTailscaleHttpsEndpoint = (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly timeout?: Duration.Input;
|
||||
readonly timeoutMs?: number;
|
||||
}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
@@ -307,7 +295,7 @@ export const probeTailscaleHttpsEndpoint = (input: {
|
||||
const url = new URL("/.well-known/t3/environment", input.baseUrl);
|
||||
const request = HttpClientRequest.get(url.toString());
|
||||
return yield* client.execute(request);
|
||||
}).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
|
||||
}).pipe(Effect.timeoutOption(input.timeoutMs ?? TAILSCALE_PROBE_TIMEOUT_MS));
|
||||
|
||||
return Option.match(response, {
|
||||
onNone: () => false,
|
||||
|
||||
Reference in new issue
Block a user