Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge f6f1b9c4a3 Instrument workspace entries tests via service construction
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:10:32 +00:00
Cursor AgentandJulius Marminge d283d94ad3 Fix workspace entries filesystem test layer
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:09:42 +00:00
Cursor AgentandJulius Marminge 63a9c85c26 Use Effect FileSystem for workspace entries
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:09:10 +00:00
Adam Buchweitz 4f0f24f055 fix: maintain reasoning selections for multiple providers (#2760) 2026-05-22 07:02:35 -07:00
12 changed files with 324 additions and 304 deletions

No files matched your search

@@ -17,7 +17,7 @@ import {
SshLaunchError,
SshPairingError,
SshPasswordPromptError,
type SshReadinessError,
SshReadinessError,
} from "@t3tools/ssh/errors";
import { SshEnvironmentManager, type RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import * as Context from "effect/Context";
@@ -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";
@@ -80,13 +79,11 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
return discoverSshHosts(input ?? {});
}
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError {
return (
isSshPasswordPromptError(error) &&
error instanceof SshPasswordPromptError &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
);
}
@@ -2,7 +2,6 @@ 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";
@@ -32,8 +31,6 @@ function makeLayer(
);
}
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
describe("DesktopSshRemoteApi", () => {
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
@@ -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,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fsPromises from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -13,7 +13,7 @@ import { ServerConfig } from "../../config.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { makeWorkspaceEntries, WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
@@ -29,6 +29,28 @@ const TestLayer = Layer.empty.pipe(
Layer.provideMerge(NodeServices.layer),
);
const makeWorkspaceEntriesWithFileSystem = (
makeFileSystem: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* makeWorkspaceEntries.pipe(
Effect.provideService(FileSystem.FileSystem, makeFileSystem(fileSystem)),
);
});
const makeWorkspaceEntriesWithReadDirectory = (
onReadDirectory: (
path: string,
run: () => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) =>
makeWorkspaceEntriesWithFileSystem((fileSystem) => ({
...fileSystem,
readDirectory: (inputPath, options) =>
onReadDirectory(inputPath, () => fileSystem.readDirectory(inputPath, options)),
}));
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
const fileSystem = yield* FileSystem.FileSystem;
const dir = yield* fileSystem.makeTempDirectoryScoped({
@@ -80,10 +102,6 @@ const appendSeparator = (input: string) =>
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
afterEach(() => {
vi.restoreAllMocks();
});
describe("search", () => {
it.effect("returns files and directories relative to cwd", () =>
Effect.gen(function* () {
@@ -227,26 +245,22 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
yield* writeTextFile(cwd, "src/components/Composer.tsx");
let rootReadCount = 0;
let releaseRootRead: (() => void) | undefined;
const rootReadGate = new Promise<void>((resolve) => {
releaseRootRead = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
if (args[0] === cwd) {
rootReadCount += 1;
await rootReadGate;
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const rootReadGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath === cwd
? Effect.gen(function* () {
rootReadCount += 1;
yield* Deferred.await(rootReadGate);
return yield* run();
})
: run(),
);
const searches = yield* Effect.all(
[
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
workspaceEntries.search({ cwd, query: "", limit: 100 }),
workspaceEntries.search({ cwd, query: "comp", limit: 100 }),
workspaceEntries.search({ cwd, query: "src", limit: 100 }),
],
{ concurrency: "unbounded" },
).pipe(Effect.forkScoped);
@@ -256,10 +270,10 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
}
yield* Effect.yieldNow;
}
releaseRootRead?.();
yield* Deferred.succeed(rootReadGate, undefined);
yield* Fiber.join(searches);
expect(rootReadCount).toBe(1);
assert.equal(rootReadCount, 1);
}),
);
@@ -274,41 +288,37 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
let activeReads = 0;
let peakReads = 0;
let releaseReads: (() => void) | undefined;
const readsGate = new Promise<void>((resolve) => {
releaseReads = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await readsGate;
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const search = yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }).pipe(
Effect.forkScoped,
const readsGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath !== cwd && inputPath.startsWith(cwd)
? Effect.gen(function* () {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
yield* Deferred.await(readsGate);
return yield* run().pipe(
Effect.ensuring(
Effect.sync(() => {
activeReads -= 1;
}),
),
);
})
: run(),
);
const search = yield* workspaceEntries
.search({ cwd, query: "", limit: 200 })
.pipe(Effect.forkScoped);
for (let attempt = 0; attempt < 50; attempt += 1) {
if (activeReads > 0) {
break;
}
yield* Effect.yieldNow;
}
releaseReads?.();
yield* Deferred.succeed(readsGate, undefined);
yield* Fiber.join(search);
expect(peakReads).toBeLessThanOrEqual(32);
assert.isAtMost(peakReads, 32);
}),
);
});
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import * as Cache from "effect/Cache";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
@@ -56,6 +56,11 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
normalizedName: string;
}
interface DirectoryEntry {
readonly name: string;
readonly kind: ProjectEntry["kind"];
}
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
function toPosixPath(input: string): string {
@@ -180,6 +185,7 @@ const resolveBrowseTarget = (
});
export const makeWorkspaceEntries = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const workspacePaths = yield* WorkspacePaths;
@@ -269,30 +275,64 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
},
);
const readDirectoryEntry = Effect.fn("WorkspaceEntries.readDirectoryEntry")(function* (
absoluteDir: string,
name: string,
): Effect.fn.Return<Option.Option<DirectoryEntry>, never> {
const absolutePath = path.join(absoluteDir, name);
const linkTarget = yield* fileSystem.readLink(absolutePath).pipe(Effect.option);
if (Option.isSome(linkTarget)) {
return Option.none();
}
return yield* fileSystem.stat(absolutePath).pipe(
Effect.map((info) =>
info.type === "Directory"
? Option.some({ name, kind: "directory" as const })
: info.type === "File"
? Option.some({ name, kind: "file" as const })
: Option.none<DirectoryEntry>(),
),
Effect.catch(() => Effect.succeed(Option.none<DirectoryEntry>())),
);
});
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
cwd: string,
relativeDir: string,
): Effect.fn.Return<
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
{
readonly relativeDir: string;
readonly entries: Option.Option<ReadonlyArray<DirectoryEntry>>;
},
WorkspaceEntriesError
> {
return yield* Effect.tryPromise({
try: async () => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
},
catch: (cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause instanceof Error ? cause.message : String(cause),
cause,
}),
}).pipe(
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
return yield* fileSystem.readDirectory(absoluteDir).pipe(
Effect.flatMap((names) =>
Effect.forEach(
names.toSorted((left, right) => left.localeCompare(right)),
(name) => readDirectoryEntry(absoluteDir, name),
{ concurrency: "unbounded" },
),
),
Effect.map((entries) => ({
relativeDir,
entries: Option.some(entries.filter(Option.isSome).map((entry) => entry.value)),
})),
Effect.mapError(
(cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause.message,
cause,
}),
),
Effect.catchIf(
() => relativeDir.length > 0,
() => Effect.succeed({ relativeDir, dirents: null }),
() =>
Effect.succeed({ relativeDir, entries: Option.none<ReadonlyArray<DirectoryEntry>>() }),
),
);
});
@@ -317,29 +357,26 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
const { relativeDir, dirents } = directoryEntry;
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
const { relativeDir, entries } = directoryEntry;
if (Option.isNone(entries))
return [] as Array<{ entry: DirectoryEntry; relativePath: string }>;
dirents.sort((left, right) => left.name.localeCompare(right.name));
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
for (const dirent of dirents) {
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
const candidates: Array<{ entry: DirectoryEntry; relativePath: string }> = [];
for (const entry of entries.value) {
if (!entry.name || entry.name === "." || entry.name === "..") {
continue;
}
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
if (entry.kind === "directory" && IGNORED_DIRECTORY_NAMES.has(entry.name)) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
relativeDir ? path.join(relativeDir, entry.name) : entry.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
candidates.push({ dirent, relativePath });
candidates.push({ entry, relativePath });
}
return candidates;
});
@@ -359,12 +396,12 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const entry = toSearchableWorkspaceEntry({
path: candidate.relativePath,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
kind: candidate.entry.kind,
parentPath: parentPathOf(candidate.relativePath),
});
entries.push(entry);
if (candidate.dirent.isDirectory()) {
if (candidate.entry.kind === "directory") {
pendingDirectories.push(candidate.relativePath);
}
@@ -442,33 +479,40 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
const entries = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.flatMap((names) =>
Effect.forEach(names, (name) => readDirectoryEntry(parentPath, name), {
concurrency: "unbounded",
}),
});
),
Effect.map((entries) => entries.filter(Option.isSome).map((entry) => entry.value)),
Effect.mapError(
(cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause.message}`,
cause,
}),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
return {
parentPath,
entries: dirents
entries: entries
.filter(
(dirent) =>
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith(".")),
(entry) =>
entry.kind === "directory" &&
entry.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !entry.name.startsWith(".")),
)
.map((dirent) => ({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
.map((entry) => ({
name: entry.name,
fullPath: path.join(parentPath, entry.name),
}))
.toSorted((left, right) => left.name.localeCompare(right.name)),
};
+13 -4
View File
@@ -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 } : {})}
+38
View File
@@ -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();
+6 -2
View File
@@ -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 };
+38 -95
View File
@@ -1,103 +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 SshReadinessProbeFailedError extends Schema.TaggedErrorClass<SshReadinessProbeFailedError>()(
"SshReadinessProbeFailedError",
{
message: Schema.String,
requestUrl: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshReadinessProbeTimedOutError extends Schema.TaggedErrorClass<SshReadinessProbeTimedOutError>()(
"SshReadinessProbeTimedOutError",
{
message: Schema.String,
requestUrl: Schema.String,
attempt: Schema.Number,
probeTimeoutMs: Schema.Number,
},
) {}
export class SshReadinessTimedOutError extends Schema.TaggedErrorClass<SshReadinessTimedOutError>()(
"SshReadinessTimedOutError",
{
message: Schema.String,
baseUrl: Schema.String,
requestUrl: Schema.String,
timeoutMs: Schema.Number,
intervalMs: Schema.Number,
probeTimeoutMs: Schema.Number,
attempts: Schema.Number,
cause: Schema.optional(Schema.Defect),
},
) {}
export type SshReadinessError =
| SshReadinessProbeFailedError
| SshReadinessProbeTimedOutError
| SshReadinessTimedOutError;
const isSshReadinessProbeFailedError = Schema.is(SshReadinessProbeFailedError);
const isSshReadinessProbeTimedOutError = Schema.is(SshReadinessProbeTimedOutError);
const isSshReadinessTimedOutError = Schema.is(SshReadinessTimedOutError);
export function isSshReadinessError(cause: unknown): cause is SshReadinessError {
return (
isSshReadinessProbeFailedError(cause) ||
isSshReadinessProbeTimedOutError(cause) ||
isSshReadinessTimedOutError(cause)
);
}
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;
}> {}
+3 -3
View File
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
Effect.result(
waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/",
timeout: Duration.seconds(1),
interval: Duration.millis(100),
probeTimeout: Duration.millis(250),
timeoutMs: 1_000,
intervalMs: 100,
probeTimeoutMs: 250,
}),
),
);
+46 -86
View File
@@ -45,20 +45,16 @@ import {
SshLaunchError,
SshPairingError,
SshPasswordPromptError,
SshReadinessProbeFailedError,
SshReadinessProbeTimedOutError,
SshReadinessTimedOutError,
isSshReadinessError,
type SshReadinessError,
SshReadinessError,
} from "./errors.ts";
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT = Duration.seconds(20);
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
const SSH_READY_TIMEOUT_MS = 20_000;
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
const REMOTE_READY_TIMEOUT_MS = 15_000;
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
@@ -241,37 +237,12 @@ function applyScriptPlaceholders(
}
export function describeReadinessCause(cause: unknown): unknown {
if (isSshReadinessError(cause)) {
const base = {
if (cause instanceof SshReadinessError) {
return {
_tag: cause._tag,
message: cause.message,
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
};
switch (cause._tag) {
case "SshReadinessProbeFailedError":
return {
...base,
requestUrl: cause.requestUrl,
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
};
case "SshReadinessProbeTimedOutError":
return {
...base,
requestUrl: cause.requestUrl,
attempt: cause.attempt,
probeTimeoutMs: cause.probeTimeoutMs,
};
case "SshReadinessTimedOutError":
return {
...base,
baseUrl: cause.baseUrl,
requestUrl: cause.requestUrl,
timeoutMs: cause.timeoutMs,
intervalMs: cause.intervalMs,
probeTimeoutMs: cause.probeTimeoutMs,
attempts: cause.attempts,
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
};
}
}
if (cause instanceof Error) {
return {
@@ -715,9 +686,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
});
}
@@ -899,21 +870,20 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
readonly baseUrl: string;
readonly timeout?: Duration.Input;
readonly interval?: Duration.Input;
readonly probeTimeout?: Duration.Input;
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly probeTimeoutMs?: number;
readonly path?: string;
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
const timeout = Duration.fromInputUnsafe(input.timeout ?? Duration.seconds(30));
const interval = Duration.fromInputUnsafe(input.interval ?? Duration.millis(100));
const probeTimeout = Duration.fromInputUnsafe(input.probeTimeout ?? SSH_READY_PROBE_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
const intervalMs = Duration.toMillis(interval);
const probeTimeoutMs = Duration.toMillis(probeTimeout);
const retryPolicy = Schedule.spaced(interval);
const timeoutMs = input.timeoutMs ?? 30_000;
const intervalMs = input.intervalMs ?? 100;
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
);
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
const client = yield* HttpClient.HttpClient;
const lastProbeFailure = yield* Ref.make<Option.Option<unknown>>(Option.none());
const lastProbeFailure = yield* Ref.make<unknown>(null);
let attempt = 0;
yield* Effect.logDebug("ssh.tunnel.httpReady.start", {
@@ -930,12 +900,11 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.gen(function* () {
attempt += 1;
const responseOption = yield* effect.pipe(
Effect.timeoutOption(probeTimeout),
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
Effect.mapError(
(cause) =>
new SshReadinessProbeFailedError({
new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
requestUrl,
cause,
}),
),
@@ -944,32 +913,30 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SshReadinessProbeTimedOutError({
new SshReadinessError({
message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
requestUrl,
attempt,
probeTimeoutMs,
cause: {
kind: "probe-timeout",
attempt,
probeTimeoutMs,
},
}),
),
});
}).pipe(
Effect.mapError((cause) =>
isSshReadinessError(cause)
cause instanceof SshReadinessError
? cause
: new SshReadinessProbeFailedError({
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
requestUrl,
cause,
}),
),
Effect.tapError((cause) =>
Ref.set(
lastProbeFailure,
Option.some({
attempt,
cause: describeReadinessCause(cause),
}),
),
Ref.set(lastProbeFailure, {
attempt,
cause: describeReadinessCause(cause),
}),
),
),
),
@@ -979,15 +946,14 @@ 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 SshReadinessProbeFailedError({
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
requestUrl,
cause,
}),
),
Effect.timeoutOption(timeout),
Effect.timeoutOption(Duration.millis(timeoutMs)),
);
return yield* Option.match(result, {
@@ -1007,17 +973,11 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
intervalMs,
probeTimeoutMs,
attempts: attempt,
lastFailure: Option.getOrUndefined(lastFailure),
lastFailure,
});
return yield* new SshReadinessTimedOutError({
return yield* new SshReadinessError({
message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
baseUrl: input.baseUrl,
requestUrl,
timeoutMs,
intervalMs,
probeTimeoutMs,
attempts: attempt,
...(Option.isSome(lastFailure) ? { cause: lastFailure.value } : {}),
cause: lastFailure,
});
}),
});
@@ -1276,7 +1236,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
yield* Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeout: SSH_READY_TIMEOUT,
timeoutMs: SSH_READY_TIMEOUT_MS,
}),
exitFailure,
).pipe(
@@ -1336,7 +1296,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: Duration.toMillis(TUNNEL_SHUTDOWN_TIMEOUT),
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore),
),
@@ -1580,7 +1540,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
[
tunnelEntry.process.kill({
killSignal: "SIGTERM",
forceKillAfter: Duration.toMillis(TUNNEL_SHUTDOWN_TIMEOUT),
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
}),
stopRemoteServer(
tunnelEntry.target,
@@ -1634,7 +1594,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
remotePort: entry.remotePort,
});
const readinessExit = yield* Effect.exit(
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
);
if (Exit.isSuccess(readinessExit)) {
yield* Effect.logDebug("ssh.environment.tunnel.reused", {