Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd57f3b461 | ||
|
|
4f0f24f055 |
No files matched your search
@@ -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* () {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ReactNode, type RefObject, useEffect, useEffectEvent, useRef } from "react";
|
||||
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
|
||||
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
|
||||
import {
|
||||
@@ -53,8 +53,6 @@ function describeExhaustedToast(): string {
|
||||
return "Retries exhausted trying to reconnect";
|
||||
}
|
||||
|
||||
type ThreadToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
function getConnectionDisplayName(status: WsConnectionStatus): string {
|
||||
return status.connectionLabel?.trim() || "T3 Server";
|
||||
}
|
||||
@@ -92,70 +90,6 @@ function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): st
|
||||
return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
|
||||
}
|
||||
|
||||
function buildReconnectToast(
|
||||
status: WsConnectionStatus,
|
||||
nowMs: number,
|
||||
triggerManualReconnect: () => void,
|
||||
) {
|
||||
return stackedThreadToast({
|
||||
actionProps: {
|
||||
children: "Retry now",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
description:
|
||||
status.nextRetryAt === null
|
||||
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
|
||||
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
|
||||
timeout: 0,
|
||||
title: buildReconnectTitle(status),
|
||||
type: "loading",
|
||||
});
|
||||
}
|
||||
|
||||
function useReconnectToastCountdown(
|
||||
status: WsConnectionStatus,
|
||||
toastIdRef: RefObject<ThreadToastId | null>,
|
||||
triggerManualReconnect: () => void,
|
||||
) {
|
||||
const nowMsRef = useRef(Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refreshReconnectToast = () => {
|
||||
nowMsRef.current = Date.now();
|
||||
const toastId = toastIdRef.current;
|
||||
if (!toastId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentStatus = getWsConnectionStatus();
|
||||
if (getWsConnectionUiState(currentStatus) !== "reconnecting") {
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.update(
|
||||
toastId,
|
||||
buildReconnectToast(currentStatus, nowMsRef.current, triggerManualReconnect),
|
||||
);
|
||||
};
|
||||
|
||||
refreshReconnectToast();
|
||||
const intervalId = window.setInterval(refreshReconnectToast, 1_000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [status.nextRetryAt, status.reconnectPhase, toastIdRef, triggerManualReconnect]);
|
||||
|
||||
return nowMsRef;
|
||||
}
|
||||
|
||||
function SlowRpcAckRequestDetails({ requests }: { requests: ReadonlyArray<SlowRpcAckRequest> }) {
|
||||
return (
|
||||
<ul className="space-y-2.5 text-xs text-muted-foreground">
|
||||
@@ -213,8 +147,9 @@ export function shouldRestartStalledReconnect(
|
||||
|
||||
export function WebSocketConnectionCoordinator() {
|
||||
const status = useWsConnectionStatus();
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
const lastForcedReconnectAtRef = useRef(0);
|
||||
const toastIdRef = useRef<ThreadToastId | null>(null);
|
||||
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
|
||||
const toastResetTimerRef = useRef<number | null>(null);
|
||||
const previousUiStateRef = useRef<WsConnectionUiState>(getWsConnectionUiState(status));
|
||||
const previousDisconnectedAtRef = useRef<string | null>(status.disconnectedAt);
|
||||
@@ -265,11 +200,6 @@ export function WebSocketConnectionCoordinator() {
|
||||
|
||||
runReconnect(false);
|
||||
});
|
||||
const reconnectToastNowMsRef = useReconnectToastCountdown(
|
||||
status,
|
||||
toastIdRef,
|
||||
triggerManualReconnect,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => {
|
||||
@@ -290,6 +220,21 @@ export function WebSocketConnectionCoordinator() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setNowMs(Date.now());
|
||||
const intervalId = window.setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [status.nextRetryAt, status.reconnectPhase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
status.reconnectPhase !== "waiting" ||
|
||||
@@ -363,7 +308,22 @@ export function WebSocketConnectionCoordinator() {
|
||||
title: buildReconnectTitle(status),
|
||||
type: "error",
|
||||
})
|
||||
: buildReconnectToast(status, reconnectToastNowMsRef.current, triggerManualReconnect);
|
||||
: stackedThreadToast({
|
||||
actionProps: {
|
||||
children: "Retry now",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
description:
|
||||
status.nextRetryAt === null
|
||||
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
|
||||
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
|
||||
timeout: 0,
|
||||
title: buildReconnectTitle(status),
|
||||
type: "loading",
|
||||
});
|
||||
|
||||
if (toastIdRef.current) {
|
||||
toastManager.update(toastIdRef.current, toastPayload);
|
||||
@@ -405,7 +365,7 @@ export function WebSocketConnectionCoordinator() {
|
||||
|
||||
previousUiStateRef.current = uiState;
|
||||
previousDisconnectedAtRef.current = status.disconnectedAt;
|
||||
}, [reconnectToastNowMsRef, status]);
|
||||
}, [nowMs, status]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user