Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5014079144 |
No files matched your search
@@ -1,4 +1,9 @@
|
||||
import type { OrchestrationEvent, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { OrchestrationCommand } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -8,7 +13,6 @@ 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";
|
||||
@@ -33,13 +37,8 @@ import {
|
||||
type OrchestrationDispatchError,
|
||||
type OrchestrationProjectorDecodeError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
createEmptyCommandReadModel,
|
||||
fromWireReadModel,
|
||||
type CommandReadModel,
|
||||
} from "../commandReadModel.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { projectEvent } from "../projector.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -86,15 +85,15 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
let commandReadModel: CommandReadModel = createEmptyCommandReadModel(yield* nowIso);
|
||||
let commandReadModel = createEmptyReadModel(yield* nowIso);
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const projectEventsOntoReadModel = (
|
||||
baseReadModel: CommandReadModel,
|
||||
baseReadModel: OrchestrationReadModel,
|
||||
events: ReadonlyArray<OrchestrationEvent>,
|
||||
): Effect.Effect<CommandReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
Effect.gen(function* () {
|
||||
let nextReadModel = baseReadModel;
|
||||
for (const event of events) {
|
||||
@@ -299,21 +298,12 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
// 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,
|
||||
});
|
||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
|
||||
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,
|
||||
threadCount: HashMap.size(commandReadModel.threads),
|
||||
projectCount: HashMap.size(commandReadModel.projects),
|
||||
}),
|
||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { fromWireReadModel } from "./commandReadModel.ts";
|
||||
import {
|
||||
findThreadById,
|
||||
listThreadsByProjectId,
|
||||
@@ -22,7 +21,7 @@ import {
|
||||
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const wireReadModel: OrchestrationReadModel = {
|
||||
const readModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 2,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
@@ -103,8 +102,6 @@ const wireReadModel: OrchestrationReadModel = {
|
||||
],
|
||||
};
|
||||
|
||||
const readModel = fromWireReadModel(wireReadModel, { dropDeletedThreads: false });
|
||||
|
||||
const messageSendCommand: OrchestrationCommand = {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
|
||||
@@ -1,25 +1,16 @@
|
||||
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,
|
||||
@@ -27,8 +18,29 @@ 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: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly projectId: ProjectId;
|
||||
}): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {
|
||||
@@ -45,7 +57,7 @@ export function requireProject(input: {
|
||||
}
|
||||
|
||||
export function requireProjectAbsent(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly projectId: ProjectId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
@@ -61,23 +73,18 @@ export function requireProjectAbsent(input: {
|
||||
}
|
||||
|
||||
export function requireActiveProjectWorkspaceRootAbsent(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly workspaceRoot: string;
|
||||
readonly exceptProjectId?: ProjectId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
|
||||
let existingProject: OrchestrationProject | undefined;
|
||||
for (const project of HashMap.values(input.readModel.projects)) {
|
||||
if (
|
||||
const existingProject = input.readModel.projects.find(
|
||||
(project) =>
|
||||
project.deletedAt === null &&
|
||||
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
|
||||
project.id !== input.exceptProjectId
|
||||
) {
|
||||
existingProject = project;
|
||||
break;
|
||||
}
|
||||
}
|
||||
project.id !== input.exceptProjectId,
|
||||
);
|
||||
if (existingProject === undefined) {
|
||||
return Effect.void;
|
||||
}
|
||||
@@ -90,7 +97,7 @@ export function requireActiveProjectWorkspaceRootAbsent(input: {
|
||||
}
|
||||
|
||||
export function requireThread(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -107,7 +114,7 @@ export function requireThread(input: {
|
||||
}
|
||||
|
||||
export function requireThreadArchived(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -126,7 +133,7 @@ export function requireThreadArchived(input: {
|
||||
}
|
||||
|
||||
export function requireThreadNotArchived(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
@@ -145,16 +152,11 @@ export function requireThreadNotArchived(input: {
|
||||
}
|
||||
|
||||
export function requireThreadAbsent(input: {
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
// 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)
|
||||
) {
|
||||
if (!findThreadById(input.readModel, input.threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.fail(
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
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"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
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,7 +2,6 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
@@ -10,7 +9,6 @@ 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";
|
||||
|
||||
@@ -216,134 +214,4 @@ 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,10 +1,14 @@
|
||||
import { EventId, type OrchestrationCommand, type OrchestrationEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} 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,
|
||||
@@ -61,7 +65,7 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
readModel,
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
@@ -95,7 +99,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
readModel,
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: CommandReadModel;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
DecideOrchestrationCommandResult,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
|
||||
@@ -5,25 +5,12 @@ 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"];
|
||||
@@ -85,7 +72,7 @@ describe("orchestration projector", () => {
|
||||
);
|
||||
|
||||
expect(next.snapshotSequence).toBe(1);
|
||||
expect(threadsArray(next)).toEqual([
|
||||
expect(next.threads).toEqual([
|
||||
{
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
@@ -196,7 +183,7 @@ describe("orchestration projector", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(firstThread(archived)?.archivedAt).toBe(later);
|
||||
expect(archived.threads[0]?.archivedAt).toBe(later);
|
||||
|
||||
const unarchived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
@@ -215,7 +202,7 @@ describe("orchestration projector", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(firstThread(unarchived)?.archivedAt).toBeNull();
|
||||
expect(unarchived.threads[0]?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
@@ -244,7 +231,7 @@ describe("orchestration projector", () => {
|
||||
|
||||
expect(next.snapshotSequence).toBe(7);
|
||||
expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
|
||||
expect(threadsArray(next)).toEqual([]);
|
||||
expect(next.threads).toEqual([]);
|
||||
});
|
||||
|
||||
it("tracks latest turn id from session lifecycle events", async () => {
|
||||
@@ -340,13 +327,13 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const thread = firstThread(afterRunning);
|
||||
const thread = afterRunning.threads[0];
|
||||
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 = firstThread(afterReady);
|
||||
const settledThread = afterReady.threads[0];
|
||||
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(settledThread?.latestTurn?.state).toBe("completed");
|
||||
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
|
||||
@@ -404,8 +391,8 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
expect(firstThread(afterUpdate)?.runtimeMode).toBe("approval-required");
|
||||
expect(firstThread(afterUpdate)?.updatedAt).toBe(updatedAt);
|
||||
expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
|
||||
expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
|
||||
});
|
||||
|
||||
it("marks assistant messages completed with non-streaming updates", async () => {
|
||||
@@ -490,7 +477,7 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const message = firstThread(afterComplete)?.messages[0];
|
||||
const message = afterComplete.threads[0]?.messages[0];
|
||||
expect(message?.id).toBe("assistant:msg-1");
|
||||
expect(message?.text).toBe("hello");
|
||||
expect(message?.streaming).toBe(false);
|
||||
@@ -698,7 +685,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = firstThread(afterRevert);
|
||||
const thread = afterRevert.threads[0];
|
||||
expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
|
||||
[
|
||||
{ role: "user", text: "First edit" },
|
||||
@@ -855,7 +842,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = firstThread(afterRevert);
|
||||
const thread = afterRevert.threads[0];
|
||||
expect(
|
||||
thread?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
@@ -957,7 +944,7 @@ describe("orchestration projector", () => {
|
||||
Promise.resolve(afterMessages),
|
||||
);
|
||||
|
||||
const thread = firstThread(finalState);
|
||||
const thread = finalState.threads[0];
|
||||
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, OrchestrationProject, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationMessage,
|
||||
@@ -6,16 +6,8 @@ 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,
|
||||
@@ -69,40 +61,12 @@ 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: HashMap.HashMap<ThreadId, OrchestrationThread>,
|
||||
threads: ReadonlyArray<OrchestrationThread>,
|
||||
threadId: ThreadId,
|
||||
patch: ThreadPatch,
|
||||
): 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)),
|
||||
};
|
||||
): OrchestrationThread[] {
|
||||
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
|
||||
}
|
||||
|
||||
function decodeForEvent<A>(
|
||||
@@ -214,15 +178,20 @@ function compareThreadActivities(
|
||||
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
export function createEmptyReadModel(nowIso: string): CommandReadModel {
|
||||
return createEmptyCommandReadModel(nowIso);
|
||||
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: nowIso,
|
||||
};
|
||||
}
|
||||
|
||||
export function projectEvent(
|
||||
model: CommandReadModel,
|
||||
model: OrchestrationReadModel,
|
||||
event: OrchestrationEvent,
|
||||
): Effect.Effect<CommandReadModel, OrchestrationProjectorDecodeError> {
|
||||
const nextBase: CommandReadModel = {
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {
|
||||
const nextBase: OrchestrationReadModel = {
|
||||
...model,
|
||||
snapshotSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
@@ -232,7 +201,8 @@ export function projectEvent(
|
||||
case "project.created":
|
||||
return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => {
|
||||
const nextProject: OrchestrationProject = {
|
||||
const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);
|
||||
const nextProject = {
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
@@ -245,38 +215,52 @@ export function projectEvent(
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
projects: HashMap.set(nextBase.projects, payload.projectId, nextProject),
|
||||
projects: existing
|
||||
? nextBase.projects.map((entry) =>
|
||||
entry.id === payload.projectId ? nextProject : entry,
|
||||
)
|
||||
: [...nextBase.projects, nextProject],
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
case "project.meta-updated":
|
||||
return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
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,
|
||||
})),
|
||||
),
|
||||
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,
|
||||
),
|
||||
})),
|
||||
);
|
||||
|
||||
case "project.deleted":
|
||||
return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) =>
|
||||
updateProject(nextBase, payload.projectId, (project) => ({
|
||||
...project,
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
})),
|
||||
),
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
projects: nextBase.projects.map((project) =>
|
||||
project.id === payload.projectId
|
||||
? {
|
||||
...project,
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
}
|
||||
: project,
|
||||
),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.created":
|
||||
@@ -311,27 +295,23 @@ export function projectEvent(
|
||||
event.type,
|
||||
"thread",
|
||||
);
|
||||
const existing = nextBase.threads.find((entry) => entry.id === thread.id);
|
||||
return {
|
||||
...nextBase,
|
||||
threads: HashMap.set(nextBase.threads, thread.id, thread),
|
||||
threads: existing
|
||||
? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
|
||||
: [...nextBase.threads, 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: HashMap.remove(nextBase.threads, payload.threadId),
|
||||
deletedThreadIds: HashSet.add(nextBase.deletedThreadIds, payload.threadId),
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
deletedAt: payload.deletedAt,
|
||||
updatedAt: payload.deletedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -408,7 +388,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -469,7 +449,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -532,7 +512,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -564,7 +544,7 @@ export function projectEvent(
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -634,7 +614,7 @@ export function projectEvent(
|
||||
case "thread.reverted":
|
||||
return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
@@ -690,7 +670,7 @@ export function projectEvent(
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = findThreadById(nextBase, payload.threadId);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
@@ -706,7 +706,6 @@ 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)));
|
||||
@@ -714,20 +713,6 @@ 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.modifyEffect(pollersRef, (activePollers) => {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (!existing) {
|
||||
return Effect.succeed([null, activePollers] as const);
|
||||
return [null, activePollers] as const;
|
||||
}
|
||||
|
||||
if (existing.subscriberCount > 1) {
|
||||
@@ -488,24 +488,12 @@ export const make = Effect.gen(function* () {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount - 1,
|
||||
});
|
||||
return Effect.succeed([null, nextPollers] as const);
|
||||
return [null, nextPollers] as const;
|
||||
}
|
||||
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.delete(cwd);
|
||||
// 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));
|
||||
return [existing.fiber, nextPollers] as const;
|
||||
});
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
|
||||
@@ -62,15 +62,17 @@ describe("browserSurfaceStore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("removes a surface entry when its current lease is released", () => {
|
||||
it("hides a surface 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]).toBeUndefined();
|
||||
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toMatchObject({
|
||||
visible: false,
|
||||
owner: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -142,14 +142,12 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
if (current?.owner !== owner) return state;
|
||||
// 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 };
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: { ...current, visible: false, updatedAt: Date.now(), owner: null },
|
||||
},
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationLatestTurnState,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
transitionCompletedThreadUnreadState,
|
||||
type CompletedThreadUnreadEnvironment,
|
||||
type CompletedThreadUnreadState,
|
||||
} from "./useMarkLiveCompletedThreadsUnread";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
const COMPLETED_AT = "2026-06-17T18:30:00.000Z";
|
||||
|
||||
function makeThread(input: {
|
||||
readonly id: string;
|
||||
readonly state?: OrchestrationLatestTurnState;
|
||||
readonly completedAt?: string | null;
|
||||
readonly updatedAt?: string;
|
||||
readonly archivedAt?: string | null;
|
||||
}): OrchestrationThreadShell {
|
||||
const threadId = ThreadId.make(input.id);
|
||||
const state = input.state ?? "completed";
|
||||
return {
|
||||
id: threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: input.id,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.6-sol",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${input.id}`),
|
||||
state,
|
||||
requestedAt: "2026-06-17T18:00:00.000Z",
|
||||
startedAt: "2026-06-17T18:00:01.000Z",
|
||||
completedAt: input.completedAt === undefined ? COMPLETED_AT : input.completedAt,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-06-17T18:00:00.000Z",
|
||||
updatedAt: input.updatedAt ?? COMPLETED_AT,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
session: null,
|
||||
latestUserMessageAt: "2026-06-17T18:00:00.000Z",
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
}
|
||||
|
||||
function environment(
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
isLive = true,
|
||||
): CompletedThreadUnreadEnvironment {
|
||||
return { environmentId: ENVIRONMENT_ID, isLive, threads };
|
||||
}
|
||||
|
||||
function bootstrap(threads: ReadonlyArray<OrchestrationThreadShell> = []) {
|
||||
return transitionCompletedThreadUnreadState(new Map(), [environment(threads)]);
|
||||
}
|
||||
|
||||
describe("transitionCompletedThreadUnreadState", () => {
|
||||
it("keeps completed threads in the initial historical snapshot read", () => {
|
||||
const historical = makeThread({ id: "historical" });
|
||||
|
||||
const transition = bootstrap([historical]);
|
||||
|
||||
expect(transition.actions).toEqual([]);
|
||||
expect(transition.state.get(ENVIRONMENT_ID)?.get(historical.id)).toBe(COMPLETED_AT);
|
||||
});
|
||||
|
||||
it("marks a first-seen live completed thread unread when updatedAt equals completedAt", () => {
|
||||
const initial = bootstrap();
|
||||
const completed = makeThread({ id: "live-equal" });
|
||||
|
||||
const transition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
|
||||
expect(transition.actions).toEqual([
|
||||
{ environmentId: ENVIRONMENT_ID, threadId: completed.id, completedAt: COMPLETED_AT },
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks a first-seen live completed thread unread when updatedAt is after completedAt", () => {
|
||||
const initial = bootstrap();
|
||||
const completed = makeThread({
|
||||
id: "live-later",
|
||||
updatedAt: "2026-06-17T18:31:00.000Z",
|
||||
});
|
||||
|
||||
const transition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
|
||||
expect(transition.actions).toEqual([
|
||||
{ environmentId: ENVIRONMENT_ID, threadId: completed.id, completedAt: COMPLETED_AT },
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks a completed thread introduced by a post-bootstrap snapshot unread", () => {
|
||||
const historical = makeThread({ id: "historical" });
|
||||
const initial = bootstrap([historical]);
|
||||
const added = makeThread({ id: "snapshot-addition" });
|
||||
|
||||
const transition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([historical, added]),
|
||||
]);
|
||||
|
||||
expect(transition.actions).toEqual([
|
||||
{ environmentId: ENVIRONMENT_ID, threadId: added.id, completedAt: COMPLETED_AT },
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks a previously running background thread when it completes", () => {
|
||||
const running = makeThread({ id: "background", state: "running", completedAt: null });
|
||||
const initial = bootstrap([running]);
|
||||
const completed = makeThread({ id: "background" });
|
||||
|
||||
const transition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
|
||||
expect(transition.actions).toEqual([
|
||||
{ environmentId: ENVIRONMENT_ID, threadId: completed.id, completedAt: COMPLETED_AT },
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves observations across reconnect snapshots without repeating unread actions", () => {
|
||||
const completed = makeThread({ id: "completed" });
|
||||
const initial = bootstrap([completed]);
|
||||
|
||||
const synchronizing = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([], false),
|
||||
]);
|
||||
const reconnected = transitionCompletedThreadUnreadState(synchronizing.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
|
||||
expect(synchronizing.actions).toEqual([]);
|
||||
expect(synchronizing.state).toEqual(initial.state);
|
||||
expect(reconnected.actions).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not repeat an unread action after reconnecting", () => {
|
||||
const initial = bootstrap();
|
||||
const completed = makeThread({ id: "completed" });
|
||||
const firstSeen = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
const synchronizing = transitionCompletedThreadUnreadState(firstSeen.state, [
|
||||
environment([completed], false),
|
||||
]);
|
||||
const reconnected = transitionCompletedThreadUnreadState(synchronizing.state, [
|
||||
environment([completed]),
|
||||
]);
|
||||
|
||||
expect(firstSeen.actions).toHaveLength(1);
|
||||
expect(reconnected.actions).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for a completion-consistent updatedAt before marking unread", () => {
|
||||
const initial = bootstrap();
|
||||
const stale = makeThread({
|
||||
id: "stale",
|
||||
updatedAt: "2026-06-17T18:29:59.000Z",
|
||||
});
|
||||
const staleTransition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([stale]),
|
||||
]);
|
||||
const consistent = makeThread({ id: "stale" });
|
||||
const consistentTransition = transitionCompletedThreadUnreadState(staleTransition.state, [
|
||||
environment([consistent]),
|
||||
]);
|
||||
|
||||
expect(staleTransition.actions).toEqual([]);
|
||||
expect(consistentTransition.actions).toEqual([
|
||||
{ environmentId: ENVIRONMENT_ID, threadId: consistent.id, completedAt: COMPLETED_AT },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not mark interrupted or error turns as completed", () => {
|
||||
const initial = bootstrap();
|
||||
const interrupted = makeThread({ id: "interrupted", state: "interrupted" });
|
||||
const failed = makeThread({ id: "failed", state: "error" });
|
||||
|
||||
const transition = transitionCompletedThreadUnreadState(initial.state, [
|
||||
environment([interrupted, failed]),
|
||||
]);
|
||||
|
||||
expect(transition.actions).toEqual([]);
|
||||
expect(transition.state.get(ENVIRONMENT_ID)).toEqual(
|
||||
new Map([
|
||||
[interrupted.id, null],
|
||||
[failed.id, null],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("treats a removed and re-added environment as a fresh historical bootstrap", () => {
|
||||
const historical = makeThread({ id: "historical" });
|
||||
const initial = bootstrap([historical]);
|
||||
const removed = transitionCompletedThreadUnreadState(initial.state, []);
|
||||
const readded = transitionCompletedThreadUnreadState(removed.state, [
|
||||
environment([historical]),
|
||||
]);
|
||||
|
||||
expect(removed.state).toEqual(new Map() satisfies CompletedThreadUnreadState);
|
||||
expect(readded.actions).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import type { EnvironmentId, OrchestrationThreadShell, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
|
||||
export interface CompletedThreadUnreadEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly isLive: boolean;
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
}
|
||||
|
||||
export type CompletedThreadUnreadState = ReadonlyMap<
|
||||
EnvironmentId,
|
||||
ReadonlyMap<ThreadId, string | null>
|
||||
>;
|
||||
|
||||
export interface CompletedThreadUnreadAction {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly completedAt: string;
|
||||
}
|
||||
|
||||
export interface CompletedThreadUnreadTransition {
|
||||
readonly state: CompletedThreadUnreadState;
|
||||
readonly actions: ReadonlyArray<CompletedThreadUnreadAction>;
|
||||
}
|
||||
|
||||
function eligibleCompletedAt(thread: OrchestrationThreadShell): string | null {
|
||||
if (thread.latestTurn?.state !== "completed" || !thread.latestTurn.completedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
const updatedAt = Date.parse(thread.updatedAt);
|
||||
if (!Number.isFinite(completedAt) || !Number.isFinite(updatedAt) || updatedAt < completedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return thread.latestTurn.completedAt;
|
||||
}
|
||||
|
||||
export function transitionCompletedThreadUnreadState(
|
||||
previousState: CompletedThreadUnreadState,
|
||||
environments: ReadonlyArray<CompletedThreadUnreadEnvironment>,
|
||||
): CompletedThreadUnreadTransition {
|
||||
const nextState = new Map<EnvironmentId, ReadonlyMap<ThreadId, string | null>>();
|
||||
const actions: CompletedThreadUnreadAction[] = [];
|
||||
|
||||
for (const environment of environments) {
|
||||
const previousCompletions = previousState.get(environment.environmentId);
|
||||
if (!environment.isLive) {
|
||||
// Keep the last live observations while a known environment reconnects,
|
||||
// but do not treat bootstrap or catch-up snapshots as new completions.
|
||||
if (previousCompletions !== undefined) {
|
||||
nextState.set(environment.environmentId, previousCompletions);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentCompletions = new Map<ThreadId, string | null>();
|
||||
for (const thread of environment.threads) {
|
||||
const completedAt = eligibleCompletedAt(thread);
|
||||
currentCompletions.set(thread.id, completedAt);
|
||||
|
||||
if (
|
||||
// An absent previous map means this is the environment's initial live
|
||||
// snapshot, whose historical completions establish the read baseline.
|
||||
previousCompletions !== undefined &&
|
||||
completedAt !== null &&
|
||||
thread.archivedAt === null &&
|
||||
(!previousCompletions.has(thread.id) || previousCompletions.get(thread.id) !== completedAt)
|
||||
) {
|
||||
actions.push({
|
||||
environmentId: environment.environmentId,
|
||||
threadId: thread.id,
|
||||
completedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
nextState.set(environment.environmentId, currentCompletions);
|
||||
}
|
||||
|
||||
return { state: nextState, actions };
|
||||
}
|
||||
|
||||
const completedThreadUnreadEnvironmentsAtom = Atom.make(
|
||||
(get): ReadonlyArray<CompletedThreadUnreadEnvironment> => {
|
||||
const environments: CompletedThreadUnreadEnvironment[] = [];
|
||||
for (const environmentId of get(environmentCatalog.catalogValueAtom).entries.keys()) {
|
||||
const shellState = get(environmentShell.stateValueAtom(environmentId));
|
||||
environments.push({
|
||||
environmentId,
|
||||
isLive: shellState.status === "live",
|
||||
threads: Option.match(shellState.snapshot, {
|
||||
onNone: () => [],
|
||||
onSome: (snapshot) => snapshot.threads,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return environments;
|
||||
},
|
||||
).pipe(Atom.withLabel("completed-thread-unread:environments"));
|
||||
|
||||
export function useMarkLiveCompletedThreadsUnread(): void {
|
||||
const environments = useAtomValue(completedThreadUnreadEnvironmentsAtom);
|
||||
const stateRef = useRef<CompletedThreadUnreadState>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
const transition = transitionCompletedThreadUnreadState(stateRef.current, environments);
|
||||
stateRef.current = transition.state;
|
||||
|
||||
const uiState = useUiStateStore.getState();
|
||||
for (const action of transition.actions) {
|
||||
uiState.markThreadUnread(
|
||||
scopedThreadKey(scopeThreadRef(action.environmentId, action.threadId)),
|
||||
action.completedAt,
|
||||
);
|
||||
}
|
||||
}, [environments]);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
@@ -14,10 +13,6 @@ 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";
|
||||
@@ -44,23 +39,6 @@ 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, {
|
||||
@@ -180,9 +158,6 @@ export function useThreadActions() {
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
refreshArchivedThreadsForEnvironment(target.environmentId);
|
||||
clearComposerDraftForThread(target);
|
||||
clearTerminalUiState(target);
|
||||
clearPerThreadClientState(target);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -272,7 +247,6 @@ export function useThreadActions() {
|
||||
threadRef,
|
||||
);
|
||||
clearTerminalUiState(threadRef);
|
||||
clearPerThreadClientState(threadRef);
|
||||
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
|
||||
@@ -50,20 +50,9 @@ 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.setIdleTTL(PREVIEW_STATE_IDLE_TTL_MS),
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`preview:thread:${threadKey}`),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
} from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useMarkLiveCompletedThreadsUnread } from "../hooks/useMarkLiveCompletedThreadsUnread";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
derivePhysicalProjectKeyFromPath,
|
||||
@@ -133,6 +134,7 @@ function RootRouteView() {
|
||||
<SshPasswordPromptDialog />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
<CompletedThreadUnreadTracker />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{appShell}
|
||||
@@ -141,6 +143,11 @@ function RootRouteView() {
|
||||
);
|
||||
}
|
||||
|
||||
function CompletedThreadUnreadTracker() {
|
||||
useMarkLiveCompletedThreadsUnread();
|
||||
return null;
|
||||
}
|
||||
|
||||
function DocumentTitleSync() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
PERSISTED_STATE_KEY,
|
||||
type PersistedUiState,
|
||||
persistState,
|
||||
removeThreadUiState,
|
||||
reorderProjects,
|
||||
resolveProjectExpanded,
|
||||
setDefaultAdvertisedEndpointKey,
|
||||
@@ -40,27 +39,6 @@ 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,27 +274,6 @@ 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,
|
||||
@@ -435,7 +414,6 @@ 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;
|
||||
@@ -452,7 +430,6 @@ 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) =>
|
||||
|
||||
Reference in new issue
Block a user