Compare commits

...
36 changed files with 853 additions and 48 deletions

No files matched your search

@@ -96,6 +96,13 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
return value ?? null;
}
function timestampCovers(timestamp: string | undefined, target: string): boolean {
if (timestamp === undefined) return false;
const timestampMs = Date.parse(timestamp);
const targetMs = Date.parse(target);
return Number.isFinite(timestampMs) && Number.isFinite(targetMs) && timestampMs >= targetMs;
}
function OpeningThreadLoadingScreen() {
return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
}
@@ -280,9 +287,45 @@ function ThreadRouteContent(
}, [props.renderInspector]),
);
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false });
const selectedThreadEnvironmentId = selectedThread?.environmentId ?? null;
const selectedThreadId = selectedThread?.id ?? null;
const selectedThreadCompletedAt = selectedThread?.latestTurn?.completedAt ?? null;
const selectedThreadViewedAtRef = useRef(selectedThread?.viewedAt);
selectedThreadViewedAtRef.current = selectedThread?.viewedAt;
const supportsThreadViewState = serverConfig?.environment.capabilities.threadViewState === true;
useFocusEffect(
useCallback(() => {
if (
selectedThreadEnvironmentId === null ||
selectedThreadId === null ||
selectedThreadCompletedAt === null ||
!supportsThreadViewState
) {
return;
}
if (timestampCovers(selectedThreadViewedAtRef.current, selectedThreadCompletedAt)) {
return;
}
void viewThread({
environmentId: selectedThreadEnvironmentId,
input: {
threadId: selectedThreadId,
viewedThrough: selectedThreadCompletedAt,
},
});
}, [
selectedThreadCompletedAt,
selectedThreadEnvironmentId,
selectedThreadId,
supportsThreadViewState,
viewThread,
]),
);
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
@@ -758,7 +801,6 @@ function ThreadRouteContent(
detailDeleted: selectedThreadDetailState.status === "deleted",
connectionState: routeConnectionState,
});
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const renderThreadRouteBody = (showActionControls: boolean) => (
<>
<ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
@@ -60,6 +60,7 @@ function threadDetailToShell(
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
viewedAt: thread.viewedAt,
snoozedUntil: thread.snoozedUntil ?? null,
snoozedAt: thread.snoozedAt ?? null,
session: thread.session,
@@ -91,6 +91,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.pullRequests).toBe(true);
expect(second.capabilities.threadViewState).toBe(true);
expect(second.capabilities.threadTitleRegeneration).toBe(true);
expect(second.capabilities.agentActivityPublishing).toBe(false);
}),
@@ -151,6 +151,7 @@ export const make = Effect.gen(function* () {
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadViewState: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
@@ -237,6 +237,64 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]);
yield* eventStore.append({
type: "thread.viewed",
eventId: EventId.make("evt-viewed-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:03.000Z",
commandId: CommandId.make("cmd-viewed-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-viewed-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
viewedAt: "2026-01-01T00:00:03.000Z",
},
});
yield* projectionPipeline.bootstrap;
const viewedRows = yield* sql<{
readonly viewedAt: string;
readonly updatedAt: string;
}>`
SELECT
viewed_at AS "viewedAt",
updated_at AS "updatedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(viewedRows, [
{
viewedAt: "2026-01-01T00:00:03.000Z",
updatedAt: "2026-01-01T00:00:02.000Z",
},
]);
yield* eventStore.append({
type: "thread.marked-unread",
eventId: EventId.make("evt-marked-unread-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:04.000Z",
commandId: CommandId.make("cmd-marked-unread-1"),
causationEventId: null,
correlationId: CommandId.make("cmd-marked-unread-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
viewedAt: "2025-12-31T23:59:59.999Z",
},
});
yield* projectionPipeline.bootstrap;
const markedUnreadRows = yield* sql<{ readonly viewedAt: string }>`
SELECT viewed_at AS "viewedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.deepEqual(markedUnreadRows, [{ viewedAt: "2025-12-31T23:59:59.999Z" }]);
}),
);
});
@@ -617,6 +617,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: event.payload.createdAt,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
@@ -695,6 +696,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.viewed":
case "thread.marked-unread": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
viewedAt: event.payload.viewedAt,
});
return;
}
case "thread.snoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -321,6 +321,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-02-24T00:00:02.000Z",
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -440,6 +441,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-02-24T00:00:02.000Z",
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -424,6 +424,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -460,6 +461,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -498,6 +500,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -940,6 +943,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -1573,6 +1577,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1780,6 +1785,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -1916,6 +1922,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2061,6 +2068,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
viewedAt: row.viewedAt ?? row.createdAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
@@ -2340,6 +2348,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
viewedAt: threadRow.value.viewedAt ?? threadRow.value.createdAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
@@ -2461,6 +2470,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
viewedAt: threadRow.value.viewedAt ?? threadRow.value.createdAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
+4
View File
@@ -11,6 +11,8 @@ import {
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadViewedPayload as ContractsThreadViewedPayloadSchema,
ThreadMarkedUnreadPayload as ContractsThreadMarkedUnreadPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
@@ -43,6 +45,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadViewedPayload = ContractsThreadViewedPayloadSchema;
export const ThreadMarkedUnreadPayload = ContractsThreadMarkedUnreadPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
+69
View File
@@ -7,6 +7,7 @@ import {
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -561,6 +562,74 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.view": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
const cappedViewedAt = DateTime.make(command.viewedThrough).pipe(
Option.filter(
(viewedThrough) => DateTime.Order(viewedThrough, DateTime.makeUnsafe(occurredAt)) <= 0,
),
Option.as(command.viewedThrough),
Option.getOrElse(() => occurredAt),
);
const viewedAt = DateTime.make(thread.viewedAt ?? thread.createdAt).pipe(
Option.filter(
(previousViewedAt) =>
DateTime.Order(previousViewedAt, DateTime.makeUnsafe(cappedViewedAt)) >= 0,
),
Option.as(thread.viewedAt ?? thread.createdAt),
Option.getOrElse(() => cappedViewedAt),
);
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.viewed",
payload: {
threadId: command.threadId,
viewedAt,
},
};
}
case "thread.mark-unread": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
const latestCompletedAt = thread.latestTurn?.completedAt;
const viewedAt =
latestCompletedAt == null
? (thread.viewedAt ?? thread.createdAt)
: DateTime.make(latestCompletedAt).pipe(
Option.map(DateTime.subtractDuration("1 millis")),
Option.map(DateTime.formatIso),
Option.getOrElse(() => thread.viewedAt ?? thread.createdAt),
);
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.marked-unread",
payload: {
threadId: command.threadId,
viewedAt,
},
};
}
case "thread.snooze": {
const thread = yield* requireThreadNotArchived({
readModel,
@@ -0,0 +1,99 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
import { decideOrchestrationCommand } from "./decider.ts";
const COMPLETED_AT = "2026-01-01T00:01:00.000Z";
const VIEWED_THROUGH = "2026-01-01T00:00:45.000Z";
function makeReadModel(): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:01.000Z",
completedAt: COMPLETED_AT,
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: COMPLETED_AT,
archivedAt: null,
settledOverride: null,
settledAt: null,
viewedAt: "2026-01-01T00:00:30.000Z",
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: COMPLETED_AT,
};
}
it.layer(NodeServices.layer)("thread view-state decider", (it) => {
it.effect("stamps a view at the acknowledged boundary", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse("2026-01-02T00:00:00.000Z"));
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.view",
commandId: CommandId.make("cmd-view"),
threadId: ThreadId.make("thread-1"),
viewedThrough: VIEWED_THROUGH,
},
readModel: makeReadModel(),
});
const viewed = Array.isArray(event) ? event[0] : event;
expect(viewed?.type).toBe("thread.viewed");
if (viewed?.type === "thread.viewed") {
expect(viewed.payload.viewedAt).toBe(VIEWED_THROUGH);
}
}),
);
it.effect("marks unread just before the latest completion", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.mark-unread",
commandId: CommandId.make("cmd-mark-unread"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(),
});
const markedUnread = Array.isArray(event) ? event[0] : event;
expect(markedUnread?.type).toBe("thread.marked-unread");
if (markedUnread?.type === "thread.marked-unread") {
expect(markedUnread.payload.viewedAt).toBe("2026-01-01T00:00:59.999Z");
}
}),
);
});
@@ -84,5 +84,29 @@ it.effect("projects settled lifecycle events", () =>
);
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
const viewedAt = "2026-01-01T00:00:01.000Z";
const viewed = yield* projectEvent(
activityUnsettled,
makeEvent({
sequence: 5,
type: "thread.viewed",
payload: { threadId: ThreadId.make("thread-1"), viewedAt },
}),
);
expect(viewed.threads[0]?.viewedAt).toBe(viewedAt);
expect(viewed.threads[0]?.updatedAt).toBe(now);
const markedUnreadAt = "2025-12-31T23:59:59.999Z";
const markedUnread = yield* projectEvent(
viewed,
makeEvent({
sequence: 6,
type: "thread.marked-unread",
payload: { threadId: ThreadId.make("thread-1"), viewedAt: markedUnreadAt },
}),
);
expect(markedUnread.threads[0]?.viewedAt).toBe(markedUnreadAt);
expect(markedUnread.threads[0]?.updatedAt).toBe(now);
}),
);
@@ -30,6 +30,8 @@ import {
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadViewedPayload,
ThreadMarkedUnreadPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -381,6 +383,26 @@ export function projectEvent(
})),
);
case "thread.viewed":
return decodeForEvent(ThreadViewedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
viewedAt: payload.viewedAt,
}),
})),
);
case "thread.marked-unread":
return decodeForEvent(ThreadMarkedUnreadPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
viewedAt: payload.viewedAt,
}),
})),
);
case "thread.snoozed":
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -45,6 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at,
settled_override,
settled_at,
viewed_at,
snoozed_until,
snoozed_at,
pinned_at,
@@ -72,6 +73,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.viewedAt ?? row.createdAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
@@ -99,6 +101,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
viewed_at = excluded.viewed_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
@@ -133,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -169,6 +173,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
viewed_at AS "viewedAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
@@ -53,6 +53,7 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
import Migration0041 from "./Migrations/041_ProjectionThreadsViewedAt.ts";
/**
* Migration loader with all migrations defined inline.
@@ -105,6 +106,7 @@ export const migrationEntries = [
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
[40, "ProjectionProjectFaviconPath", Migration0040],
[41, "ProjectionThreadsViewedAt", Migration0041],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,47 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("041_ProjectionThreadsViewedAt", (it) => {
it.effect("adds viewed_at and marks historical rows viewed", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 40 });
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
runtime_mode,
interaction_mode,
created_at,
updated_at
) VALUES (
'thread-1',
'project-1',
'Historical thread',
'full-access',
'default',
'2026-01-01T00:00:00.000Z',
'2026-01-02T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 41 });
const rows = yield* sql<{ readonly viewedAt: string | null }>`
SELECT viewed_at AS "viewedAt"
FROM projection_threads
WHERE thread_id = 'thread-1'
`;
assert.equal(rows[0]?.viewedAt, "2026-01-02T00:00:00.000Z");
}),
);
});
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "viewed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN viewed_at TEXT
`;
}
// Upgrading must not make every historical completion appear unread.
yield* sql`
UPDATE projection_threads
SET viewed_at = COALESCE(viewed_at, updated_at, created_at)
WHERE viewed_at IS NULL
`;
});
@@ -39,6 +39,7 @@ export const ProjectionThread = Schema.Struct({
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
viewedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
+16 -10
View File
@@ -101,7 +101,8 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useUiStateStore } from "../uiStateStore";
import { resolveThreadViewedAt, useUiStateStore } from "../uiStateStore";
import { useThreadViewState } from "../hooks/useThreadViewState";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -1282,7 +1283,7 @@ function ChatViewContent(props: ChatViewProps) {
},
};
}, [routeKind, routeThreadRef, routeThreadState]);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const { markViewed } = useThreadViewState();
const settings = useEnvironmentSettings(environmentId);
// New-thread defaults live in the primary environment's settings.json (the
// settings UI never writes to remote environments), so read them from the
@@ -1679,12 +1680,9 @@ function ChatViewContent(props: ChatViewProps) {
useEffect(() => {
const completedAt = serverThread?.latestTurn?.completedAt;
if (!serverThread?.id || !completedAt) return;
markThreadVisited(
scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
completedAt,
);
markViewed(scopeThreadRef(serverThread.environmentId, serverThread.id), completedAt);
}, [
markThreadVisited,
markViewed,
serverThread?.environmentId,
serverThread?.id,
serverThread?.latestTurn?.completedAt,
@@ -4148,13 +4146,21 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
const acknowledgeActiveThreadWoke = useCallback(() => {
if (activeThreadRef === null || activeThreadWokeAt === null) return;
markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);
}, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);
markViewed(activeThreadRef, activeThreadWokeAt);
}, [activeThreadRef, activeThreadWokeAt, markViewed]);
// Mirror of the sidebar's Woke pill for the open thread. It uses the same
// visit comparison and change request settle rule.
const activeThreadLastVisitedAt = useUiStateStore((store) =>
const activeThreadLocalLastVisitedAt = useUiStateStore((store) =>
activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
);
const activeThreadPendingViewState = useUiStateStore((store) =>
activeThreadKey === null ? undefined : store.threadViewStatePendingById[activeThreadKey],
);
const activeThreadLastVisitedAt = resolveThreadViewedAt({
serverViewedAt: activeThreadShell?.viewedAt,
localViewedAt: activeThreadLocalLastVisitedAt,
pending: activeThreadPendingViewState,
});
const activeThreadWokeVisible = useMemo(() => {
if (activeThreadWokeAt === null) return false;
if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false;
+25 -13
View File
@@ -92,6 +92,7 @@ import { previewEnvironment } from "../state/preview";
import {
legacyProjectCwdPreferenceKey,
resolveProjectExpanded,
resolveThreadViewedAt,
useUiStateStore,
} from "../uiStateStore";
import {
@@ -110,6 +111,7 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useDesktopUpdateState } from "../state/desktopUpdate";
import { useThreadActions } from "../hooks/useThreadActions";
import { useThreadViewState } from "../hooks/useThreadViewState";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
@@ -373,7 +375,13 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
} = props;
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const pendingViewState = useUiStateStore((state) => state.threadViewStatePendingById[threadKey]);
const lastVisitedAt = resolveThreadViewedAt({
serverViewedAt: thread.viewedAt,
localViewedAt: localLastVisitedAt,
pending: pendingViewState,
});
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: thread.environmentId,
@@ -1138,7 +1146,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar();
const markThreadUnread = useUiStateStore((state) => state.markThreadUnread);
const { markUnread } = useThreadViewState();
const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded);
const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread);
const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo);
@@ -1209,12 +1217,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const threadLastVisitedAts = useUiStateStore(
useShallow((state) =>
projectThreads.map(
(thread) =>
state.threadLastVisitedAtById[
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
] ?? null,
),
projectThreads.map((thread) => {
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
return (
resolveThreadViewedAt({
serverViewedAt: thread.viewedAt,
localViewedAt: state.threadLastVisitedAtById[threadKey],
pending: state.threadViewStatePendingById[threadKey],
}) ?? null
);
}),
),
);
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
@@ -1802,8 +1814,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
if (clicked === "mark-unread") {
for (const { threadKey, thread } of selectedThreadEntries) {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
for (const { threadRef, thread } of selectedThreadEntries) {
markUnread(threadRef, thread.latestTurn?.completedAt);
}
clearSelection();
return;
@@ -1890,7 +1902,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
archiveThread,
clearSelection,
deleteThread,
markThreadUnread,
markUnread,
removeFromSelection,
],
);
@@ -2181,7 +2193,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
if (clicked === "mark-unread") {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
markUnread(threadRef, thread.latestTurn?.completedAt);
return;
}
if (clicked === "copy-path") {
@@ -2233,7 +2245,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
markThreadUnread,
markUnread,
memberProjectByScopedKey,
project.workspaceRoot,
startThreadRename,
+28 -10
View File
@@ -94,9 +94,14 @@ import {
buildSidebarProjectSnapshots,
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import {
legacyProjectCwdPreferenceKey,
resolveThreadViewedAt,
useUiStateStore,
} from "../uiStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useThreadActions } from "../hooks/useThreadActions";
import { useThreadViewState } from "../hooks/useThreadViewState";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { openCommandPalette } from "../commandPaletteBus";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
@@ -741,7 +746,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
);
const threadKey = scopedThreadKey(threadRef);
const isRegeneratingTitle = thread.titleRegeneration != null;
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const pendingViewState = useUiStateStore((state) => state.threadViewStatePendingById[threadKey]);
const lastVisitedAt = resolveThreadViewedAt({
serverViewedAt: thread.viewedAt,
localViewedAt: localLastVisitedAt,
pending: pendingViewState,
});
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -1705,13 +1716,12 @@ export default function Sidebar() {
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const markThreadVisited = useUiStateStore((s) => s.markThreadVisited);
const { markUnread, markViewed } = useThreadViewState();
const acknowledgeWoke = useCallback(
(threadRef: ScopedThreadRef, visitedAt: string) => {
markThreadVisited(scopedThreadKey(threadRef), visitedAt);
markViewed(threadRef, visitedAt);
},
[markThreadVisited],
[markViewed],
);
const routeTarget = useParams({
strict: false,
@@ -2882,7 +2892,12 @@ export default function Sidebar() {
if (clicked.value === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
if (thread) {
markUnread(
scopeThreadRef(thread.environmentId, thread.id),
thread.latestTurn?.completedAt,
);
}
}
clearSelection();
return;
@@ -2934,7 +2949,7 @@ export default function Sidebar() {
clearSelection,
confirmThreadDelete,
deleteThread,
markThreadUnread,
markUnread,
performSnooze,
removeFromSelection,
serverConfigs,
@@ -3070,7 +3085,10 @@ export default function Sidebar() {
return;
}
case "mark-unread":
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
markUnread(
scopeThreadRef(thread.environmentId, thread.id),
thread.latestTurn?.completedAt,
);
return;
case "copy-path":
if (!threadWorkspacePath) {
@@ -3138,7 +3156,7 @@ export default function Sidebar() {
copyThreadIdToClipboard,
deleteThread,
handleMultiSelectContextMenu,
markThreadUnread,
markUnread,
projectCwdByKey,
serverConfigs,
startThreadRename,
@@ -11,7 +11,7 @@ import { useProject } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { vcsEnvironment } from "../state/vcs";
import { useUiStateStore } from "../uiStateStore";
import { resolveThreadViewedAt, useUiStateStore } from "../uiStateStore";
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
import type { SidebarThreadSummary } from "../types";
@@ -231,9 +231,17 @@ export function ThreadStatusLabel({
*/
export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const lastVisitedAt = useUiStateStore(
const localLastVisitedAt = useUiStateStore(
(state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
);
const pendingViewState = useUiStateStore(
(state) => state.threadViewStatePendingById[scopedThreadKey(threadRef)],
);
const lastVisitedAt = resolveThreadViewedAt({
serverViewedAt: thread.viewedAt,
localViewedAt: localLastVisitedAt,
pending: pendingViewState,
});
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
+5 -5
View File
@@ -1,4 +1,4 @@
import { scopeProjectRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
@@ -30,11 +30,11 @@ import {
readThreadShell,
} from "../state/entities";
import { readLocalApi } from "../localApi";
import { useUiStateStore } from "../uiStateStore";
import { useCopyToClipboard } from "./useCopyToClipboard";
import { useNewThreadHandler } from "./useHandleNewThread";
import { useClientSettings } from "./useSettings";
import { useThreadActions } from "./useThreadActions";
import { useThreadViewState } from "./useThreadViewState";
function failureToast(title: string, error: unknown) {
toastManager.add(
@@ -78,7 +78,7 @@ export function useThreadActionMenu(input: {
reportFailure: false,
});
const handleNewThread = useNewThreadHandler();
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const { markUnread } = useThreadViewState();
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
@@ -228,7 +228,7 @@ export function useThreadActionMenu(input: {
);
return;
case "mark-unread":
markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
markUnread(threadRef, thread.latestTurn?.completedAt);
return;
case "copy-path": {
const workspacePath = thread.worktreePath ?? projectCwd;
@@ -294,7 +294,7 @@ export function useThreadActionMenu(input: {
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
markThreadUnread,
markUnread,
onStartRename,
pinThread,
projectCwd,
+6 -7
View File
@@ -2,7 +2,6 @@ import {
parseScopedThreadKey,
scopeProjectRef,
scopeThreadRef,
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSettle, canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
@@ -32,12 +31,12 @@ import {
readThreadShells,
} from "../state/entities";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { useUiStateStore } from "../uiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { useClientSettings } from "./useSettings";
import { useAtomCommand } from "../state/use-atom-command";
import { useThreadViewState } from "./useThreadViewState";
export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
"ThreadArchiveBlockedError",
@@ -181,7 +180,7 @@ export function useThreadActions() {
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
const { markViewed } = useThreadViewState();
const router = useRouter();
const handleNewThread = useNewThreadHandler();
// Keep a ref so archiveThread can call handleNewThread without appearing in
@@ -235,7 +234,7 @@ export function useThreadActions() {
}
const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
if (wokeAt !== null) {
markThreadVisited(scopedThreadKey(threadRef), wokeAt);
markViewed(threadRef, wokeAt);
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
opts.onArchived?.();
@@ -252,7 +251,7 @@ export function useThreadActions() {
return archiveResult;
},
[archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],
[archiveThreadMutation, getCurrentRouteThreadRef, markViewed, resolveThreadTarget],
);
const unarchiveThread = useCallback(
@@ -506,11 +505,11 @@ export function useThreadActions() {
input: { threadId: target.threadId },
});
if (result._tag === "Success" && wokeAt !== null) {
markThreadVisited(scopedThreadKey(target), wokeAt);
markViewed(target, wokeAt);
}
return result;
},
[markThreadVisited, resolveThreadTarget, settleThreadMutation],
[markViewed, resolveThreadTarget, settleThreadMutation],
);
const unsettleThread = useCallback(
+68
View File
@@ -0,0 +1,68 @@
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { readEnvironmentSupportsViewState, readThreadShell } from "../state/entities";
import { threadEnvironment } from "../state/threads";
import { useUiStateStore } from "../uiStateStore";
import { useAtomCommand } from "../state/use-atom-command";
function timestampCovers(timestamp: string | undefined, target: string): boolean {
if (timestamp === undefined) return false;
const timestampMs = Date.parse(timestamp);
const targetMs = Date.parse(target);
return Number.isFinite(timestampMs) && Number.isFinite(targetMs) && timestampMs >= targetMs;
}
/** Keeps the local compatibility marker and the server view marker in sync. */
export function useThreadViewState() {
const markLocalViewed = useUiStateStore((state) => state.markThreadVisited);
const markLocalUnread = useUiStateStore((state) => state.markThreadUnread);
const setPending = useUiStateStore((state) => state.setThreadViewStatePending);
const clearPending = useUiStateStore((state) => state.clearThreadViewStatePending);
const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false });
const markUnreadOnServer = useAtomCommand(threadEnvironment.markUnread, "thread mark unread");
const markViewed = useCallback(
(threadRef: ScopedThreadRef, viewedThrough: string) => {
const threadKey = scopedThreadKey(threadRef);
if (!readEnvironmentSupportsViewState(threadRef.environmentId)) {
markLocalViewed(threadKey, viewedThrough);
return;
}
const thread = readThreadShell(threadRef);
if (timestampCovers(thread?.viewedAt, viewedThrough)) return;
const pending = { kind: "viewed", targetAt: viewedThrough } as const;
setPending(threadKey, pending);
markLocalViewed(threadKey, viewedThrough);
void viewThread({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, viewedThrough },
}).then(() => clearPending(threadKey, pending));
},
[clearPending, markLocalViewed, setPending, viewThread],
);
const markUnread = useCallback(
(threadRef: ScopedThreadRef, latestTurnCompletedAt: string | null | undefined) => {
const threadKey = scopedThreadKey(threadRef);
if (
latestTurnCompletedAt == null ||
!readEnvironmentSupportsViewState(threadRef.environmentId)
) {
markLocalUnread(threadKey, latestTurnCompletedAt);
return;
}
const pending = { kind: "unread", targetAt: latestTurnCompletedAt } as const;
setPending(threadKey, pending);
markLocalUnread(threadKey, latestTurnCompletedAt);
void markUnreadOnServer({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
}).then(() => clearPending(threadKey, pending));
},
[clearPending, markLocalUnread, markUnreadOnServer, setPending],
);
return useMemo(() => ({ markViewed, markUnread }), [markUnread, markViewed]);
}
+8
View File
@@ -241,6 +241,14 @@ export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boo
);
}
/** Whether the environment's server persists thread view state. */
export function readEnvironmentSupportsViewState(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadViewState === true
);
}
/** Whether the environment's server understands thread.pin/unpin.
Same version-skew contract as settlement. */
export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {
+18
View File
@@ -10,6 +10,7 @@ import {
type PersistedUiState,
persistState,
reorderProjects,
resolveThreadViewedAt,
resolveProjectExpanded,
setDefaultAdvertisedEndpointKey,
setProjectExpanded,
@@ -53,6 +54,23 @@ describe("uiStateStore pure functions", () => {
expect(markThreadUnread(next, threadId, null)).toBe(next);
});
it("uses local view state only while its server command is pending", () => {
const input = {
serverViewedAt: "2026-02-25T12:30:00.000Z",
localViewedAt: "2026-02-25T12:35:00.000Z",
};
expect(resolveThreadViewedAt({ ...input, pending: undefined })).toBe(
"2026-02-25T12:30:00.000Z",
);
expect(
resolveThreadViewedAt({
...input,
pending: { kind: "viewed", targetAt: "2026-02-25T12:35:00.000Z" },
}),
).toBe("2026-02-25T12:35:00.000Z");
});
it("resolves project expansion from logical, physical, and legacy preference keys", () => {
const physicalKey = "environment:/repo/project";
const legacyKey = legacyProjectCwdPreferenceKey("/repo/project");
+33
View File
@@ -45,6 +45,11 @@ export interface UiEndpointState {
export interface UiState extends UiProjectState, UiThreadState, UiEndpointState {}
export interface PendingThreadViewState {
kind: "viewed" | "unread";
targetAt: string;
}
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
@@ -270,6 +275,16 @@ export function markThreadUnread(
};
}
export function resolveThreadViewedAt(input: {
serverViewedAt: string | undefined;
localViewedAt: string | undefined;
pending: PendingThreadViewState | undefined;
}): string | undefined {
return input.pending === undefined
? (input.serverViewedAt ?? input.localViewedAt)
: (input.localViewedAt ?? input.serverViewedAt);
}
export function setThreadChangedFilesExpanded(
state: UiState,
threadId: string,
@@ -382,8 +397,11 @@ export function reorderProjects(
}
interface UiStateStore extends UiState {
threadViewStatePendingById: Record<string, PendingThreadViewState>;
markThreadVisited: (threadId: string, visitedAt: string) => void;
markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;
setThreadViewStatePending: (threadId: string, pending: PendingThreadViewState) => void;
clearThreadViewStatePending: (threadId: string, pending: PendingThreadViewState) => void;
setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;
setDefaultAdvertisedEndpointKey: (key: string | null) => void;
setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void;
@@ -396,10 +414,25 @@ interface UiStateStore extends UiState {
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
threadViewStatePendingById: {},
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
setThreadViewStatePending: (threadId, pending) =>
set((state) => ({
threadViewStatePendingById: {
...state.threadViewStatePendingById,
[threadId]: pending,
},
})),
clearThreadViewStatePending: (threadId, pending) =>
set((state) => {
if (state.threadViewStatePendingById[threadId] !== pending) return state;
const threadViewStatePendingById = { ...state.threadViewStatePendingById };
delete threadViewStatePendingById[threadId];
return { threadViewStatePendingById };
}),
setThreadChangedFilesExpanded: (threadId, turnId, expanded) =>
set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),
setDefaultAdvertisedEndpointKey: (key) =>
@@ -25,6 +25,8 @@ import {
archiveThread,
createProject,
settleThread,
viewThread,
markThreadUnread,
stopThreadSession,
unsettleThread,
} from "./commands.ts";
@@ -171,4 +173,35 @@ describe("environment commands", () => {
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("dispatches thread view-state commands without client timestamps", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
yield* viewThread({
commandId: CommandId.make("view-command"),
threadId: ThreadId.make("thread-1"),
viewedThrough: "2026-01-01T00:00:00.000Z",
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
yield* markThreadUnread({
commandId: CommandId.make("mark-unread-command"),
threadId: ThreadId.make("thread-1"),
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.view",
commandId: "view-command",
threadId: "thread-1",
viewedThrough: "2026-01-01T00:00:00.000Z",
},
{
type: "thread.mark-unread",
commandId: "mark-unread-command",
threadId: "thread-1",
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
});
@@ -37,6 +37,8 @@ export type ArchiveThreadInput = CommandInput<"thread.archive">;
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
export type SettleThreadInput = CommandInput<"thread.settle">;
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
export type ViewThreadInput = CommandInput<"thread.view">;
export type MarkThreadUnreadInput = CommandInput<"thread.mark-unread">;
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
export type PinThreadInput = CommandInput<"thread.pin">;
@@ -180,6 +182,26 @@ export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Eff
});
});
export const viewThread: (input: ViewThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.viewThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.view",
commandId: yield* commandId(input),
});
});
export const markThreadUnread: (input: MarkThreadUnreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.markThreadUnread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.mark-unread",
commandId: yield* commandId(input),
});
});
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.snoozeThread",
)(function* (input) {
@@ -21,6 +21,8 @@ import {
type UnarchiveThreadInput,
type UnpinThreadInput,
type UnsettleThreadInput,
type ViewThreadInput,
type MarkThreadUnreadInput,
type UnsnoozeThreadInput,
type UpdateThreadMetadataInput,
archiveThread,
@@ -41,6 +43,8 @@ import {
unarchiveThread,
unpinThread,
unsettleThread,
viewThread,
markThreadUnread,
unsnoozeThread,
updateThreadMetadata,
} from "../operations/commands.ts";
@@ -65,6 +69,8 @@ export type {
UnarchiveThreadInput,
UnpinThreadInput,
UnsettleThreadInput,
ViewThreadInput,
MarkThreadUnreadInput,
UnsnoozeThreadInput,
UpdateThreadMetadataInput,
} from "../operations/commands.ts";
@@ -115,6 +121,18 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
view: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:view",
execute: (input: ViewThreadInput) => viewThread(input),
scheduler,
concurrency,
}),
markUnread: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:mark-unread",
execute: (input: MarkThreadUnreadInput) => markThreadUnread(input),
scheduler,
concurrency,
}),
snooze: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:snooze",
execute: (input: SnoozeThreadInput) => snoozeThread(input),
@@ -231,6 +231,32 @@ describe("applyThreadDetailEvent", () => {
});
});
describe("thread.viewed / thread.marked-unread", () => {
it.each(["thread.viewed", "thread.marked-unread"] as const)(
"stores viewedAt for %s",
(type) => {
const viewedAt = "2026-04-01T05:00:00.000Z";
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 5,
occurredAt: viewedAt,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type,
payload: {
threadId: ThreadId.make("thread-1"),
viewedAt,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.viewedAt).toBe(viewedAt);
}
},
);
});
describe("thread.pinned / thread.unpinned", () => {
it("sets pinnedAt", () => {
const pinnedAt = "2026-04-01T05:00:00.000Z";
@@ -145,6 +145,16 @@ export function applyThreadDetailEvent(
},
};
case "thread.viewed":
case "thread.marked-unread":
return {
kind: "updated",
thread: {
...thread,
viewedAt: event.payload.viewedAt,
},
};
case "thread.snoozed":
return {
kind: "updated",
+3
View File
@@ -64,6 +64,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server understands thread.pin.reorder (and orderKey on thread.pin).
Same version-skew contract as threadSettlement. */
threadPinReorder: Schema.optionalKey(Schema.Boolean),
/** Server persists thread.view / thread.mark-unread state. Same
version-skew contract as threadSettlement. */
threadViewState: Schema.optionalKey(Schema.Boolean),
/** Server understands regenerateTitle on thread.meta.update. Absent on
older servers, so clients hide the action instead of sending it. */
threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
@@ -385,6 +385,25 @@ it.effect("decodes thread settle and unsettle commands", () =>
}),
);
it.effect("decodes thread view-state commands", () =>
Effect.gen(function* () {
const view = yield* decodeOrchestrationCommand({
type: "thread.view",
commandId: "cmd-view-1",
threadId: "thread-1",
viewedThrough: "2026-01-01T00:00:00.000Z",
});
const markUnread = yield* decodeOrchestrationCommand({
type: "thread.mark-unread",
commandId: "cmd-mark-unread-1",
threadId: "thread-1",
});
assert.strictEqual(view.type, "thread.view");
assert.strictEqual(markUnread.type, "thread.mark-unread");
}),
);
it.effect("defaults settled fields when decoding historical thread data", () =>
Effect.gen(function* () {
const common = {
@@ -511,6 +530,41 @@ it.effect("decodes thread settled and unsettled events", () =>
}),
);
it.effect("decodes thread view-state events", () =>
Effect.gen(function* () {
const viewedAt = "2026-01-02T00:00:00.000Z";
const viewed = yield* decodeOrchestrationEvent({
sequence: 1,
eventId: "event-viewed-1",
aggregateKind: "thread",
aggregateId: "thread-1",
type: "thread.viewed",
occurredAt: viewedAt,
commandId: "cmd-viewed-1",
causationEventId: null,
correlationId: "cmd-viewed-1",
metadata: {},
payload: { threadId: "thread-1", viewedAt },
});
const markedUnread = yield* decodeOrchestrationEvent({
sequence: 2,
eventId: "event-marked-unread-1",
aggregateKind: "thread",
aggregateId: "thread-1",
type: "thread.marked-unread",
occurredAt: viewedAt,
commandId: "cmd-marked-unread-1",
causationEventId: null,
correlationId: "cmd-marked-unread-1",
metadata: {},
payload: { threadId: "thread-1", viewedAt },
});
assert.strictEqual(viewed.type, "thread.viewed");
assert.strictEqual(markedUnread.type, "thread.marked-unread");
}),
);
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
Effect.gen(function* () {
const parsed = yield* decodeThreadTurnStartCommand({
+42
View File
@@ -380,6 +380,8 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
// Optional so payloads and cached snapshots from pre-view-state servers decode.
viewedAt: Schema.optional(IsoDateTime),
// Snooze is an overlay on the active lifecycle, not a fourth destination:
// a snoozed thread stays "active" in the model and is only suppressed from
// the inbox until snoozedUntil passes (or the thread raises its hand).
@@ -450,6 +452,7 @@ export const OrchestrationThreadShell = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
viewedAt: Schema.optional(IsoDateTime),
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
@@ -700,6 +703,19 @@ const ThreadUnsettleCommand = Schema.Struct({
reason: Schema.Literal("user"),
});
const ThreadViewCommand = Schema.Struct({
type: Schema.Literal("thread.view"),
commandId: CommandId,
threadId: ThreadId,
viewedThrough: IsoDateTime,
});
const ThreadMarkUnreadCommand = Schema.Struct({
type: Schema.Literal("thread.mark-unread"),
commandId: CommandId,
threadId: ThreadId,
});
const ThreadSnoozeCommand = Schema.Struct({
type: Schema.Literal("thread.snooze"),
commandId: CommandId,
@@ -905,6 +921,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadViewCommand,
ThreadMarkUnreadCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadPinCommand,
@@ -933,6 +951,8 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadViewCommand,
ThreadMarkUnreadCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadPinCommand,
@@ -1051,6 +1071,8 @@ export const OrchestrationEventType = Schema.Literals([
"thread.unarchived",
"thread.settled",
"thread.unsettled",
"thread.viewed",
"thread.marked-unread",
"thread.snoozed",
"thread.unsnoozed",
"thread.pinned",
@@ -1151,6 +1173,16 @@ export const ThreadUnsettledPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
export const ThreadViewedPayload = Schema.Struct({
threadId: ThreadId,
viewedAt: IsoDateTime,
});
export const ThreadMarkedUnreadPayload = Schema.Struct({
threadId: ThreadId,
viewedAt: IsoDateTime,
});
export const ThreadSnoozedPayload = Schema.Struct({
threadId: ThreadId,
snoozedUntil: IsoDateTime,
@@ -1372,6 +1404,16 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.unsettled"),
payload: ThreadUnsettledPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.viewed"),
payload: ThreadViewedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.marked-unread"),
payload: ThreadMarkedUnreadPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.snoozed"),