diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index cad1cab8e6..91629f6ff2 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -280,9 +280,34 @@ 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 });
+ useEffect(() => {
+ const completedAt = selectedThread?.latestTurn?.completedAt;
+ if (
+ selectedThread === null ||
+ completedAt == null ||
+ serverConfig?.environment.capabilities.threadViewState !== true
+ ) {
+ return;
+ }
+ const viewedAtMs = Date.parse(selectedThread.viewedAt ?? "");
+ const completedAtMs = Date.parse(completedAt);
+ if (
+ Number.isFinite(viewedAtMs) &&
+ Number.isFinite(completedAtMs) &&
+ viewedAtMs >= completedAtMs
+ ) {
+ return;
+ }
+ void viewThread({
+ environmentId: selectedThread.environmentId,
+ input: { threadId: selectedThread.id },
+ });
+ }, [selectedThread, serverConfig?.environment.capabilities.threadViewState, viewThread]);
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
@@ -758,7 +783,6 @@ function ThreadRouteContent(
detailDeleted: selectedThreadDetailState.status === "deleted",
connectionState: routeConnectionState,
});
- const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const renderThreadRouteBody = (showActionControls: boolean) => (
<>
diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts
index 8e340ef33b..c50e99ab08 100644
--- a/apps/mobile/src/state/use-thread-selection.ts
+++ b/apps/mobile/src/state/use-thread-selection.ts
@@ -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,
diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts
index ee30d98759..64c326bc31 100644
--- a/apps/server/src/environment/ServerEnvironment.test.ts
+++ b/apps/server/src/environment/ServerEnvironment.test.ts
@@ -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);
}),
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 45dc0ee9cf..cbb851005e 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -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 } : {}),
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts
index e3b18d74a9..7127eb23bc 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts
@@ -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" }]);
}),
);
});
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index e9a625dd91..0429406b2b 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -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,
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index be596b36b8..8cc5273289 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -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",
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index 3e77f9cf87..f256849925 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -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,
diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts
index 7e866cf895..fd6794f507 100644
--- a/apps/server/src/orchestration/Schemas.ts
+++ b/apps/server/src/orchestration/Schemas.ts
@@ -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;
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index a48bb29e15..0d7d0b1971 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -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,59 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
+ case "thread.view": {
+ yield* requireThread({
+ readModel,
+ command,
+ threadId: command.threadId,
+ });
+ const occurredAt = yield* nowIso;
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt,
+ commandId: command.commandId,
+ })),
+ type: "thread.viewed",
+ payload: {
+ threadId: command.threadId,
+ viewedAt: occurredAt,
+ },
+ };
+ }
+
+ 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,
diff --git a/apps/server/src/orchestration/decider.viewState.test.ts b/apps/server/src/orchestration/decider.viewState.test.ts
new file mode 100644
index 0000000000..d589aabbb6
--- /dev/null
+++ b/apps/server/src/orchestration/decider.viewState.test.ts
@@ -0,0 +1,95 @@
+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 { decideOrchestrationCommand } from "./decider.ts";
+
+const COMPLETED_AT = "2026-01-01T00:01:00.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 with server time", () =>
+ Effect.gen(function* () {
+ const event = yield* decideOrchestrationCommand({
+ command: {
+ type: "thread.view",
+ commandId: CommandId.make("cmd-view"),
+ threadId: ThreadId.make("thread-1"),
+ },
+ 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.occurredAt);
+ }
+ }),
+ );
+
+ 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");
+ }
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration/projector.settled.test.ts b/apps/server/src/orchestration/projector.settled.test.ts
index 2070c44418..8c95857470 100644
--- a/apps/server/src/orchestration/projector.settled.test.ts
+++ b/apps/server/src/orchestration/projector.settled.test.ts
@@ -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);
}),
);
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index f486dcb2bc..96d52ddc2d 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -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) => ({
diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts
index b7d8ae1374..0111dceae1 100644
--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts
+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts
@@ -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",
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index b137cedfbe..961ef20db4 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -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);
diff --git a/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.test.ts b/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.test.ts
new file mode 100644
index 0000000000..5dbadc742b
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.test.ts
@@ -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");
+ }),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.ts b/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.ts
new file mode 100644
index 0000000000..610cc78bbc
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/041_ProjectionThreadsViewedAt.ts
@@ -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
+ `;
+});
diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts
index c572e1d11c..f58840b8c6 100644
--- a/apps/server/src/persistence/Services/ProjectionThreads.ts
+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts
@@ -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),
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 6eab33aec1..caca433884 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -102,6 +102,7 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { 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,14 @@ 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 activeThreadLastVisitedAt = activeThreadShell?.viewedAt ?? activeThreadLocalLastVisitedAt;
const activeThreadWokeVisible = useMemo(() => {
if (activeThreadWokeAt === null) return false;
if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false;
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index f40dc211c6..f148567b4b 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -110,6 +110,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 +374,8 @@ 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 lastVisitedAt = thread.viewedAt ?? localLastVisitedAt;
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: thread.environmentId,
@@ -1138,7 +1140,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);
@@ -1211,9 +1213,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
useShallow((state) =>
projectThreads.map(
(thread) =>
+ thread.viewedAt ??
state.threadLastVisitedAtById[
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
- ] ?? null,
+ ] ??
+ null,
),
),
);
@@ -1802,8 +1806,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 +1894,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
archiveThread,
clearSelection,
deleteThread,
- markThreadUnread,
+ markUnread,
removeFromSelection,
],
);
@@ -2181,7 +2185,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 +2237,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
- markThreadUnread,
+ markUnread,
memberProjectByScopedKey,
project.workspaceRoot,
startThreadRename,
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 2f0c5a2214..7b922d43eb 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -97,6 +97,7 @@ import {
import { legacyProjectCwdPreferenceKey, 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 +742,8 @@ 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 lastVisitedAt = thread.viewedAt ?? localLastVisitedAt;
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -1705,13 +1707,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 +2883,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 +2940,7 @@ export default function Sidebar() {
clearSelection,
confirmThreadDelete,
deleteThread,
- markThreadUnread,
+ markUnread,
performSnooze,
removeFromSelection,
serverConfigs,
@@ -3070,7 +3076,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 +3147,7 @@ export default function Sidebar() {
copyThreadIdToClipboard,
deleteThread,
handleMultiSelectContextMenu,
- markThreadUnread,
+ markUnread,
projectCwdByKey,
serverConfigs,
startThreadRename,
diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx
index af53d1a78b..5811c727f6 100644
--- a/apps/web/src/components/ThreadStatusIndicators.tsx
+++ b/apps/web/src/components/ThreadStatusIndicators.tsx
@@ -231,9 +231,10 @@ 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 lastVisitedAt = thread.viewedAt ?? localLastVisitedAt;
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts
index d7ca230516..ecd5f75248 100644
--- a/apps/web/src/hooks/useThreadActionMenu.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.ts
@@ -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,
diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts
index 569b4be96e..bf40402494 100644
--- a/apps/web/src/hooks/useThreadActions.ts
+++ b/apps/web/src/hooks/useThreadActions.ts
@@ -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",
@@ -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(
diff --git a/apps/web/src/hooks/useThreadViewState.ts b/apps/web/src/hooks/useThreadViewState.ts
new file mode 100644
index 0000000000..ec424cc376
--- /dev/null
+++ b/apps/web/src/hooks/useThreadViewState.ts
@@ -0,0 +1,58 @@
+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 viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false });
+ const markUnreadOnServer = useAtomCommand(threadEnvironment.markUnread, {
+ reportFailure: false,
+ });
+
+ const markViewed = useCallback(
+ (threadRef: ScopedThreadRef, viewedThrough: string) => {
+ markLocalViewed(scopedThreadKey(threadRef), viewedThrough);
+ if (!readEnvironmentSupportsViewState(threadRef.environmentId)) return;
+ const thread = readThreadShell(threadRef);
+ if (timestampCovers(thread?.viewedAt, viewedThrough)) return;
+ void viewThread({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId },
+ });
+ },
+ [markLocalViewed, viewThread],
+ );
+
+ const markUnread = useCallback(
+ (threadRef: ScopedThreadRef, latestTurnCompletedAt: string | null | undefined) => {
+ markLocalUnread(scopedThreadKey(threadRef), latestTurnCompletedAt);
+ if (
+ latestTurnCompletedAt == null ||
+ !readEnvironmentSupportsViewState(threadRef.environmentId)
+ ) {
+ return;
+ }
+ void markUnreadOnServer({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId },
+ });
+ },
+ [markLocalUnread, markUnreadOnServer],
+ );
+
+ return useMemo(() => ({ markViewed, markUnread }), [markUnread, markViewed]);
+}
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 7bca311823..7d1251686f 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -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 {
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index 0cb1650066..f0aded7d67 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -25,6 +25,8 @@ import {
archiveThread,
createProject,
settleThread,
+ viewThread,
+ markThreadUnread,
stopThreadSession,
unsettleThread,
} from "./commands.ts";
@@ -171,4 +173,33 @@ 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"),
+ }).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",
+ },
+ {
+ type: "thread.mark-unread",
+ commandId: "mark-unread-command",
+ threadId: "thread-1",
+ },
+ ]);
+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
+ );
});
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index cb74f117b7..332738d975 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -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) {
diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts
index ed3537e4f8..076f9d3c09 100644
--- a/packages/client-runtime/src/state/threadCommands.ts
+++ b/packages/client-runtime/src/state/threadCommands.ts
@@ -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(
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),
diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts
index 8b2479c7a3..6175ce3cb5 100644
--- a/packages/client-runtime/src/state/threadReducer.test.ts
+++ b/packages/client-runtime/src/state/threadReducer.test.ts
@@ -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";
diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts
index 970fd94b1a..a2e485cbc0 100644
--- a/packages/client-runtime/src/state/threadReducer.ts
+++ b/packages/client-runtime/src/state/threadReducer.ts
@@ -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",
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 1777bcebc2..f4ea963895 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -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),
diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts
index eba1b4648b..76a3650546 100644
--- a/packages/contracts/src/orchestration.test.ts
+++ b/packages/contracts/src/orchestration.test.ts
@@ -385,6 +385,24 @@ 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",
+ });
+ 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 +529,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({
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 35fef721ef..fc93f447fb 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -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,18 @@ const ThreadUnsettleCommand = Schema.Struct({
reason: Schema.Literal("user"),
});
+const ThreadViewCommand = Schema.Struct({
+ type: Schema.Literal("thread.view"),
+ commandId: CommandId,
+ threadId: ThreadId,
+});
+
+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 +920,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
+ ThreadViewCommand,
+ ThreadMarkUnreadCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadPinCommand,
@@ -933,6 +950,8 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
+ ThreadViewCommand,
+ ThreadMarkUnreadCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadPinCommand,
@@ -1051,6 +1070,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 +1172,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 +1403,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"),