Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56b6615afd |
No files matched your search
@@ -58,8 +58,6 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
|
||||
|
||||
function pendingTaskDraftKey(messageId: string): string {
|
||||
return `pending-task:${messageId}`;
|
||||
}
|
||||
@@ -350,14 +348,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
// Keep the user's explicit choice separate from the resolved display value:
|
||||
// only the explicit flag is ever written back to the draft, so the resolved
|
||||
// value keeps tracking the server setting when the config loads late.
|
||||
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
|
||||
const startFromOrigin =
|
||||
draftStartFromOrigin ??
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -377,7 +368,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions.find((option) => option.isDefault)?.selection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
@@ -485,14 +475,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
);
|
||||
const branchState = useBranches(branchTarget);
|
||||
const branchesLoading = branchState.isPending;
|
||||
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
|
||||
const availableBranches = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
allBranchRefs,
|
||||
branchState.data?.refs ?? [],
|
||||
Arr.filter((branch) => !branch.isRemote),
|
||||
),
|
||||
[allBranchRefs],
|
||||
[branchState.data?.refs],
|
||||
);
|
||||
|
||||
const filteredBranches = useMemo(() => {
|
||||
@@ -554,11 +543,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
@@ -571,11 +560,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
|
||||
startFromOrigin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
|
||||
);
|
||||
|
||||
const setStartFromOrigin = useCallback(
|
||||
@@ -608,16 +597,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
// The default may only exist as origin/<default> (isRemote), which
|
||||
// availableBranches filters out — search the unfiltered refs for it.
|
||||
const preferredBranch =
|
||||
allBranchRefs.find((branch) => branch.isDefault) ??
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
@@ -709,12 +696,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
workspaceMode: mode,
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
// The draft only carries the flag when the user touched it; fall
|
||||
// back to the resolved default (server settings) so queued tasks
|
||||
// drain with the same origin mode the composer displayed.
|
||||
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
|
||||
? { startFromOrigin: true }
|
||||
: {}),
|
||||
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
createdAt: metadata.createdAt,
|
||||
};
|
||||
@@ -725,7 +707,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
selectedModel,
|
||||
selectedProject,
|
||||
selectedProjectDraftKey,
|
||||
startFromOrigin,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ export type ModelOption = {
|
||||
readonly providerKey: string;
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -79,7 +78,6 @@ export function buildModelOptions(
|
||||
providerKey: provider.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -109,7 +107,6 @@ export function buildModelOptions(
|
||||
providerKey: fallbackModelSelection.instanceId,
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { OrchestrationEvent, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { OrchestrationCommand } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -13,6 +8,7 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Metric from "effect/Metric";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -37,8 +33,13 @@ import {
|
||||
type OrchestrationDispatchError,
|
||||
type OrchestrationProjectorDecodeError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
createEmptyCommandReadModel,
|
||||
fromWireReadModel,
|
||||
type CommandReadModel,
|
||||
} from "../commandReadModel.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
import { projectEvent } from "../projector.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -85,15 +86,15 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
let commandReadModel = createEmptyReadModel(yield* nowIso);
|
||||
let commandReadModel: CommandReadModel = createEmptyCommandReadModel(yield* nowIso);
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const projectEventsOntoReadModel = (
|
||||
baseReadModel: OrchestrationReadModel,
|
||||
baseReadModel: CommandReadModel,
|
||||
events: ReadonlyArray<OrchestrationEvent>,
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
): Effect.Effect<CommandReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
Effect.gen(function* () {
|
||||
let nextReadModel = baseReadModel;
|
||||
for (const event of events) {
|
||||
@@ -298,12 +299,21 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
// Seed the in-memory command model from the DB projection. Deleted threads
|
||||
// are dropped so the model starts consistent with the projector's eviction
|
||||
// policy (see commandReadModel.ts / the `thread.deleted` projector branch).
|
||||
commandReadModel = fromWireReadModel(yield* projectionSnapshotQuery.getCommandReadModel(), {
|
||||
dropDeletedThreads: true,
|
||||
});
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
||||
Effect.annotateLogs({
|
||||
sequence: commandReadModel.snapshotSequence,
|
||||
threadCount: HashMap.size(commandReadModel.threads),
|
||||
projectCount: HashMap.size(commandReadModel.projects),
|
||||
}),
|
||||
);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { fromWireReadModel } from "./commandReadModel.ts";
|
||||
import {
|
||||
findThreadById,
|
||||
listThreadsByProjectId,
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const readModel: OrchestrationReadModel = {
|
||||
const wireReadModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 2,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
@@ -102,6 +103,8 @@ const readModel: OrchestrationReadModel = {
|
||||
],
|
||||
};
|
||||
|
||||
const readModel = fromWireReadModel(wireReadModel, { dropDeletedThreads: false });
|
||||
|
||||
const messageSendCommand: OrchestrationCommand = {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationProject,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationThread,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
|
||||
import {
|
||||
findProjectById,
|
||||
findThreadById,
|
||||
isThreadDeleted,
|
||||
listThreadsByProjectId,
|
||||
type CommandReadModel,
|
||||
} from "./commandReadModel.ts";
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
|
||||
export { findProjectById, findThreadById, listThreadsByProjectId };
|
||||
|
||||
function invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError {
|
||||
return new OrchestrationCommandInvariantError({
|
||||
commandType,
|
||||
@@ -18,29 +27,8 @@ function invariantError(commandType: string, detail: string): OrchestrationComma
|
||||
});
|
||||
}
|
||||
|
||||
export function findThreadById(
|
||||
readModel: OrchestrationReadModel,
|
||||
threadId: ThreadId,
|
||||
): OrchestrationThread | undefined {
|
||||
return readModel.threads.find((thread) => thread.id === threadId);
|
||||
}
|
||||
|
||||
export function findProjectById(
|
||||
readModel: OrchestrationReadModel,
|
||||
projectId: ProjectId,
|
||||
): OrchestrationProject | undefined {
|
||||
return readModel.projects.find((project) => project.id === projectId);
|
||||
}
|
||||
|
||||
export function listThreadsByProjectId(
|
||||
readModel: OrchestrationReadModel,
|
||||
projectId: ProjectId,
|
||||
): ReadonlyArray<OrchestrationThread> {
|
||||
return readModel.threads.filter((thread) => thread.projectId === projectId);
|
||||
}
|
||||
|
||||
export function requireProject(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly projectId: ProjectId;
|
||||
}): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {
|
||||
@@ -57,7 +45,7 @@ export function requireProject(input: {
|
||||
}
|
||||
|
||||
export function requireProjectAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly projectId: ProjectId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
@@ -73,18 +61,23 @@ export function requireProjectAbsent(input: {
|
||||
}
|
||||
|
||||
export function requireActiveProjectWorkspaceRootAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly workspaceRoot: string;
|
||||
readonly exceptProjectId?: ProjectId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
|
||||
const existingProject = input.readModel.projects.find(
|
||||
(project) =>
|
||||
let existingProject: OrchestrationProject | undefined;
|
||||
for (const project of HashMap.values(input.readModel.projects)) {
|
||||
if (
|
||||
project.deletedAt === null &&
|
||||
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
|
||||
project.id !== input.exceptProjectId,
|
||||
);
|
||||
project.id !== input.exceptProjectId
|
||||
) {
|
||||
existingProject = project;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (existingProject === undefined) {
|
||||
return Effect.void;
|
||||
}
|
||||
@@ -97,7 +90,7 @@ export function requireActiveProjectWorkspaceRootAbsent(input: {
|
||||
}
|
||||
|
||||
export function requireThread(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -114,7 +107,7 @@ export function requireThread(input: {
|
||||
}
|
||||
|
||||
export function requireThreadArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -133,7 +126,7 @@ export function requireThreadArchived(input: {
|
||||
}
|
||||
|
||||
export function requireThreadNotArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -152,11 +145,16 @@ export function requireThreadNotArchived(input: {
|
||||
}
|
||||
|
||||
export function requireThreadAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
if (!findThreadById(input.readModel, input.threadId)) {
|
||||
// A deleted thread is evicted from `threads` but its id is retained in
|
||||
// `deletedThreadIds`, so reject re-using a live OR previously-deleted id.
|
||||
if (
|
||||
!findThreadById(input.readModel, input.threadId) &&
|
||||
!isThreadDeleted(input.readModel, input.threadId)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.fail(
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createEmptyCommandReadModel,
|
||||
findProjectById,
|
||||
findThreadById,
|
||||
fromWireReadModel,
|
||||
isThreadDeleted,
|
||||
listThreadsByProjectId,
|
||||
} from "./commandReadModel.ts";
|
||||
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
function makeThread(
|
||||
id: string,
|
||||
projectId: string,
|
||||
overrides?: Partial<OrchestrationThread>,
|
||||
): OrchestrationThread {
|
||||
return {
|
||||
id: ThreadId.make(id),
|
||||
projectId: ProjectId.make(projectId),
|
||||
title: id,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const wireReadModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 5,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.make("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
makeThread("thread-live", "project-a"),
|
||||
makeThread("thread-archived", "project-a", { archivedAt: now }),
|
||||
makeThread("thread-deleted", "project-a", { deletedAt: now }),
|
||||
makeThread("thread-other", "project-b"),
|
||||
],
|
||||
};
|
||||
|
||||
describe("commandReadModel", () => {
|
||||
it("creates an empty model", () => {
|
||||
const model = createEmptyCommandReadModel(now);
|
||||
expect(model.snapshotSequence).toBe(0);
|
||||
expect(HashMap.size(model.threads)).toBe(0);
|
||||
expect(HashMap.size(model.projects)).toBe(0);
|
||||
expect(model.updatedAt).toBe(now);
|
||||
});
|
||||
|
||||
it("seeds from the wire model and drops deleted threads by default", () => {
|
||||
const model = fromWireReadModel(wireReadModel);
|
||||
expect(model.snapshotSequence).toBe(5);
|
||||
// deleted thread is evicted; archived + live + other retained
|
||||
expect(HashMap.size(model.threads)).toBe(3);
|
||||
expect(HashMap.has(model.threads, ThreadId.make("thread-deleted"))).toBe(false);
|
||||
expect(HashMap.has(model.threads, ThreadId.make("thread-archived"))).toBe(true);
|
||||
expect(HashMap.has(model.threads, ThreadId.make("thread-live"))).toBe(true);
|
||||
expect(HashMap.size(model.projects)).toBe(1);
|
||||
// The evicted deleted thread's id is retained so the create-twice invariant
|
||||
// survives a restart.
|
||||
expect(isThreadDeleted(model, ThreadId.make("thread-deleted"))).toBe(true);
|
||||
expect(isThreadDeleted(model, ThreadId.make("thread-live"))).toBe(false);
|
||||
expect(isThreadDeleted(model, ThreadId.make("thread-archived"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains deleted threads when dropDeletedThreads is false", () => {
|
||||
const model = fromWireReadModel(wireReadModel, { dropDeletedThreads: false });
|
||||
expect(HashMap.size(model.threads)).toBe(4);
|
||||
expect(HashMap.has(model.threads, ThreadId.make("thread-deleted"))).toBe(true);
|
||||
});
|
||||
|
||||
it("finds threads and projects by id with O(1) lookups", () => {
|
||||
const model = fromWireReadModel(wireReadModel);
|
||||
expect(findThreadById(model, ThreadId.make("thread-live"))?.projectId).toBe("project-a");
|
||||
expect(findThreadById(model, ThreadId.make("thread-deleted"))).toBeUndefined();
|
||||
expect(findThreadById(model, ThreadId.make("missing"))).toBeUndefined();
|
||||
expect(findProjectById(model, ProjectId.make("project-a"))?.title).toBe("Project A");
|
||||
expect(findProjectById(model, ProjectId.make("missing"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("lists threads by project id", () => {
|
||||
const model = fromWireReadModel(wireReadModel);
|
||||
const ids = listThreadsByProjectId(model, ProjectId.make("project-a"))
|
||||
.map((thread) => thread.id)
|
||||
.toSorted();
|
||||
expect(ids).toEqual([ThreadId.make("thread-archived"), ThreadId.make("thread-live")]);
|
||||
expect(listThreadsByProjectId(model, ProjectId.make("project-b")).map((t) => t.id)).toEqual([
|
||||
ThreadId.make("thread-other"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
OrchestrationProject,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationThread,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import * as HashSet from "effect/HashSet";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
/**
|
||||
* Server-internal representation of the orchestration read model.
|
||||
*
|
||||
* Unlike the wire {@link OrchestrationReadModel} (which uses arrays and is
|
||||
* produced by the DB-backed `ProjectionSnapshotQuery`), this model is only ever
|
||||
* touched by the single serial command-worker fiber in `OrchestrationEngine`.
|
||||
* It uses persistent `HashMap`s keyed by id so the projector and command
|
||||
* invariants get O(1)-ish lookups and single-key updates instead of O(N)
|
||||
* array scans and full-array copies on every event.
|
||||
*
|
||||
* The model is never serialized or sent over the wire, so its shape can evolve
|
||||
* independently of the contract.
|
||||
*/
|
||||
export interface CommandReadModel {
|
||||
readonly snapshotSequence: number;
|
||||
readonly projects: HashMap.HashMap<ProjectId, OrchestrationProject>;
|
||||
readonly threads: HashMap.HashMap<ThreadId, OrchestrationThread>;
|
||||
/**
|
||||
* Ids of threads that have been deleted. Deleted threads are evicted from
|
||||
* `threads` (freeing their message/activity/checkpoint arrays), but their id
|
||||
* is retained here so `requireThreadAbsent` still rejects re-creating a
|
||||
* thread with a previously-used id — the "cannot be created twice" invariant
|
||||
* the DB projection also upholds (its tombstone row is never removed).
|
||||
*/
|
||||
readonly deletedThreadIds: HashSet.HashSet<ThreadId>;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export function createEmptyCommandReadModel(nowIso: string): CommandReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: HashMap.empty<ProjectId, OrchestrationProject>(),
|
||||
threads: HashMap.empty<ThreadId, OrchestrationThread>(),
|
||||
deletedThreadIds: HashSet.empty<ThreadId>(),
|
||||
updatedAt: nowIso,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a thread id has been used and deleted. Used by `requireThreadAbsent`
|
||||
* so an evicted (deleted) thread's id cannot be re-created.
|
||||
*/
|
||||
export function isThreadDeleted(model: CommandReadModel, threadId: ThreadId): boolean {
|
||||
return HashSet.has(model.deletedThreadIds, threadId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed a {@link CommandReadModel} from the array-based wire read model produced
|
||||
* by `ProjectionSnapshotQuery.getCommandReadModel()` at engine boot.
|
||||
*
|
||||
* Deleted threads are dropped so the in-memory model starts consistent with the
|
||||
* projector's eviction policy (deleted threads are removed, archived threads are
|
||||
* retained). The DB projection remains the source of truth for deleted rows.
|
||||
*/
|
||||
export function fromWireReadModel(
|
||||
model: OrchestrationReadModel,
|
||||
options?: { readonly dropDeletedThreads?: boolean },
|
||||
): CommandReadModel {
|
||||
const dropDeletedThreads = options?.dropDeletedThreads ?? true;
|
||||
const threads = dropDeletedThreads
|
||||
? model.threads.filter((thread) => thread.deletedAt === null)
|
||||
: model.threads;
|
||||
// Retain the ids of deleted threads so the create-twice invariant survives
|
||||
// a restart even though the (evicted) thread bodies are not loaded.
|
||||
const deletedThreadIds = HashSet.fromIterable(
|
||||
model.threads.filter((thread) => thread.deletedAt !== null).map((thread) => thread.id),
|
||||
);
|
||||
return {
|
||||
snapshotSequence: model.snapshotSequence,
|
||||
updatedAt: model.updatedAt,
|
||||
projects: HashMap.fromIterable(model.projects.map((project) => [project.id, project] as const)),
|
||||
threads: HashMap.fromIterable(threads.map((thread) => [thread.id, thread] as const)),
|
||||
deletedThreadIds,
|
||||
};
|
||||
}
|
||||
|
||||
export function findThreadById(
|
||||
model: CommandReadModel,
|
||||
threadId: ThreadId,
|
||||
): OrchestrationThread | undefined {
|
||||
return Option.getOrUndefined(HashMap.get(model.threads, threadId));
|
||||
}
|
||||
|
||||
export function findProjectById(
|
||||
model: CommandReadModel,
|
||||
projectId: ProjectId,
|
||||
): OrchestrationProject | undefined {
|
||||
return Option.getOrUndefined(HashMap.get(model.projects, projectId));
|
||||
}
|
||||
|
||||
export function listThreadsByProjectId(
|
||||
model: CommandReadModel,
|
||||
projectId: ProjectId,
|
||||
): ReadonlyArray<OrchestrationThread> {
|
||||
const result: OrchestrationThread[] = [];
|
||||
for (const thread of HashMap.values(model.threads)) {
|
||||
if (thread.projectId === projectId) {
|
||||
result.push(thread);
|
||||
}
|
||||
}
|
||||
// HashMap iteration order is not insertion order; sort by creation time (then
|
||||
// id) so callers observe a stable, deterministic order — matching the prior
|
||||
// array-backed behavior. Only used by the rare `project.delete` fan-out.
|
||||
return result.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
@@ -214,4 +216,134 @@ it.layer(NodeServices.layer)("decider deletion flows", (it) => {
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects commands targeting an already-deleted (evicted) thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const seeded = yield* seedReadModel;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
// Delete thread-delete-1; the projector evicts it from the model.
|
||||
const afterDelete = yield* projectEvent(seeded, {
|
||||
sequence: 4,
|
||||
eventId: asEventId("evt-thread-delete-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-1"),
|
||||
type: "thread.deleted",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-delete-1"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-delete-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
deletedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
// A follow-up command to the deleted thread now fails cleanly.
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: asCommandId("cmd-turn-after-delete"),
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("msg-after-delete"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel: afterDelete,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("does not exist");
|
||||
|
||||
// Re-creating a thread with the SAME (deleted) id is rejected: the id is
|
||||
// retained in deletedThreadIds even though the thread body was evicted, so
|
||||
// the "cannot be created twice" invariant still holds and the durable DB
|
||||
// row is not silently overwritten.
|
||||
const recreateSameId = (threadId: ThreadId) =>
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.create",
|
||||
commandId: asCommandId(`cmd-recreate-${threadId}`),
|
||||
threadId,
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Recreate",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
},
|
||||
readModel: afterDelete,
|
||||
});
|
||||
|
||||
const recreateError = yield* Effect.flip(recreateSameId(asThreadId("thread-delete-1")));
|
||||
expect(recreateError.message).toContain("cannot be created twice");
|
||||
|
||||
// A fresh thread with a NEW, never-used id can still be created.
|
||||
const created = yield* recreateSameId(asThreadId("thread-delete-3"));
|
||||
const createdEvents = Array.isArray(created) ? created : [created];
|
||||
expect(createdEvents.map((event) => event.type)).toEqual(["thread.created"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("projector evicts deleted threads but retains archived threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const seeded = yield* seedReadModel;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
expect(HashMap.size(seeded.threads)).toBe(2);
|
||||
|
||||
// Archiving keeps the thread resident (unarchive/other commands need it).
|
||||
const afterArchive = yield* projectEvent(seeded, {
|
||||
sequence: 4,
|
||||
eventId: asEventId("evt-thread-archive-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-1"),
|
||||
type: "thread.archived",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-archive-1"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-archive-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
archivedAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
expect(HashMap.size(afterArchive.threads)).toBe(2);
|
||||
expect(HashMap.has(afterArchive.threads, asThreadId("thread-delete-1"))).toBe(true);
|
||||
|
||||
// Deleting evicts the thread from the in-memory model entirely.
|
||||
const afterDelete = yield* projectEvent(afterArchive, {
|
||||
sequence: 5,
|
||||
eventId: asEventId("evt-thread-delete-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-2"),
|
||||
type: "thread.deleted",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-delete-2"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-delete-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
deletedAt: now,
|
||||
},
|
||||
});
|
||||
expect(HashMap.size(afterDelete.threads)).toBe(1);
|
||||
expect(HashMap.has(afterDelete.threads, asThreadId("thread-delete-2"))).toBe(false);
|
||||
expect(HashMap.has(afterDelete.threads, asThreadId("thread-delete-1"))).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,14 +1,10 @@
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, type OrchestrationCommand, type OrchestrationEvent } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import type { CommandReadModel } from "./commandReadModel.ts";
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
import {
|
||||
listThreadsByProjectId,
|
||||
@@ -65,7 +61,7 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
readModel,
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
@@ -99,7 +95,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
readModel,
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly readModel: CommandReadModel;
|
||||
}): Effect.fn.Return<
|
||||
DecideOrchestrationCommandResult,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
|
||||
@@ -5,12 +5,25 @@ import {
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { CommandReadModel } from "./commandReadModel.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
/** Thread list from the map, for assertions that previously used an array. */
|
||||
function threadsArray(model: CommandReadModel): ReadonlyArray<OrchestrationThread> {
|
||||
return Array.from(HashMap.values(model.threads));
|
||||
}
|
||||
|
||||
/** First thread in the map (insertion-order-independent tests use a single thread). */
|
||||
function firstThread(model: CommandReadModel): OrchestrationThread | undefined {
|
||||
return threadsArray(model)[0];
|
||||
}
|
||||
|
||||
function makeEvent(input: {
|
||||
sequence: number;
|
||||
type: OrchestrationEvent["type"];
|
||||
@@ -72,7 +85,7 @@ describe("orchestration projector", () => {
|
||||
);
|
||||
|
||||
expect(next.snapshotSequence).toBe(1);
|
||||
expect(next.threads).toEqual([
|
||||
expect(threadsArray(next)).toEqual([
|
||||
{
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
@@ -183,7 +196,7 @@ describe("orchestration projector", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(archived.threads[0]?.archivedAt).toBe(later);
|
||||
expect(firstThread(archived)?.archivedAt).toBe(later);
|
||||
|
||||
const unarchived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
@@ -202,7 +215,7 @@ describe("orchestration projector", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(unarchived.threads[0]?.archivedAt).toBeNull();
|
||||
expect(firstThread(unarchived)?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
@@ -231,7 +244,7 @@ describe("orchestration projector", () => {
|
||||
|
||||
expect(next.snapshotSequence).toBe(7);
|
||||
expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
|
||||
expect(next.threads).toEqual([]);
|
||||
expect(threadsArray(next)).toEqual([]);
|
||||
});
|
||||
|
||||
it("tracks latest turn id from session lifecycle events", async () => {
|
||||
@@ -327,13 +340,13 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const thread = afterRunning.threads[0];
|
||||
const thread = firstThread(afterRunning);
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
|
||||
// Leaving the "running" session status settles the running turn with the
|
||||
// session timestamp as the turn end.
|
||||
const settledThread = afterReady.threads[0];
|
||||
const settledThread = firstThread(afterReady);
|
||||
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(settledThread?.latestTurn?.state).toBe("completed");
|
||||
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
|
||||
@@ -391,8 +404,8 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
|
||||
expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
|
||||
expect(firstThread(afterUpdate)?.runtimeMode).toBe("approval-required");
|
||||
expect(firstThread(afterUpdate)?.updatedAt).toBe(updatedAt);
|
||||
});
|
||||
|
||||
it("marks assistant messages completed with non-streaming updates", async () => {
|
||||
@@ -477,7 +490,7 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const message = afterComplete.threads[0]?.messages[0];
|
||||
const message = firstThread(afterComplete)?.messages[0];
|
||||
expect(message?.id).toBe("assistant:msg-1");
|
||||
expect(message?.text).toBe("hello");
|
||||
expect(message?.streaming).toBe(false);
|
||||
@@ -685,7 +698,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = afterRevert.threads[0];
|
||||
const thread = firstThread(afterRevert);
|
||||
expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
|
||||
[
|
||||
{ role: "user", text: "First edit" },
|
||||
@@ -842,7 +855,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = afterRevert.threads[0];
|
||||
const thread = firstThread(afterRevert);
|
||||
expect(
|
||||
thread?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
@@ -944,7 +957,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterMessages),
|
||||
);
|
||||
|
||||
const thread = finalState.threads[0];
|
||||
const thread = firstThread(finalState);
|
||||
expect(thread?.messages).toHaveLength(2_000);
|
||||
expect(thread?.messages[0]?.id).toBe("msg-100");
|
||||
expect(thread?.messages.at(-1)?.id).toBe("msg-2099");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationEvent, OrchestrationProject, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationMessage,
|
||||
@@ -6,8 +6,16 @@ import {
|
||||
OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HashMap from "effect/HashMap";
|
||||
import * as HashSet from "effect/HashSet";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
createEmptyCommandReadModel,
|
||||
findThreadById,
|
||||
type CommandReadModel,
|
||||
} from "./commandReadModel.ts";
|
||||
import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
|
||||
import {
|
||||
MessageSentPayloadSchema,
|
||||
@@ -61,12 +69,40 @@ function settledTurnStateForSessionStatus(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a patch to a single thread, keyed by id. No-op if the thread is absent
|
||||
* (mirrors the previous array-map behavior, which left the collection unchanged
|
||||
* when no entry matched).
|
||||
*/
|
||||
function updateThread(
|
||||
threads: ReadonlyArray<OrchestrationThread>,
|
||||
threads: HashMap.HashMap<ThreadId, OrchestrationThread>,
|
||||
threadId: ThreadId,
|
||||
patch: ThreadPatch,
|
||||
): OrchestrationThread[] {
|
||||
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
|
||||
): HashMap.HashMap<ThreadId, OrchestrationThread> {
|
||||
const existing = HashMap.get(threads, threadId);
|
||||
if (Option.isNone(existing)) {
|
||||
return threads;
|
||||
}
|
||||
return HashMap.set(threads, threadId, { ...existing.value, ...patch });
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an update function to a single project in the model, keyed by id. No-op
|
||||
* if the project is absent.
|
||||
*/
|
||||
function updateProject(
|
||||
model: CommandReadModel,
|
||||
projectId: OrchestrationProject["id"],
|
||||
update: (project: OrchestrationProject) => OrchestrationProject,
|
||||
): CommandReadModel {
|
||||
const existing = HashMap.get(model.projects, projectId);
|
||||
if (Option.isNone(existing)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
projects: HashMap.set(model.projects, projectId, update(existing.value)),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeForEvent<A>(
|
||||
@@ -178,20 +214,15 @@ function compareThreadActivities(
|
||||
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: nowIso,
|
||||
};
|
||||
export function createEmptyReadModel(nowIso: string): CommandReadModel {
|
||||
return createEmptyCommandReadModel(nowIso);
|
||||
}
|
||||
|
||||
export function projectEvent(
|
||||
model: OrchestrationReadModel,
|
||||
model: CommandReadModel,
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {
|
||||
const nextBase: OrchestrationReadModel = {
|
||||
): Effect.Effect<CommandReadModel, OrchestrationProjectorDecodeError> {
|
||||
const nextBase: CommandReadModel = {
|
||||
...model,
|
||||
snapshotSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
@@ -201,8 +232,7 @@ export function projectEvent(
|
||||
case "project.created":
|
||||
return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => {
|
||||
const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);
|
||||
const nextProject = {
|
||||
const nextProject: OrchestrationProject = {
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
@@ -215,52 +245,38 @@ export function projectEvent(
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
projects: existing
|
||||
? nextBase.projects.map((entry) =>
|
||||
entry.id === payload.projectId ? nextProject : entry,
|
||||
)
|
||||
: [...nextBase.projects, nextProject],
|
||||
projects: HashMap.set(nextBase.projects, payload.projectId, nextProject),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
case "project.meta-updated":
|
||||
return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
projects: nextBase.projects.map((project) =>
|
||||
project.id === payload.projectId
|
||||
? {
|
||||
...project,
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
}
|
||||
: project,
|
||||
),
|
||||
})),
|
||||
Effect.map((payload) =>
|
||||
updateProject(nextBase, payload.projectId, (project) => ({
|
||||
...project,
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
case "project.deleted":
|
||||
return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
projects: nextBase.projects.map((project) =>
|
||||
project.id === payload.projectId
|
||||
? {
|
||||
...project,
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
}
|
||||
: project,
|
||||
),
|
||||
})),
|
||||
Effect.map((payload) =>
|
||||
updateProject(nextBase, payload.projectId, (project) => ({
|
||||
...project,
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
case "thread.created":
|
||||
@@ -295,23 +311,27 @@ export function projectEvent(
|
||||
event.type,
|
||||
"thread",
|
||||
);
|
||||
const existing = nextBase.threads.find((entry) => entry.id === thread.id);
|
||||
return {
|
||||
...nextBase,
|
||||
threads: existing
|
||||
? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
|
||||
: [...nextBase.threads, thread],
|
||||
threads: HashMap.set(nextBase.threads, thread.id, thread),
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.deleted":
|
||||
// Evict deleted threads from the in-memory model entirely rather than
|
||||
// tombstoning them. The DB projection retains the row (it is the source
|
||||
// of truth for downstream/HTTP reads and cleanup reactors consume the
|
||||
// event stream, not this model), and no command legitimately targets an
|
||||
// already-deleted thread. This is the primary fix for unbounded growth:
|
||||
// a deleted thread's messages/activities/checkpoints are freed and it no
|
||||
// longer costs anything on every subsequent event. The id is recorded in
|
||||
// `deletedThreadIds` so `requireThreadAbsent` still rejects re-creating a
|
||||
// thread with a previously-used id (the invariant the DB tombstone kept).
|
||||
return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
}),
|
||||
threads: HashMap.remove(nextBase.threads, payload.threadId),
|
||||
deletedThreadIds: HashSet.add(nextBase.deletedThreadIds, payload.threadId),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -388,7 +408,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -449,7 +469,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -512,7 +532,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -544,7 +564,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -614,7 +634,7 @@ export function projectEvent(
|
||||
case "thread.reverted":
|
||||
return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -670,7 +690,7 @@ export function projectEvent(
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
@@ -92,67 +92,11 @@ it.effect("launches the default browser through the platform command", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reveals a file in Finder on macOS", () => {
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
const target = "/tmp/project with spaces/src/odd '✨' file.ts";
|
||||
return Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
|
||||
yield* launcher.revealInFileManager(target);
|
||||
|
||||
assert.ok(spawned);
|
||||
assert.equal(spawned.command, "open");
|
||||
assert.deepEqual(spawned.args, ["-R", target]);
|
||||
assert.equal(spawned.options.detached, true);
|
||||
assert.equal(didUnref, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
platform: "darwin",
|
||||
onSpawn: (command) => {
|
||||
spawned = command;
|
||||
},
|
||||
onUnref: () => {
|
||||
didUnref = true;
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reveals a file in Explorer on Windows", () => {
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
const target = `C:/project with spaces/src/odd '✨' file.ts`;
|
||||
const windowsTarget = String.raw`C:\project with spaces\src\odd '✨' file.ts`;
|
||||
return Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
|
||||
yield* launcher.revealInFileManager(target);
|
||||
|
||||
assert.ok(spawned);
|
||||
assert.equal(spawned.command, "explorer");
|
||||
assert.deepEqual(spawned.args, ["/select,", windowsTarget]);
|
||||
assert.equal(spawned.options.detached, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
platform: "win32",
|
||||
onSpawn: (command) => {
|
||||
spawned = command;
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("launches an installed editor with platform-safe arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-editors-",
|
||||
});
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
|
||||
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
@@ -190,9 +134,7 @@ it.effect("discovers editors through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-editors-",
|
||||
});
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
|
||||
|
||||
@@ -217,10 +159,7 @@ it.effect("rejects unknown editors through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const error = yield* launcher
|
||||
.launchEditor({
|
||||
editor: "missing-editor" as never,
|
||||
cwd: "/tmp/workspace",
|
||||
})
|
||||
.launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
|
||||
assert.equal(error.editor, "missing-editor");
|
||||
|
||||
@@ -313,8 +313,6 @@ export class ExternalLauncher extends Context.Service<
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
|
||||
/** Reveal a workspace path in the host platform's file manager. */
|
||||
readonly revealInFileManager: (target: string) => Effect.Effect<void, ExternalLauncherError>;
|
||||
}
|
||||
>()("t3/process/externalLauncher") {}
|
||||
|
||||
@@ -334,9 +332,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new ExternalLauncherUnknownEditorError({
|
||||
editor: input.editor,
|
||||
});
|
||||
return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
@@ -353,9 +349,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new ExternalLauncherUnsupportedEditorError({
|
||||
editor: input.editor,
|
||||
});
|
||||
return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -436,57 +430,6 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
|
||||
);
|
||||
});
|
||||
|
||||
const resolveFileManagerRevealLaunch = Effect.fn("externalLauncher.resolveFileManagerRevealLaunch")(
|
||||
function* (target: string): Effect.fn.Return<ProcessLaunch, never, Path.Path> {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return {
|
||||
command: "open",
|
||||
args: ["-R", target],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
case "win32": {
|
||||
const windowsTarget = target.replaceAll("/", "\\");
|
||||
return {
|
||||
command: "explorer",
|
||||
args: ["/select,", windowsTarget],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return {
|
||||
command: "xdg-open",
|
||||
args: [path.dirname(target)],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const revealInFileManager = Effect.fn("externalLauncher.revealInFileManager")(function* (
|
||||
target: string,
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
ExternalLauncherError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
> {
|
||||
const launch = yield* resolveFileManagerRevealLaunch(target);
|
||||
return yield* launchAndUnref(
|
||||
launch,
|
||||
(cause) =>
|
||||
new ExternalLauncherEditorSpawnError({
|
||||
editor: "file-manager",
|
||||
target,
|
||||
command: launch.command,
|
||||
args: launch.args,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -514,11 +457,6 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
revealInFileManager: (target) =>
|
||||
revealInFileManager(target).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1711,133 +1711,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => runtimeEvents.push(event)),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Undeclared wire-only roster snapshot + every typed UX-internal
|
||||
// subtype and top-level type consumed silently: none may surface as
|
||||
// unknown-subtype warnings.
|
||||
for (const message of [
|
||||
{
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
|
||||
session_id: "session",
|
||||
uuid: "roster",
|
||||
},
|
||||
{
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "t1",
|
||||
patch: { status: "running" },
|
||||
session_id: "session",
|
||||
uuid: "tu",
|
||||
},
|
||||
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
|
||||
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
|
||||
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
|
||||
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
|
||||
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
|
||||
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
|
||||
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
|
||||
{
|
||||
type: "system",
|
||||
subtype: "notification",
|
||||
key: "context",
|
||||
text: "low priority note",
|
||||
priority: "low",
|
||||
session_id: "session",
|
||||
uuid: "notif",
|
||||
},
|
||||
]) {
|
||||
harness.query.emit(message as unknown as SDKMessage);
|
||||
}
|
||||
// High-priority notifications DO surface as a warning row.
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "notification",
|
||||
key: "limit",
|
||||
text: "context window nearly full",
|
||||
priority: "high",
|
||||
session_id: "session",
|
||||
uuid: "notif-high",
|
||||
} as unknown as SDKMessage);
|
||||
// session_state_changed maps to the matching session states.
|
||||
for (const [state, uuid] of [
|
||||
["running", "ssc-run"],
|
||||
["requires_action", "ssc-req"],
|
||||
["idle", "ssc-idle"],
|
||||
]) {
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
session_id: "session",
|
||||
uuid,
|
||||
} as unknown as SDKMessage);
|
||||
}
|
||||
// api_retry maps to a session heartbeat, not a warning row.
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "api_retry",
|
||||
attempt: 3,
|
||||
max_retries: 10,
|
||||
retry_delay_ms: 1000,
|
||||
error_status: 502,
|
||||
error: { type: "api_error" },
|
||||
session_id: "session",
|
||||
uuid: "retry",
|
||||
} as unknown as SDKMessage);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
|
||||
// Exactly one warning: the high-priority notification. Nothing else.
|
||||
assert.deepEqual(
|
||||
warnings.map((event) => event.payload.message),
|
||||
["context window nearly full"],
|
||||
);
|
||||
const sessionStates = runtimeEvents
|
||||
.filter((event) => event.type === "session.state.changed")
|
||||
.map((event) =>
|
||||
event.type === "session.state.changed"
|
||||
? `${event.payload.state}:${event.payload.reason ?? ""}`
|
||||
: "",
|
||||
)
|
||||
.filter(
|
||||
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
|
||||
);
|
||||
assert.deepEqual(sessionStates, [
|
||||
"running:session_state:running",
|
||||
"waiting:session_state:requires_action",
|
||||
"ready:session_state:idle",
|
||||
]);
|
||||
const heartbeat = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "session.state.changed" &&
|
||||
typeof event.payload.reason === "string" &&
|
||||
event.payload.reason.startsWith("api_retry:"),
|
||||
);
|
||||
assert.equal(heartbeat?.type, "session.state.changed");
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits thread token usage updates from Claude task progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -3172,7 +3045,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -3270,11 +3143,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-opus-4-6",
|
||||
[{ id: "contextWindow", value: "200k" }],
|
||||
),
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -77,7 +77,6 @@ import {
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeContextWindow,
|
||||
resolveClaudeEffort,
|
||||
} from "./ClaudeProvider.ts";
|
||||
import {
|
||||
@@ -342,18 +341,24 @@ function selectedClaudeContextWindow(
|
||||
switch (modelSelection?.model) {
|
||||
case "claude-opus-4-8":
|
||||
case "claude-opus-4-7":
|
||||
// Always 1M at the API; these models expose no contextWindow option.
|
||||
return 1_000_000;
|
||||
}
|
||||
|
||||
switch (resolveClaudeContextWindow(modelSelection)) {
|
||||
case "1m":
|
||||
return 1_000_000;
|
||||
case "200k":
|
||||
return 200_000;
|
||||
default:
|
||||
return undefined;
|
||||
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
if (optionValue === "1m") {
|
||||
return 1_000_000;
|
||||
}
|
||||
if (optionValue === "200k") {
|
||||
return 200_000;
|
||||
}
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
|
||||
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
|
||||
);
|
||||
if (hasContextWindowOption) {
|
||||
return 200_000;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function finiteNonNegativeInteger(value: unknown): number | undefined {
|
||||
@@ -2585,17 +2590,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
};
|
||||
|
||||
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
|
||||
// be switch cases): consumed intentionally without emitting, otherwise
|
||||
// they fall through to the unknown-subtype warning and surface as spurious
|
||||
// error rows in client work logs. `background_tasks_changed` is a roster
|
||||
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
|
||||
// authoritative per-agent data and the typed background_tasks control
|
||||
// request is the reconciliation source.
|
||||
if ((message.subtype as string) === "background_tasks_changed") {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.subtype) {
|
||||
case "init":
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -2708,11 +2702,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
return;
|
||||
// Task state patch (status/backgrounded/end_time). No runtime mapping
|
||||
// yet — the terminal task_notification reports the outcome — but it
|
||||
// must not surface as an unknown-subtype warning row.
|
||||
case "task_updated":
|
||||
return;
|
||||
case "task_notification":
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
@@ -2757,52 +2746,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
return;
|
||||
case "thinking_tokens":
|
||||
return;
|
||||
case "api_retry":
|
||||
// Transport-level retry heartbeat. Surfacing each attempt as a
|
||||
// warning row spammed the work log (10 rows during a 502 storm);
|
||||
// the terminal result/error path reports the actual failure. Keep
|
||||
// the session visibly alive instead.
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state: "running",
|
||||
reason: `api_retry:${message.attempt}/${message.max_retries}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "session_state_changed":
|
||||
// Authoritative turn-over signal from the CLI.
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state:
|
||||
message.state === "running"
|
||||
? "running"
|
||||
: message.state === "requires_action"
|
||||
? "waiting"
|
||||
: "ready",
|
||||
reason: `session_state:${message.state}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "notification":
|
||||
// User-facing CLI notification (e.g. context-limit warnings). Only
|
||||
// high-priority ones warrant a work-log row.
|
||||
if (message.priority === "high" || message.priority === "immediate") {
|
||||
yield* emitRuntimeWarning(context, message.text, message);
|
||||
}
|
||||
return;
|
||||
// Inner protocol/UX details with no T3 surface today — consumed
|
||||
// deliberately so they don't masquerade as unknown-subtype warnings.
|
||||
case "model_refusal_fallback":
|
||||
case "local_command_output":
|
||||
case "plugin_install":
|
||||
case "commands_changed":
|
||||
case "memory_recall":
|
||||
case "elicitation_complete":
|
||||
return;
|
||||
case "permission_denied":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2822,21 +2765,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
message,
|
||||
);
|
||||
return;
|
||||
default: {
|
||||
// Exhaustiveness guard: every subtype in the SDK's typed union is
|
||||
// handled above, so `message` narrows to never here — a new SDK
|
||||
// release adding a subtype fails this typecheck instead of silently
|
||||
// warning at runtime. The runtime fallback still catches undeclared
|
||||
// wire-only subtypes (like background_tasks_changed used to be).
|
||||
message satisfies never;
|
||||
const unknownMessage = message as never as { subtype: string };
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
|
||||
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2944,21 +2879,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
case "rate_limit_event":
|
||||
yield* handleSdkTelemetryMessage(context, message);
|
||||
return;
|
||||
// Composer prompt suggestions have no T3 surface; consumed deliberately.
|
||||
case "prompt_suggestion":
|
||||
return;
|
||||
default: {
|
||||
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
|
||||
// message types fail typecheck here instead of warning at runtime.
|
||||
message satisfies never;
|
||||
const unknownMessage = message as never as { type: string };
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
|
||||
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
|
||||
message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
@@ -214,7 +214,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
@@ -244,7 +243,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
@@ -371,22 +369,8 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
|
||||
return effort === "ultracode";
|
||||
}
|
||||
|
||||
export function resolveClaudeContextWindow(
|
||||
modelSelection: ModelSelection | undefined,
|
||||
): string | undefined {
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
caps,
|
||||
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
|
||||
});
|
||||
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
|
||||
const value = getProviderOptionCurrentValue(descriptor);
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
|
||||
switch (resolveClaudeContextWindow(modelSelection)) {
|
||||
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
@@ -102,45 +102,3 @@ it("uses standard routing when the catalog has no default service tier", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks the most preferred available model as default", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
|
||||
[
|
||||
{ slug: "gpt-5.6-terra", isDefault: true },
|
||||
{ slug: "gpt-5.4", isDefault: undefined },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers sol over terra when both are available", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
|
||||
});
|
||||
|
||||
it("keeps Codex's own default when no preferred model is available", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
|
||||
});
|
||||
|
||||
it("ignores custom models that shadow a preferred slug", () => {
|
||||
const models = applyPreferredCodexDefaultModel([
|
||||
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
|
||||
});
|
||||
@@ -22,7 +22,7 @@ import type {
|
||||
ServerProviderModel,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
@@ -189,36 +189,10 @@ function parseCodexModelListResponse(
|
||||
slug: model.model,
|
||||
name: toDisplayName(model),
|
||||
isCustom: false,
|
||||
...(model.isDefault ? { isDefault: true } : {}),
|
||||
capabilities: mapCodexModelCapabilities(model),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer our own default-model ranking when one of the preferred slugs is in
|
||||
* the live catalog; otherwise keep whatever Codex itself flagged as default.
|
||||
*/
|
||||
export function applyPreferredCodexDefaultModel(
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
|
||||
models.some((model) => model.slug === slug && !model.isCustom),
|
||||
);
|
||||
if (!preferredSlug) {
|
||||
return models;
|
||||
}
|
||||
return models.map((model) => {
|
||||
if (model.slug === preferredSlug) {
|
||||
return model.isDefault ? model : { ...model, isDefault: true };
|
||||
}
|
||||
if (!model.isDefault) {
|
||||
return model;
|
||||
}
|
||||
const { isDefault: _isDefault, ...rest } = model;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
||||
function appendCustomCodexModels(
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
customModels: ReadonlyArray<string>,
|
||||
@@ -402,9 +376,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
return {
|
||||
account: accountResponse,
|
||||
version,
|
||||
models: applyPreferredCodexDefaultModel(
|
||||
appendCustomCodexModels(models, input.customModels ?? []),
|
||||
),
|
||||
models: appendCustomCodexModels(models, input.customModels ?? []),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
@@ -4798,33 +4798,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc shell.revealInFileManager", () =>
|
||||
Effect.gen(function* () {
|
||||
let revealedPath: string | null = null;
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
externalLauncher: {
|
||||
revealInFileManager: (path) =>
|
||||
Effect.sync(() => {
|
||||
revealedPath = path;
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.shellRevealInFileManager]({
|
||||
path: "/tmp/project/src/index.ts",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(revealedPath, "/tmp/project/src/index.ts");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc git methods", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
|
||||
@@ -596,26 +596,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks the origin default ref as default when no local copy exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
|
||||
yield* git(cwd, ["branch", "-D", initialBranch]);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
|
||||
assert.equal(remoteDefault?.isRemote, true);
|
||||
assert.equal(remoteDefault?.isDefault, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates, checks out, renames, and lists refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -2217,12 +2217,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
// origin/HEAD's target is the repo default even when no local
|
||||
// copy of the default branch exists.
|
||||
isDefault:
|
||||
defaultBranch !== null &&
|
||||
parsedRemoteRef?.remoteName === "origin" &&
|
||||
parsedRemoteRef.branchName === defaultBranch,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
@@ -2237,16 +2232,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
})
|
||||
: [];
|
||||
|
||||
const combinedBranches = input.includeMatchingRemoteRefs
|
||||
const allBranches = input.includeMatchingRemoteRefs
|
||||
? [...localBranches, ...remoteBranches]
|
||||
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
|
||||
// Keep current/default refs on the first page even when the default
|
||||
// only exists as origin/<default> (remote refs sort after all locals).
|
||||
const allBranches = combinedBranches.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
return aPriority - bPriority;
|
||||
});
|
||||
const branchesForKind =
|
||||
input.refKind === "local"
|
||||
? allBranches.filter((ref) => !ref.isRemote)
|
||||
|
||||
@@ -706,6 +706,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
yield* Deferred.await(remoteStarted);
|
||||
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
|
||||
yield* Scope.close(firstScope, Exit.void);
|
||||
assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
|
||||
@@ -713,6 +714,20 @@ describe("VcsStatusBroadcaster", () => {
|
||||
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
|
||||
yield* Deferred.await(remoteInterrupted);
|
||||
assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
|
||||
|
||||
const nextSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const nextScope = yield* Scope.make();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(nextSnapshot, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(nextScope));
|
||||
yield* Deferred.await(nextSnapshot);
|
||||
|
||||
// Releasing the final poller also evicts its cwd cache entry, so a later
|
||||
// subscription reloads local status instead of retaining state forever.
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
yield* Scope.close(nextScope, Exit.void);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
@@ -476,10 +476,10 @@ export const make = Effect.gen(function* () {
|
||||
const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (!existing) {
|
||||
return [null, activePollers] as const;
|
||||
return Effect.succeed([null, activePollers] as const);
|
||||
}
|
||||
|
||||
if (existing.subscriberCount > 1) {
|
||||
@@ -488,12 +488,24 @@ export const make = Effect.gen(function* () {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount - 1,
|
||||
});
|
||||
return [null, nextPollers] as const;
|
||||
return Effect.succeed([null, nextPollers] as const);
|
||||
}
|
||||
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.delete(cwd);
|
||||
return [existing.fiber, nextPollers] as const;
|
||||
// Drop the cached status for this cwd in the same critical section that
|
||||
// removes the poller, so a concurrent retainRemotePoller (which reloads
|
||||
// the cache and installs a fresh poller) cannot have its new entry wiped
|
||||
// by this release. Otherwise the cache grows one entry per cwd for the
|
||||
// broadcaster's lifetime; a future subscriber re-loads and re-seeds it.
|
||||
return Ref.update(cacheRef, (cache) => {
|
||||
if (!cache.has(cwd)) {
|
||||
return cache;
|
||||
}
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.delete(cwd);
|
||||
return nextCache;
|
||||
}).pipe(Effect.as([existing.fiber, nextPollers] as const));
|
||||
});
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
|
||||
@@ -315,7 +315,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellRevealInFileManager, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
@@ -1676,12 +1675,6 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.shellRevealInFileManager]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.shellRevealInFileManager,
|
||||
externalLauncher.revealInFileManager(input.path),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.filesystemBrowse]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.filesystemBrowse,
|
||||
|
||||
@@ -62,17 +62,15 @@ describe("browserSurfaceStore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("hides a surface when its current lease is released", () => {
|
||||
it("removes a surface entry when its current lease is released", () => {
|
||||
const tabId = "released-browser-surface";
|
||||
const lease = acquireBrowserSurface(tabId);
|
||||
lease.present({ x: 10, y: 20, width: 900, height: 640 }, true);
|
||||
|
||||
lease.release();
|
||||
// A stale present() from the released lease must not resurrect the entry.
|
||||
lease.present({ x: 0, y: 0, width: 1, height: 1 }, true);
|
||||
|
||||
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toMatchObject({
|
||||
visible: false,
|
||||
owner: null,
|
||||
});
|
||||
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -142,12 +142,14 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
if (current?.owner !== owner) return state;
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: { ...current, visible: false, updatedAt: Date.now(), owner: null },
|
||||
},
|
||||
};
|
||||
// Delete the entry entirely instead of leaving a released tombstone
|
||||
// ({ visible: false, owner: null }). Readers only consider `visible`
|
||||
// entries, so removal is behavior-preserving, and it stops byTabId from
|
||||
// accumulating one dead entry per preview tab ever opened. A later
|
||||
// re-claim of the same tabId starts fresh, which is correct since release
|
||||
// means the surface was torn down.
|
||||
const { [tabId]: _released, ...byTabId } = state.byTabId;
|
||||
return { byTabId };
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -120,44 +119,6 @@ describe("resolveEnvironmentOptionLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowEnvironmentIndicator", () => {
|
||||
it("shows the indicator whenever multiple environments are pickable", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: true },
|
||||
canPickEnvironment: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a sole remote environment so the user knows where the project runs", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: false },
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("hides a sole primary (this-device) environment", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: { isPrimary: true },
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("hides the indicator when the active environment is unknown", () => {
|
||||
expect(
|
||||
shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: null,
|
||||
canPickEnvironment: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEffectiveEnvMode", () => {
|
||||
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
|
||||
expect(
|
||||
|
||||
@@ -42,17 +42,6 @@ export function resolveEnvironmentOptionLabel(input: {
|
||||
return runtimeLabel ?? savedLabel ?? input.environmentId;
|
||||
}
|
||||
|
||||
// A remote (non-primary) environment is always surfaced, even when it is the
|
||||
// only environment available: with a single connected machine there is nothing
|
||||
// to pick, but the user still needs to see where the project runs.
|
||||
export function shouldShowEnvironmentIndicator(input: {
|
||||
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
|
||||
canPickEnvironment: boolean;
|
||||
}): boolean {
|
||||
if (input.canPickEnvironment) return true;
|
||||
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
|
||||
}
|
||||
|
||||
export function resolveEnvModeLabel(mode: EnvMode): string {
|
||||
return mode === "worktree" ? "New worktree" : "Current checkout";
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
resolveEnvModeLabel,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldShowEnvironmentIndicator,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
|
||||
@@ -61,7 +60,6 @@ interface MobileRunContextSelectorProps {
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[] | undefined;
|
||||
showEnvironmentPicker: boolean;
|
||||
showEnvironmentIndicator: boolean;
|
||||
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
|
||||
effectiveEnvMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
@@ -74,7 +72,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
environmentId,
|
||||
availableEnvironments,
|
||||
showEnvironmentPicker,
|
||||
showEnvironmentIndicator,
|
||||
onEnvironmentChange,
|
||||
effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
@@ -97,7 +94,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
: resolveCurrentWorkspaceLabel(activeWorktreePath);
|
||||
const isLocked = envLocked || envModeLocked;
|
||||
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
|
||||
const icon = showEnvironmentIndicator ? (
|
||||
const icon = showEnvironmentPicker ? (
|
||||
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
|
||||
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5">
|
||||
@@ -111,7 +108,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
<>
|
||||
{icon}
|
||||
<span className="min-w-0 truncate">
|
||||
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
@@ -237,12 +234,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const showEnvironmentPicker = Boolean(
|
||||
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
|
||||
);
|
||||
const activeEnvironmentOption =
|
||||
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
|
||||
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
|
||||
activeEnvironment: activeEnvironmentOption,
|
||||
canPickEnvironment: showEnvironmentPicker,
|
||||
});
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
@@ -256,7 +247,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
showEnvironmentPicker={showEnvironmentPicker}
|
||||
showEnvironmentIndicator={showEnvironmentIndicator}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
@@ -264,13 +254,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
{showEnvironmentIndicator && availableEnvironments && (
|
||||
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
|
||||
<>
|
||||
<BranchToolbarEnvironmentSelector
|
||||
envLocked={envLocked}
|
||||
environmentId={environmentId}
|
||||
availableEnvironments={availableEnvironments}
|
||||
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
|
||||
onEnvironmentChange={onEnvironmentChange}
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
</>
|
||||
|
||||
@@ -422,32 +422,17 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
// Default the worktree base to the repo default branch (origin/HEAD), only
|
||||
// falling back to the checked-out branch when no default is known.
|
||||
const defaultBranchName = useMemo(
|
||||
() => refs.find((refName) => refName.isDefault)?.name ?? null,
|
||||
[refs],
|
||||
);
|
||||
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
|
||||
? null
|
||||
: (defaultBranchName ?? currentGitBranch);
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
activeWorktreePath ||
|
||||
activeThreadBranch ||
|
||||
!worktreeBaseBranchCandidate
|
||||
!currentGitBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setThreadBranch(worktreeBaseBranchCandidate, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
setThreadBranch,
|
||||
worktreeBaseBranchCandidate,
|
||||
]);
|
||||
setThreadBranch(currentGitBranch, null);
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / list plumbing
|
||||
|
||||
@@ -17,9 +17,7 @@ interface BranchToolbarEnvironmentSelectorProps {
|
||||
envLocked: boolean;
|
||||
environmentId: EnvironmentId;
|
||||
availableEnvironments: readonly EnvironmentOption[];
|
||||
// Absent when there is only one environment to show: the indicator still
|
||||
// renders (as a static label) so remote projects are always identifiable.
|
||||
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
|
||||
onEnvironmentChange: (environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
|
||||
@@ -41,7 +39,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
[availableEnvironments],
|
||||
);
|
||||
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
if (envLocked) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
|
||||
@@ -9,11 +9,7 @@ import {
|
||||
Minimize2Icon,
|
||||
WrapTextIcon,
|
||||
} from "lucide-react";
|
||||
import type {
|
||||
ExecutionEnvironmentPlatformOs,
|
||||
ScopedThreadRef,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
@@ -78,7 +74,6 @@ import { serverEnvironment } from "../state/server";
|
||||
import { assetEnvironment } from "../state/assets";
|
||||
import { usePreparedConnection } from "../state/session";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { shellEnvironment } from "../state/shell";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
@@ -748,8 +743,6 @@ interface MarkdownFileLinkProps {
|
||||
theme: "light" | "dark";
|
||||
threadRef?: ScopedThreadRef | undefined;
|
||||
onOpen: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
|
||||
onShowInFinder: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
|
||||
fileManagerLabel: string;
|
||||
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
|
||||
className?: string | undefined;
|
||||
}
|
||||
@@ -758,12 +751,6 @@ const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)
|
||||
const MARKDOWN_FILE_LINK_CLASS_NAME =
|
||||
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
|
||||
|
||||
function fileManagerLabelForPlatform(platform: ExecutionEnvironmentPlatformOs | undefined): string {
|
||||
if (platform === "darwin") return "Show in Finder";
|
||||
if (platform === "windows") return "Show in File Explorer";
|
||||
return "Show in Files";
|
||||
}
|
||||
|
||||
function pathParentSegments(path: string): string[] {
|
||||
const normalized = path.replaceAll("\\", "/");
|
||||
const segments = normalized.split("/").filter((segment) => segment.length > 0);
|
||||
@@ -1035,8 +1022,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
theme,
|
||||
threadRef,
|
||||
onOpen,
|
||||
onShowInFinder,
|
||||
fileManagerLabel,
|
||||
onOpenInBrowser,
|
||||
className,
|
||||
}: MarkdownFileLinkProps) {
|
||||
@@ -1083,38 +1068,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line);
|
||||
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
|
||||
|
||||
const handleShowInFinder = useCallback(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await onShowInFinder(iconPath);
|
||||
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
reportMarkdownActionFailure(
|
||||
{ operation: "show-file-in-finder", target: iconPath },
|
||||
result.cause,
|
||||
);
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Unable to ${fileManagerLabel.toLowerCase()}`,
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
reportMarkdownActionFailure({ operation: "show-file-in-finder", target: iconPath }, cause);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Unable to ${fileManagerLabel.toLowerCase()}`,
|
||||
description: cause instanceof Error ? cause.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
}, [fileManagerLabel, iconPath, onShowInFinder]);
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
if (!onOpenInBrowser) {
|
||||
return;
|
||||
@@ -1209,10 +1162,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
: []),
|
||||
{ id: "copy-relative", label: "Copy relative path" },
|
||||
{ id: "copy-full", label: "Copy full path" },
|
||||
{
|
||||
id: "show-in-finder",
|
||||
label: fileManagerLabel,
|
||||
},
|
||||
] as const,
|
||||
{ x: event.clientX, y: event.clientY },
|
||||
);
|
||||
@@ -1231,10 +1180,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
}
|
||||
if (clicked === "copy-full") {
|
||||
handleCopy(targetPath, "Full path");
|
||||
return;
|
||||
}
|
||||
if (clicked === "show-in-finder") {
|
||||
handleShowInFinder();
|
||||
}
|
||||
} catch (cause) {
|
||||
reportMarkdownActionFailure(
|
||||
@@ -1243,16 +1188,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
);
|
||||
}
|
||||
},
|
||||
[
|
||||
displayPath,
|
||||
handleCopy,
|
||||
handleOpenInBrowser,
|
||||
handleOpenInEditor,
|
||||
handleShowInFinder,
|
||||
fileManagerLabel,
|
||||
onOpenInBrowser,
|
||||
targetPath,
|
||||
],
|
||||
[displayPath, handleCopy, handleOpenInBrowser, handleOpenInEditor, onOpenInBrowser, targetPath],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -1306,8 +1242,6 @@ function areMarkdownFileLinkPropsEqual(
|
||||
previous.theme === next.theme &&
|
||||
previous.threadRef === next.threadRef &&
|
||||
previous.onOpen === next.onOpen &&
|
||||
previous.onShowInFinder === next.onShowInFinder &&
|
||||
previous.fileManagerLabel === next.fileManagerLabel &&
|
||||
previous.onOpenInBrowser === next.onOpenInBrowser &&
|
||||
previous.className === next.className
|
||||
);
|
||||
@@ -1330,34 +1264,13 @@ function ChatMarkdown({
|
||||
const openPreview = useAtomCommand(previewEnvironment.open, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const revealInFileManager = useAtomCommand(shellEnvironment.revealInFileManager, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null);
|
||||
const environmentId = useActiveEnvironmentId();
|
||||
const fileEnvironmentId = threadRef?.environmentId ?? environmentId;
|
||||
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(fileEnvironmentId));
|
||||
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
|
||||
const openInPreferredEditor = useOpenInPreferredEditor(
|
||||
fileEnvironmentId,
|
||||
environmentId,
|
||||
serverConfig?.availableEditors ?? [],
|
||||
);
|
||||
const showFileInFinder = useCallback(
|
||||
(targetPath: string) => {
|
||||
if (fileEnvironmentId === null) {
|
||||
return Promise.resolve(
|
||||
AsyncResult.failure<void, Error>(
|
||||
Cause.fail(new Error("Cannot show the file because no environment is selected.")),
|
||||
),
|
||||
);
|
||||
}
|
||||
return revealInFileManager({
|
||||
environmentId: fileEnvironmentId,
|
||||
input: { path: targetPath },
|
||||
});
|
||||
},
|
||||
[fileEnvironmentId, revealInFileManager],
|
||||
);
|
||||
const fileManagerLabel = fileManagerLabelForPlatform(serverConfig?.environment.platform.os);
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownFileLinkMetaByHref = useMemo(() => {
|
||||
const metaByHref = new Map<
|
||||
@@ -1579,8 +1492,6 @@ function ChatMarkdown({
|
||||
theme={resolvedTheme}
|
||||
threadRef={threadRef}
|
||||
onOpen={openInPreferredEditor}
|
||||
onShowInFinder={showFileInFinder}
|
||||
fileManagerLabel={fileManagerLabel}
|
||||
onOpenInBrowser={
|
||||
threadRef &&
|
||||
isPreviewSupportedInRuntime() &&
|
||||
@@ -1636,9 +1547,7 @@ function ChatMarkdown({
|
||||
openInPreferredEditor,
|
||||
openExternalLinkInPreview,
|
||||
openMarkdownFileInPreview,
|
||||
fileManagerLabel,
|
||||
resolvedTheme,
|
||||
showFileInFinder,
|
||||
skills,
|
||||
text,
|
||||
threadRef,
|
||||
|
||||
@@ -1159,7 +1159,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
projectSelectionRequired ||
|
||||
environmentUnavailable !== null ||
|
||||
!composerSendState.hasSendableContent;
|
||||
const collapsedComposerPrimaryActionLabel = "Send message";
|
||||
const showMobilePendingAnswerActions =
|
||||
@@ -1698,9 +1697,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
|
||||
if (!isMobileViewport) return false;
|
||||
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
|
||||
return false;
|
||||
}
|
||||
if (isSendBusy || isConnecting || phase === "running") return false;
|
||||
if (activePendingProgress) {
|
||||
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
|
||||
}
|
||||
@@ -1709,7 +1706,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
activePendingProgress,
|
||||
activePendingResolvedAnswers,
|
||||
composerSendState.hasSendableContent,
|
||||
environmentUnavailable,
|
||||
isConnecting,
|
||||
isMobileViewport,
|
||||
isSendBusy,
|
||||
@@ -1896,7 +1892,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
pendingUserInputs.length > 0 ||
|
||||
projectSelectionRequired
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -2104,6 +2101,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isComposerApprovalState,
|
||||
pendingUserInputs.length,
|
||||
projectSelectionRequired,
|
||||
environmentUnavailable,
|
||||
activePendingProgress,
|
||||
applyPromptReplacement,
|
||||
isComposerModelPickerOpen,
|
||||
readComposerSnapshot,
|
||||
@@ -2145,7 +2144,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
className={cn(
|
||||
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
projectSelectionRequired ? "opacity-75" : null,
|
||||
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
onFocusCapture={(event) => {
|
||||
@@ -2503,7 +2502,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
|
||||
disabled={
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
projectSelectionRequired ||
|
||||
(environmentUnavailable !== null && activePendingProgress === null)
|
||||
}
|
||||
/>
|
||||
{showMobilePendingAnswerActions ? (
|
||||
<div
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
@@ -13,6 +14,10 @@ import { useCallback, useMemo, useRef } from "react";
|
||||
|
||||
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useDiffPanelStore } from "../diffPanelStore";
|
||||
import { removePreviewThread } from "../previewStateStore";
|
||||
import { useRightPanelStore } from "../rightPanelStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { terminalEnvironment } from "../state/terminal";
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
@@ -39,6 +44,23 @@ export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArc
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune per-thread client state that would otherwise accumulate forever.
|
||||
*
|
||||
* These stores keep a per-thread entry (preview atom, right-panel surfaces,
|
||||
* diff-panel selection) that is persisted to localStorage and was never cleaned
|
||||
* up on thread deletion/archival — a long-lived tab leaked one entry per thread
|
||||
* ever visited. The cleanup functions already existed but had no callers; this
|
||||
* wires them into the deletion/archival flow.
|
||||
*/
|
||||
function clearPerThreadClientState(ref: ScopedThreadRef): void {
|
||||
removePreviewThread(ref);
|
||||
useRightPanelStore.getState().removeThread(ref);
|
||||
useDiffPanelStore.getState().removeThread(ref);
|
||||
// uiStateStore is keyed by the scoped thread key (see ChatView.markThreadVisited).
|
||||
useUiStateStore.getState().removeThread(scopedThreadKey(ref));
|
||||
}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
|
||||
@@ -158,6 +180,9 @@ export function useThreadActions() {
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
refreshArchivedThreadsForEnvironment(target.environmentId);
|
||||
clearComposerDraftForThread(target);
|
||||
clearTerminalUiState(target);
|
||||
clearPerThreadClientState(target);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -247,6 +272,7 @@ export function useThreadActions() {
|
||||
threadRef,
|
||||
);
|
||||
clearTerminalUiState(threadRef);
|
||||
clearPerThreadClientState(threadRef);
|
||||
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
|
||||
@@ -75,7 +75,6 @@ export interface AppModelOption {
|
||||
shortName?: string;
|
||||
subProvider?: string;
|
||||
isCustom: boolean;
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
|
||||
@@ -86,7 +85,6 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
|
||||
};
|
||||
if (model.shortName) option.shortName = model.shortName;
|
||||
if (model.subProvider) option.subProvider = model.subProvider;
|
||||
if (model.isDefault) option.isDefault = true;
|
||||
return option;
|
||||
}
|
||||
|
||||
@@ -249,9 +247,7 @@ export function resolveAppModelSelectionForInstance(
|
||||
const options = getAppModelOptionsForInstance(settings, entry);
|
||||
return (
|
||||
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
|
||||
options.find((option) => option.isDefault)?.slug ??
|
||||
options[0]?.slug ??
|
||||
entry.models.find((model) => model.isDefault)?.slug ??
|
||||
entry.models[0]?.slug ??
|
||||
null
|
||||
);
|
||||
|
||||
@@ -50,9 +50,20 @@ const emptyPreviewStateAtom = Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW
|
||||
Atom.withLabel("preview:empty-thread"),
|
||||
);
|
||||
|
||||
// Previously `Atom.keepAlive`, which pinned one atom node per thread key ever
|
||||
// visited in the registry for the process lifetime — an unbounded leak in a
|
||||
// long-lived tab. Idle-TTL lets the registry evict a thread's preview atom once
|
||||
// nothing observes it, matching the pattern used for other per-resource atom
|
||||
// families (see browser/previewWebviewConfigState.ts). Threads with live
|
||||
// preview sessions stay resident because the observed aggregate
|
||||
// `activePreviewSessionsAtom` reads them, keeping them out of the idle state;
|
||||
// only closed/idle threads are collected. An evicted idle thread re-seeds from
|
||||
// EMPTY and is re-populated by the next server snapshot, so eviction is safe.
|
||||
const PREVIEW_STATE_IDLE_TTL_MS = 5 * 60_000;
|
||||
|
||||
export const previewStateAtom = Atom.family((threadKey: string) =>
|
||||
Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.setIdleTTL(PREVIEW_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`preview:thread:${threadKey}`),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -92,7 +92,6 @@ export function getDefaultServerModel(
|
||||
): string {
|
||||
const models = getProviderModels(providers, provider);
|
||||
return (
|
||||
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
|
||||
models.find((model) => !model.isCustom)?.slug ??
|
||||
models[0]?.slug ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[provider] ??
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
PERSISTED_STATE_KEY,
|
||||
type PersistedUiState,
|
||||
persistState,
|
||||
removeThreadUiState,
|
||||
reorderProjects,
|
||||
resolveProjectExpanded,
|
||||
setDefaultAdvertisedEndpointKey,
|
||||
@@ -39,6 +40,27 @@ describe("uiStateStore pure functions", () => {
|
||||
expect(markThreadVisited(visited, threadId, "not-a-date")).toBe(visited);
|
||||
});
|
||||
|
||||
it("removes all per-thread ui state for a deleted thread", () => {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const otherId = ThreadId.make("thread-2");
|
||||
const state = makeUiState({
|
||||
threadLastVisitedAtById: {
|
||||
[threadId]: "2026-02-25T12:30:00.000Z",
|
||||
[otherId]: "2026-02-25T12:31:00.000Z",
|
||||
},
|
||||
threadChangedFilesExpandedById: {
|
||||
[threadId]: { "turn-1": false },
|
||||
[otherId]: { "turn-1": false },
|
||||
},
|
||||
});
|
||||
|
||||
const next = removeThreadUiState(state, threadId);
|
||||
expect(next.threadLastVisitedAtById).toEqual({ [otherId]: "2026-02-25T12:31:00.000Z" });
|
||||
expect(next.threadChangedFilesExpandedById).toEqual({ [otherId]: { "turn-1": false } });
|
||||
// No-op (same reference) when the thread has no state.
|
||||
expect(removeThreadUiState(next, threadId)).toBe(next);
|
||||
});
|
||||
|
||||
it("marks a completed thread unread using the server completion timestamp", () => {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const initialState = makeUiState({
|
||||
|
||||
@@ -274,6 +274,27 @@ export function markThreadUnread(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop all per-thread UI state for a deleted thread. Without this, both
|
||||
* `threadLastVisitedAtById` and `threadChangedFilesExpandedById` grew one entry
|
||||
* per thread ever visited and were persisted to localStorage indefinitely.
|
||||
*/
|
||||
export function removeThreadUiState(state: UiState, threadId: string): UiState {
|
||||
const hasVisited = threadId in state.threadLastVisitedAtById;
|
||||
const hasChangedFiles = threadId in state.threadChangedFilesExpandedById;
|
||||
if (!hasVisited && !hasChangedFiles) {
|
||||
return state;
|
||||
}
|
||||
const { [threadId]: _visited, ...threadLastVisitedAtById } = state.threadLastVisitedAtById;
|
||||
const { [threadId]: _changed, ...threadChangedFilesExpandedById } =
|
||||
state.threadChangedFilesExpandedById;
|
||||
return {
|
||||
...state,
|
||||
threadLastVisitedAtById,
|
||||
threadChangedFilesExpandedById,
|
||||
};
|
||||
}
|
||||
|
||||
export function setThreadChangedFilesExpanded(
|
||||
state: UiState,
|
||||
threadId: string,
|
||||
@@ -414,6 +435,7 @@ export function reorderProjects(
|
||||
interface UiStateStore extends UiState {
|
||||
markThreadVisited: (threadId: string, visitedAt: string) => void;
|
||||
markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;
|
||||
removeThread: (threadId: string) => void;
|
||||
setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;
|
||||
setDefaultAdvertisedEndpointKey: (key: string | null) => void;
|
||||
setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void;
|
||||
@@ -430,6 +452,7 @@ export const useUiStateStore = create<UiStateStore>((set) => ({
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId, latestTurnCompletedAt) =>
|
||||
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
|
||||
removeThread: (threadId) => set((state) => removeThreadUiState(state, threadId)),
|
||||
setThreadChangedFilesExpanded: (threadId, turnId, expanded) =>
|
||||
set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),
|
||||
setDefaultAdvertisedEndpointKey: (key) =>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
CommandId,
|
||||
@@ -140,7 +139,7 @@ describe("add project shared logic", () => {
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: {
|
||||
instanceId: "codex",
|
||||
model: DEFAULT_MODEL,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,9 +12,5 @@ export function createShellEnvironmentAtoms<R, E>(
|
||||
label: "environment-data:shell:open-in-editor",
|
||||
tag: WS_METHODS.shellOpenInEditor,
|
||||
}),
|
||||
revealInFileManager: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:shell:reveal-in-file-manager",
|
||||
tag: WS_METHODS.shellRevealInFileManager,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -50,11 +50,6 @@ export const LaunchEditorInput = Schema.Struct({
|
||||
});
|
||||
export type LaunchEditorInput = typeof LaunchEditorInput.Type;
|
||||
|
||||
export const RevealPathInput = Schema.Struct({
|
||||
path: TrimmedNonEmptyString,
|
||||
});
|
||||
export type RevealPathInput = typeof RevealPathInput.Type;
|
||||
|
||||
export class ExternalLauncherUnknownEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnknownEditorError>()(
|
||||
"ExternalLauncherUnknownEditorError",
|
||||
{
|
||||
|
||||
@@ -133,18 +133,8 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.6-sol";
|
||||
|
||||
/**
|
||||
* Codex default-model preference, most preferred first. The provider snapshot
|
||||
* marks the first of these present in the live `model/list` response as
|
||||
* default; when none are available, Codex's own `isDefault` flag wins.
|
||||
*/
|
||||
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
];
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
export const DEFAULT_MODEL = "gpt-5.4";
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Rpc from "effect/unstable/rpc/Rpc";
|
||||
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
|
||||
|
||||
import { ExternalLauncherError, LaunchEditorInput, RevealPathInput } from "./editor.ts";
|
||||
import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";
|
||||
import {
|
||||
AuthAccessStreamError,
|
||||
AuthAccessStreamEvent,
|
||||
@@ -156,7 +156,6 @@ export const WS_METHODS = {
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
shellRevealInFileManager: "shell.revealInFileManager",
|
||||
|
||||
// Filesystem methods
|
||||
filesystemBrowse: "filesystem.browse",
|
||||
@@ -391,11 +390,6 @@ export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
|
||||
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsShellRevealInFileManagerRpc = Rpc.make(WS_METHODS.shellRevealInFileManager, {
|
||||
payload: RevealPathInput,
|
||||
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
|
||||
payload: FilesystemBrowseInput,
|
||||
success: FilesystemBrowseResult,
|
||||
@@ -718,7 +712,6 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
WsShellRevealInFileManagerRpc,
|
||||
WsFilesystemBrowseRpc,
|
||||
WsAssetsCreateUrlRpc,
|
||||
WsSubscribeVcsStatusRpc,
|
||||
|
||||
@@ -64,7 +64,6 @@ export const ServerProviderModel = Schema.Struct({
|
||||
shortName: Schema.optional(TrimmedNonEmptyString),
|
||||
subProvider: Schema.optional(TrimmedNonEmptyString),
|
||||
isCustom: Schema.Boolean,
|
||||
isDefault: Schema.optional(Schema.Boolean),
|
||||
capabilities: Schema.NullOr(ModelCapabilities),
|
||||
});
|
||||
export type ServerProviderModel = typeof ServerProviderModel.Type;
|
||||
|
||||
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
|
||||
});
|
||||
|
||||
describe("ServerSettings worktree defaults", () => {
|
||||
it("defaults start-from-origin on for legacy configs", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
|
||||
it("defaults start-from-origin off for legacy configs", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts start-from-origin updates", () => {
|
||||
expect(
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
|
||||
).toBe(false);
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
|
||||
),
|
||||
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
Schema.withDecodingDefault(Effect.succeed(false)),
|
||||
),
|
||||
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
textGenerationModelSelection: ModelSelection.pipe(
|
||||
|
||||
Reference in new issue
Block a user