Merge remote-tracking branch 'origin/main' into t3code/sidebar-work-overview

# Conflicts:
#	apps/server/src/environment/ServerEnvironment.ts
#	packages/contracts/src/environment.ts
This commit is contained in:
Theo Browne committed 2026-07-23 22:13:31 -07:00
commit b806ba34c2
65 files changed
+4047 -899

No files matched your search

+56 -4
View File
@@ -472,6 +472,10 @@ export function HomeScreen(props: HomeScreenProps) {
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
@@ -493,8 +497,18 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const snoozeEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSnooze === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
@@ -504,20 +518,38 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProjectGroup,
]);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
useEffect(() => {
if (nextSnoozeWakeAt === null) return;
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
if (Number.isNaN(wakeAtMs)) return;
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const threadListV2Items = threadListV2Layout.items;
const renderV2Item = useCallback(
@@ -813,11 +845,31 @@ export function HomeScreen(props: HomeScreenProps) {
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Pending tasks render in the header, so the
// list showing them isn't empty in the user's eyes.
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss. Pending tasks render in the header, so the list showing them
// isn't empty in the user's eyes.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
@@ -399,6 +399,10 @@ function ThreadNavigationSidebarPane(
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
@@ -420,8 +424,18 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const snoozeEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSnooze === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
@@ -429,20 +443,38 @@ function ThreadNavigationSidebarPane(
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Enabled,
threads,
selectedProjectScope,
]);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
useEffect(() => {
if (nextSnoozeWakeAt === null) return;
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
if (Number.isNaN(wakeAtMs)) return;
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
return () => clearTimeout(id);
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks render above the thread rows (mirrors the
@@ -930,15 +962,28 @@ function ThreadNavigationSidebarPane(
}),
[filterIcon, filterMenu, props.onOpenSettings],
);
// "No threads yet" over an inbox that is merely all-snoozed reads as
// data loss; name the snoozed threads instead.
const snoozedCount = threadListV2Layout.snoozedCount;
const listEmpty = (
<Text className="px-2 py-4 text-sm text-foreground-muted">
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? "No matching threads"
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
? snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
: `${snoozedCount} threads snoozed`
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
</Text>
);
@@ -77,6 +77,85 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("woken"),
title: "Woken",
// Wake time already passed: back in the active list.
snoozedUntil: "2026-06-01T18:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
// Same createdAt → static sort tiebreaks by id; the point is the woken
// thread is BACK in the card block and the snoozed one is gone.
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
expect(layout.snoozedCount).toBe(1);
});
it("classifies snooze with the second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("just-woke"),
title: "Just woke",
// Woke 30s ago: hidden under the minute-floored clock, visible
// under the precise one.
snoozedUntil: "2026-06-02T00:00:30.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("still-snoozed"),
title: "Still snoozed",
snoozedUntil: "2026-06-02T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
// Minute-floored partition clock vs precise snooze clock.
now: "2026-06-02T00:01:00.000Z",
snoozeNow: "2026-06-02T00:01:07.500Z",
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
expect(layout.snoozedCount).toBe(1);
expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
});
it("keeps snoozed threads visible on environments without the snooze capability", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("snoozed"),
title: "Snoozed",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
snoozeEnvironmentIds: new Set(),
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
expect(layout.snoozedCount).toBe(0);
});
it("partitions settled threads into a slim tail with one divider", () => {
const { items } = buildThreadListV2Items({
threads: [
@@ -1,4 +1,4 @@
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
@@ -84,6 +84,13 @@ export interface ThreadListV2Layout {
readonly items: ThreadListV2Item[];
/** Settled threads beyond the render limit (behind "Show more"). */
readonly hiddenSettledCount: number;
/** Snoozed threads hidden from the list (visibility parity with web's
collapsed Snoozed shelf; mobile has no shelf UI yet). */
readonly snoozedCount: number;
/** Soonest wake time among hidden snoozed threads, or null. Callers arm
a timeout at this boundary so the list re-partitions the moment a
snooze expires instead of on the next minute tick. */
readonly nextSnoozeWakeAt: string | null;
}
/**
@@ -106,13 +113,22 @@ export function buildThreadListV2Items(input: {
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
/** Environments whose server supports thread.snooze/unsnooze. Same
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
readonly now?: string;
/** Second-precise clock for snooze classification. Callers pass a
minute-quantized `now` for memoization; snooze wake times are
second-precise, so classifying with the floored minute would hold a
woken thread hidden for up to a minute. Defaults to `now`. */
readonly snoozeNow?: string;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
@@ -121,6 +137,8 @@ export function buildThreadListV2Items(input: {
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
let snoozedCount = 0;
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
// Callers pass live (unarchived) shells; settled threads are among them
// and partition into the tail via effectiveSettled.
@@ -130,8 +148,23 @@ export function buildThreadListV2Items(input: {
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: a snoozed thread leaves the list until it
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozedCount += 1;
if (
thread.snoozedUntil != null &&
(nextSnoozeWakeAt === null ||
parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
) {
nextSnoozeWakeAt = thread.snoozedUntil;
}
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
@@ -168,5 +201,10 @@ export function buildThreadListV2Items(input: {
if (last) {
items[items.length - 1] = { ...last, isLast: true };
}
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
return {
items,
hiddenSettledCount: orderedSettled.length - visibleSettled.length,
snoozedCount,
nextSnoozeWakeAt,
};
}
@@ -60,6 +60,8 @@ function threadDetailToShell(
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
settledAt: thread.settledAt,
snoozedUntil: thread.snoozedUntil ?? null,
snoozedAt: thread.snoozedAt ?? null,
session: thread.session,
latestUserMessageAt: latestUserMessageAt(thread),
hasPendingApprovals: false,
+2 -1
View File
@@ -31,7 +31,8 @@
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"node-pty": "^1.1.0"
"node-pty": "^1.1.0",
"yaml": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
@@ -141,6 +141,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
reviewSweep: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -679,6 +681,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.snoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
snoozedUntil: event.payload.snoozedUntil,
snoozedAt: event.payload.snoozedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unsnoozed": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
snoozedUntil: null,
snoozedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -310,6 +310,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [
{
@@ -422,6 +424,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
@@ -336,6 +336,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -366,6 +368,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -398,6 +402,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -762,6 +768,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -1196,6 +1204,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1396,6 +1406,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
deletedAt: row.deletedAt,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1527,6 +1539,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1663,6 +1677,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1905,6 +1921,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
@@ -2001,6 +2019,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
+4
View File
@@ -11,6 +11,8 @@ import {
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -38,6 +40,8 @@ export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSet
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -0,0 +1,286 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
type OrchestrationThread,
} 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 NOW = "2026-01-01T00:00:00.000Z";
// The decider's clock is the Effect test clock, pinned to the epoch, so
// "future" wake times are relative to 1970-01-01T00:00:00.000Z.
const FUTURE_WAKE = "1970-01-02T09:00:00.000Z";
const PAST_WAKE = "1969-12-31T09:00:00.000Z";
const SNOOZED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
readonly archivedAt?: string | null;
readonly activities?: OrchestrationThread["activities"];
readonly messages?: OrchestrationThread["messages"];
}): 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: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: null,
settledAt: null,
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
deletedAt: null,
messages: input.messages ?? [],
proposedPlans: [],
activities: input.activities ?? [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("snoozed thread decider", (it) => {
it.effect("snoozes a thread to a future wake time", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.snoozed");
if (events[0]?.type === "thread.snoozed") {
expect(events[0].payload.snoozedUntil).toBe(FUTURE_WAKE);
expect(events[0].payload.snoozedAt).toBe(events[0].payload.updatedAt);
}
}),
);
it.effect("rejects a wake time that is not in the future", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-past"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: PAST_WAKE,
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects an unparseable wake time", () =>
Effect.gen(function* () {
// IsoDateTime is structurally a string, so garbage can reach the
// decider; a NaN wake time must never persist as snooze state.
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-garbage"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: "not-a-date",
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects snoozing blocked-on-you work", () =>
Effect.gen(function* () {
const requestActivity = {
id: EventId.make("activity-req-1"),
tone: "approval" as const,
kind: "approval.requested",
summary: "approval.requested",
payload: { requestId: "req-1" },
turnId: null,
createdAt: NOW,
} as OrchestrationThread["activities"][number];
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-blocked"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ activities: [requestActivity] }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("re-emits idempotently for a duplicate snooze to the same wake time", () =>
Effect.gen(function* () {
const reEmit = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-again"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(reEmit) ? reEmit : [reEmit];
expect(events).toHaveLength(1);
if (events[0]?.type === "thread.snoozed") {
// Original snoozedAt preserved; updatedAt must not churn.
expect(events[0].payload.snoozedAt).toBe(SNOOZED_AT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("re-snoozing to a DIFFERENT wake time stamps fresh", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-extend"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: "1970-01-03T09:00:00.000Z",
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(event) ? event : [event];
if (events[0]?.type === "thread.snoozed") {
expect(events[0].payload.snoozedUntil).toBe("1970-01-03T09:00:00.000Z");
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("unsnoozes with reason user and re-emits idempotently when awake", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unsnooze",
commandId: CommandId.make("cmd-unsnooze"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unsnoozed");
if (events[0]?.type === "thread.unsnoozed") {
expect(events[0].payload.reason).toBe("user");
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
const awake = yield* decideOrchestrationCommand({
command: {
type: "thread.unsnooze",
commandId: CommandId.make("cmd-unsnooze-awake"),
threadId: ThreadId.make("thread-1"),
reason: "user",
},
readModel: makeReadModel({}),
});
const awakeEvents = Array.isArray(awake) ? awake : [awake];
expect(awakeEvents[0]?.type).toBe("thread.unsnoozed");
if (awakeEvents[0]?.type === "thread.unsnoozed") {
// No state change — keep the existing updatedAt.
expect(awakeEvents[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("rejects snoozing a thread with a queued turn start", () =>
Effect.gen(function* () {
// The decider clock is the Effect test clock pinned to the epoch: a
// user message 30s before it with no adopting turn is queued work.
const queuedMessage = {
id: MessageId.make("message-queued"),
role: "user",
text: "Continue",
turnId: null,
streaming: false,
createdAt: "1969-12-31T23:59:30.000Z",
updatedAt: "1969-12-31T23:59:30.000Z",
} as OrchestrationThread["messages"][number];
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-queued"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ messages: [queuedMessage] }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("rejects snoozing an archived thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.snooze",
commandId: CommandId.make("cmd-snooze-archived"),
threadId: ThreadId.make("thread-1"),
snoozedUntil: FUTURE_WAKE,
},
readModel: makeReadModel({ archivedAt: NOW }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("a user message spends the snooze return ticket (activity wake)", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "Continue",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: NOW,
},
readModel: makeReadModel({ snoozedUntil: FUTURE_WAKE }),
});
const events = Array.isArray(result) ? result : [result];
const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
expect(unsnoozed).toBeDefined();
if (unsnoozed?.type === "thread.unsnoozed") {
expect(unsnoozed.payload.reason).toBe("activity");
}
}),
);
});
+203 -58
View File
@@ -53,6 +53,13 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b
);
}
// Scans the read model's activities, which the projector caps at the most
// recent 500. That bound is safe here: an OPEN approval/user-input request
// blocks its turn, so the thread cannot accumulate hundreds of later
// activities while one is outstanding — a request that has scrolled out of
// the window is one whose turn kept running, i.e. it was resolved or went
// stale. (The projection pipeline's pendingApprovalCount reads the same
// capped stream and stays consistent with this view.)
function hasOpenBlockingRequest(thread: {
readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
}): boolean {
@@ -79,6 +86,62 @@ function hasOpenBlockingRequest(thread: {
return openRequestIds.size > 0;
}
/**
* A queued turn start — a user message no turn has picked up yet — is work
* in flight even though session is still null (turn.start emits
* message-sent + turn-start-requested; the session arrives later). Detection
* mirrors the client's hasQueuedTurnStart: the newest user message is
* strictly newer than every latestTurn timestamp (adoption stamps the new
* turn's requestedAt with the message time, clearing this), and only within
* the adoption grace window — historical threads whose last user message
* postdates their turn timestamps (older-server data, mid-turn messages)
* must not be blocked forever. A failed session start (status "error")
* clears the block immediately.
*
* The age check is bounded on BOTH sides: message timestamps are
* client-supplied, so a client clock ahead of the server yields a negative
* age. Without the lower bound that negative age satisfies `<= grace` for
* as long as the skew lasts, extending the block far past the intended two
* minutes.
*/
function threadHasQueuedTurnStart(
thread: {
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
readonly latestTurn: {
readonly requestedAt: string;
readonly startedAt: string | null;
readonly completedAt: string | null;
} | null;
readonly session: { readonly status: string } | null;
},
occurredAt: string,
): boolean {
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs =
thread.latestTurn === null
? Number.NEGATIVE_INFINITY
: Math.max(
...[
thread.latestTurn.requestedAt,
thread.latestTurn.startedAt,
thread.latestTurn.completedAt,
].map((candidate) =>
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
),
);
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
return (
thread.session?.status !== "error" &&
Number.isFinite(latestUserMessageAtMs) &&
latestUserMessageAtMs > latestTurnAtMs &&
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
);
}
function withEventBase(
input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -411,46 +474,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
);
}
const occurredAt = yield* nowIso;
// A queued turn start — a user message no turn has picked up yet — is
// work in flight even though session is still null (turn.start emits
// message-sent + turn-start-requested; the session arrives later).
// Settling in that window would hide just-requested work. Detection
// mirrors the client's hasQueuedTurnStart: the newest user message is
// strictly newer than every latestTurn timestamp (adoption stamps the
// new turn's requestedAt with the message time, clearing this), and
// only within the adoption grace window — historical threads whose
// last user message postdates their turn timestamps (older-server
// data, mid-turn messages) must stay settleable. A failed session
// start (status "error") clears the block immediately.
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs =
thread.latestTurn === null
? Number.NEGATIVE_INFINITY
: Math.max(
...[
thread.latestTurn.requestedAt,
thread.latestTurn.startedAt,
thread.latestTurn.completedAt,
].map((candidate) =>
candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
),
);
// The age check is bounded on BOTH sides: message timestamps are
// client-supplied, so a client clock ahead of the server yields a
// negative age. Without the lower bound that negative age satisfies
// `<= grace` for as long as the skew lasts, extending the settle
// block far past the intended two minutes.
const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
const hasQueuedTurnStart =
thread.session?.status !== "error" &&
Number.isFinite(latestUserMessageAtMs) &&
latestUserMessageAtMs > latestTurnAtMs &&
Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS;
if (hasQueuedTurnStart) {
// Settling inside the adoption window would hide just-requested work.
if (threadHasQueuedTurnStart(thread, occurredAt)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
@@ -508,6 +533,103 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.snooze": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
// A wake time in the past would create a thread that is snoozed and
// woken at once — the row would never leave the inbox but still carry
// snooze state. Reject instead of silently normalizing. The negated
// comparison also catches unparseable wake times (IsoDateTime is
// structurally just a string): NaN fails every comparison, and an
// unparseable snoozedUntil must never persist.
if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
}),
);
}
// Blocked-on-you work must not be snoozed away: a pending approval or
// user-input request is the agent waiting on the user, and hiding it
// defeats the request. (A running session IS snoozable — snooze only
// affects visibility, never the agent.)
if (hasOpenBlockingRequest(thread)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
}),
);
}
// A queued turn start — a user message no turn has adopted yet — is
// invisible pending work: no session, no pending flags. Snoozing in
// that window would hide a just-requested turn exactly the way settle
// would.
if (threadHasQueuedTurnStart(thread, occurredAt)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
}),
);
}
// Re-snoozing an already-snoozed thread to the SAME wake time is a
// duplicate (double-click, raced clients): re-emit with the original
// timestamps so the projection is a no-op. A different wake time is a
// real change and stamps fresh.
const existingSnoozedAt =
thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
? thread.snoozedAt
: null;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.snoozed",
payload: {
threadId: command.threadId,
snoozedUntil: command.snoozedUntil,
snoozedAt: existingSnoozedAt ?? occurredAt,
updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
},
};
}
case "thread.unsnooze": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): waking a thread that
// is not snoozed lands on the same null state without churning
// updatedAt.
const alreadyAwake = thread.snoozedUntil == null;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: command.reason,
updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -663,24 +785,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// Real activity resets ANY override: it wakes an explicitly settled
// thread, and it clears a keep-active pin back to neutral so the
// thread can auto-settle again after this burst of work goes stale.
if (targetThread.settledOverride === null) {
return [userMessageEvent, turnStartRequestedEvent];
// A snooze clears the same way — sending a message to a snoozed
// thread is the user re-engaging, so the return ticket is spent.
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (targetThread.settledOverride !== null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
};
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
if (targetThread.snoozedUntil != null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
}
case "thread.turn.interrupt": {
@@ -822,7 +962,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
// Only a session coming alive is activity worth waking a settled thread
// for — status writes like ready/stopped/error arrive after the fact and
// must not fight a user's explicit settle.
// must not fight a user's explicit settle. Snooze is deliberately NOT
// cleared here: snooze never pauses the agent, so its session starting
// or erroring is not the user re-engaging. Blocked/failed work still
// surfaces immediately — effectiveSnoozed refuses to classify a thread
// with a raised hand (approval / input / failure / fresh completion)
// as snoozed, without spending the return ticket.
const isSessionActivity =
command.session.status === "starting" || command.session.status === "running";
// Real activity resets ANY override (settled wakes, active unpins).
@@ -91,6 +91,8 @@ describe("orchestration projector", () => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -23,8 +23,10 @@ import {
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadSnoozedPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -290,6 +292,8 @@ export function projectEvent(
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -365,6 +369,30 @@ export function projectEvent(
})),
);
case "thread.snoozed":
return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
snoozedUntil: payload.snoozedUntil,
snoozedAt: payload.snoozedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unsnoozed":
return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
snoozedUntil: null,
snoozedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -93,6 +93,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -153,6 +155,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
archivedAt: null,
settledOverride: "settled",
settledAt: "2026-03-25T00:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -169,12 +173,17 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
}
assert.strictEqual(row.settledOverride, "settled");
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and confirm the flip persists.
// Un-settle to the keep-active pin and wake the snooze; confirm the
// flips persist.
yield* threads.upsert({
...row,
settledOverride: "active",
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
});
const repersisted = yield* threads.getById({
threadId: ThreadId.make("thread-settled"),
@@ -182,6 +191,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const updated = Option.getOrNull(repersisted);
assert.strictEqual(updated?.settledOverride, "active");
assert.strictEqual(updated?.settledAt, null);
assert.strictEqual(updated?.snoozedUntil, null);
assert.strictEqual(updated?.snoozedAt, null);
}),
);
});
@@ -45,6 +45,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at,
settled_override,
settled_at,
snoozed_until,
snoozed_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
@@ -66,6 +68,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.archivedAt},
${row.settledOverride},
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.latestUserMessageAt},
${row.pendingApprovalCount},
${row.pendingUserInputCount},
@@ -87,6 +91,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at = excluded.archived_at,
settled_override = excluded.settled_override,
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
latest_user_message_at = excluded.latest_user_message_at,
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
@@ -115,6 +121,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -145,6 +153,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -46,6 +46,7 @@ import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
/**
* Migration loader with all migrations defined inline.
@@ -91,6 +92,7 @@ export const migrationEntries = [
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -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 === "snoozed_until")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN snoozed_until TEXT
`;
}
if (!columns.some((column) => column.name === "snoozed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN snoozed_at TEXT
`;
}
});
@@ -38,6 +38,8 @@ export const ProjectionThread = Schema.Struct({
archivedAt: Schema.NullOr(IsoDateTime),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
@@ -118,6 +118,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { cwd } = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
@@ -165,9 +166,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
effectiveConfig,
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
processEnv,
cwd,
).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
@@ -0,0 +1,205 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
const writeSkill = Effect.fn(function* (
skillsDir: string,
directoryName: string,
contents: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const skillDir = path.join(skillsDir, directoryName);
yield* fs.makeDirectory(skillDir, { recursive: true });
yield* fs.writeFileString(path.join(skillDir, "SKILL.md"), contents);
});
it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => {
it.effect("discovers user and project skills with frontmatter metadata", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
yield* writeSkill(
path.join(configDir, "skills"),
"codex-review",
[
"---",
"name: codex-review",
"description: Ask Codex for a review.",
"---",
"",
"# Body",
].join("\n"),
);
yield* writeSkill(
path.join(workspace, ".claude", "skills"),
"deploy",
["---", "name: deploy", "description: Deploy the app.", "---", "", "# Deploy"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.deepEqual(skills, [
{
name: "codex-review",
path: path.join(configDir, "skills", "codex-review", "SKILL.md"),
enabled: true,
scope: "user",
description: "Ask Codex for a review.",
},
{
name: "deploy",
path: path.join(workspace, ".claude", "skills", "deploy", "SKILL.md"),
enabled: true,
scope: "project",
description: "Deploy the app.",
},
]);
}),
);
it.effect("prefers project skills over user skills on name collisions", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const workspace = path.join(tempDir, "workspace");
yield* writeSkill(
path.join(configDir, "skills"),
"deploy",
["---", "name: deploy", "description: User deploy.", "---"].join("\n"),
);
yield* writeSkill(
path.join(workspace, ".claude", "skills"),
"deploy",
["---", "name: deploy", "description: Project deploy.", "---"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace);
assert.equal(skills.length, 1);
assert.equal(skills[0]?.scope, "project");
assert.equal(skills[0]?.description, "Project deploy.");
}),
);
it.effect("falls back to the directory name and skips malformed frontmatter", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const configDir = path.join(tempDir, "claude-home");
const skillsDir = path.join(configDir, "skills");
yield* writeSkill(skillsDir, "no-frontmatter", "# Just a heading\n");
yield* writeSkill(skillsDir, "broken-yaml", "---\nname: [unclosed\n---\n");
// A stray file (not a directory with SKILL.md) must be skipped.
yield* fs.makeDirectory(skillsDir, { recursive: true });
yield* fs.writeFileString(path.join(skillsDir, "README.md"), "not a skill");
const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined);
// A skill with no frontmatter falls back to its directory name; a skill
// whose frontmatter fails to parse is skipped entirely (Claude Code
// won't load it either).
assert.deepEqual(
skills.map((skill) => skill.name),
["no-frontmatter"],
);
assert.equal(skills[0]?.description, undefined);
}),
);
it.effect("honors CLAUDE_CONFIG_DIR from the environment when homePath is unset", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const environmentConfigDir = path.join(tempDir, "env-config");
yield* writeSkill(
path.join(environmentConfigDir, "skills"),
"env-skill",
["---", "name: env-skill", "description: From env config dir.", "---"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: "" }, undefined, {
CLAUDE_CONFIG_DIR: environmentConfigDir,
});
assert.deepEqual(
skills.map((skill) => skill.name),
["env-skill"],
);
// An explicit homePath wins over the environment variable, matching
// makeClaudeEnvironment which overwrites CLAUDE_CONFIG_DIR for the CLI.
const explicitHome = path.join(tempDir, "explicit-home");
yield* writeSkill(
path.join(explicitHome, "skills"),
"explicit-skill",
["---", "name: explicit-skill", "---"].join("\n"),
);
const explicitSkills = yield* discoverClaudeSkills({ homePath: explicitHome }, undefined, {
CLAUDE_CONFIG_DIR: environmentConfigDir,
});
assert.deepEqual(
explicitSkills.map((skill) => skill.name),
["explicit-skill"],
);
}),
);
it.effect("resolves a relative CLAUDE_CONFIG_DIR against the workspace cwd", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const workspace = path.join(tempDir, "workspace");
yield* fs.makeDirectory(workspace, { recursive: true });
// The spawned CLI resolves a relative CLAUDE_CONFIG_DIR against its own
// cwd (the workspace), so discovery must do the same.
yield* writeSkill(
path.join(workspace, "relative-config", "skills"),
"relative-skill",
["---", "name: relative-skill", "---"].join("\n"),
);
const skills = yield* discoverClaudeSkills({ homePath: "" }, workspace, {
CLAUDE_CONFIG_DIR: "relative-config",
});
assert.deepEqual(
skills.map((skill) => skill.name),
["relative-skill"],
);
assert.equal(skills[0]?.scope, "user");
}),
);
it.effect("returns an empty list when no skill roots exist", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" });
const skills = yield* discoverClaudeSkills(
{ homePath: path.join(tempDir, "missing-home") },
path.join(tempDir, "missing-workspace"),
);
assert.deepEqual(skills, []);
}),
);
});
@@ -0,0 +1,148 @@
/**
* ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
*
* Claude Code loads skills from `<config dir>/skills` (user scope) and
* `<cwd>/.claude/skills` (project scope), one directory per skill with a
* `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces
* skills only as slash commands without their filesystem paths, so the
* provider snapshot scans the same locations directly, mirroring how the
* Codex app-server reports its skills.
*
* @module provider/Drivers/ClaudeSkills
*/
import * as NodeOS from "node:os";
import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { parse as parseYamlDocument } from "yaml";
import { expandHomePath } from "../../pathExpansion.ts";
type ClaudeSkillScope = "user" | "project";
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
type SkillFrontmatter =
| { readonly kind: "missing" }
| { readonly kind: "malformed" }
| { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
function parseSkillFrontmatter(contents: string): SkillFrontmatter {
const match = FRONTMATTER_PATTERN.exec(contents);
if (!match) {
return { kind: "missing" };
}
let parsed: unknown;
try {
parsed = parseYamlDocument(match[1] ?? "");
} catch {
return { kind: "malformed" };
}
if (typeof parsed !== "object" || parsed === null) {
return { kind: "malformed" };
}
const record = parsed as Record<string, unknown>;
const name = typeof record.name === "string" ? record.name.trim() : "";
const description = typeof record.description === "string" ? record.description.trim() : "";
return {
kind: "parsed",
...(name ? { name } : {}),
...(description ? { description } : {}),
};
}
/**
* Resolve the Claude config directory the CLI would use, matching the
* precedence the spawned CLI sees: the instance's `homePath` (exported as
* `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
* already present in the process environment, then `~/.claude`.
*/
const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
config: Pick<ClaudeSettings, "homePath">,
environment: NodeJS.ProcessEnv,
cwd?: string,
): Effect.fn.Return<string, never, Path.Path> {
const path = yield* Path.Path;
const homePath = config.homePath.trim();
if (homePath.length > 0) {
return path.resolve(expandHomePath(homePath));
}
// No tilde expansion here: the spawned CLI receives this env var verbatim
// (env vars are never shell-expanded), so a literal `~` must stay literal
// for discovery to scan the same directory the runtime would. A relative
// value is resolved against the workspace cwd — the subprocess's own cwd —
// for the same reason.
const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
if (environmentConfigDir.length > 0) {
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
}
return path.join(NodeOS.homedir(), ".claude");
});
/**
* Enumerate Claude Code skills from the user config dir and the workspace.
* Discovery is best-effort: unreadable roots and malformed skill entries are
* skipped so a broken skill never degrades the provider snapshot. On name
* collisions the project-scoped skill wins, matching Claude Code's
* most-specific-wins resolution.
*/
export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
config: Pick<ClaudeSettings, "homePath">,
cwd?: string,
environment?: NodeJS.ProcessEnv,
): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
{ directory: path.join(configDirPath, "skills"), scope: "user" },
...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
];
const skillsByName = new Map<string, ServerProviderSkill>();
for (const root of roots) {
const entries = yield* fileSystem
.readDirectory(root.directory)
.pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
for (const entry of [...entries].sort()) {
const skillPath = path.join(root.directory, entry, "SKILL.md");
const contents = yield* fileSystem
.readFileString(skillPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (contents === undefined) {
continue;
}
const frontmatter = parseSkillFrontmatter(contents);
// Malformed frontmatter means the skill won't load in Claude Code
// either — skip it rather than surfacing a broken entry under its
// directory name.
if (frontmatter.kind === "malformed") {
continue;
}
const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
if (!name) {
continue;
}
skillsByName.set(name, {
name,
path: skillPath,
enabled: true,
scope: root.scope,
...(frontmatter.kind === "parsed" && frontmatter.description
? { description: frontmatter.description }
: {}),
});
}
}
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
});
@@ -7,6 +7,7 @@ import {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
@@ -40,6 +41,7 @@ import {
} from "../providerSnapshot.ts";
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
@@ -732,10 +734,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings: ClaudeSettings,
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
environment?: NodeJS.ProcessEnv,
cwd?: string,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Path.Path
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const resolvedEnvironment = environment ?? process.env;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
@@ -845,6 +848,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
const slashCommands = capabilities?.slashCommands ?? [];
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
@@ -855,6 +859,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
checkedAt,
models,
slashCommands: dedupedSlashCommands,
skills,
probe: {
installed: true,
version: parsedVersion,
@@ -876,6 +881,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
checkedAt,
models,
slashCommands: dedupedSlashCommands,
skills,
probe: {
installed: true,
version: parsedVersion,
@@ -12,6 +12,8 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
@@ -19,6 +21,91 @@ import {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
describe("resolvePreviousWorktreeSeed", () => {
it("picks the most recently updated worktree thread", () => {
expect(
resolvePreviousWorktreeSeed({
threads: [
{
branch: "t3/older",
worktreePath: "/repo/.t3/worktrees/older",
updatedAt: "2026-07-20T00:00:00.000Z",
},
{
branch: "t3/newer",
worktreePath: "/repo/.t3/worktrees/newer",
updatedAt: "2026-07-22T00:00:00.000Z",
},
{ branch: "main", worktreePath: null, updatedAt: "2026-07-23T00:00:00.000Z" },
],
currentWorktreePath: null,
}),
).toEqual({ branch: "t3/newer", worktreePath: "/repo/.t3/worktrees/newer" });
});
it("skips the worktree the composer already points at", () => {
expect(
resolvePreviousWorktreeSeed({
threads: [
{
branch: "t3/current",
worktreePath: "/repo/.t3/worktrees/current",
updatedAt: "2026-07-22T00:00:00.000Z",
},
],
currentWorktreePath: "/repo/.t3/worktrees/current",
}),
).toBeNull();
});
it("returns null when no thread has a worktree", () => {
expect(
resolvePreviousWorktreeSeed({
threads: [{ branch: "main", worktreePath: null, updatedAt: "2026-07-22T00:00:00.000Z" }],
currentWorktreePath: null,
}),
).toBeNull();
});
it("ignores archived threads and threads with unparseable timestamps", () => {
expect(
resolvePreviousWorktreeSeed({
threads: [
{
branch: "t3/archived",
worktreePath: "/repo/.t3/worktrees/archived",
updatedAt: "2026-07-23T00:00:00.000Z",
archivedAt: "2026-07-23T01:00:00.000Z",
},
{
branch: "t3/garbage-timestamp",
worktreePath: "/repo/.t3/worktrees/garbage",
updatedAt: "not-a-date",
},
{
branch: "t3/live",
worktreePath: "/repo/.t3/worktrees/live",
updatedAt: "2026-07-21T00:00:00.000Z",
archivedAt: null,
},
],
currentWorktreePath: null,
}),
).toEqual({ branch: "t3/live", worktreePath: "/repo/.t3/worktrees/live" });
});
});
describe("resolvePreviousWorktreeLabel", () => {
it("includes the branch when known", () => {
expect(resolvePreviousWorktreeLabel({ branch: "t3/fix-thing", worktreePath: "/wt" })).toBe(
"Previous worktree (t3/fix-thing)",
);
expect(resolvePreviousWorktreeLabel({ branch: null, worktreePath: "/wt" })).toBe(
"Previous worktree",
);
});
});
describe("resolveDraftEnvModeAfterBranchChange", () => {
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
expect(
@@ -1,5 +1,6 @@
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { toSortableTimestamp } from "../lib/threadSort";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
@@ -65,6 +66,53 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null):
return activeWorktreePath ? "Worktree" : "Local checkout";
}
export interface PreviousWorktreeSeed {
branch: string | null;
worktreePath: string;
}
// The most recently touched worktree in the project that the composer isn't
// already pointing at. Backs the "Previous worktree" entry in the workspace
// selector so a follow-up thread can hop back into the worktree you just
// worked in without hunting for its branch. Archived threads don't compete —
// the rest of the UI hides them, so their worktrees shouldn't resurface here.
export function resolvePreviousWorktreeSeed(input: {
threads: ReadonlyArray<{
branch: string | null;
worktreePath: string | null;
updatedAt: string;
archivedAt?: string | null;
}>;
currentWorktreePath: string | null;
}): PreviousWorktreeSeed | null {
let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
for (const thread of input.threads) {
if (
!thread.worktreePath ||
thread.worktreePath === input.currentWorktreePath ||
(thread.archivedAt ?? null) !== null
) {
continue;
}
const updatedAt = toSortableTimestamp(thread.updatedAt);
if (updatedAt === null) {
continue;
}
if (latest === null || updatedAt > latest.updatedAt) {
latest = {
branch: thread.branch,
worktreePath: thread.worktreePath,
updatedAt,
};
}
}
return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
}
export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
}
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
hasServerThread: boolean;
+63 -3
View File
@@ -6,12 +6,13 @@ import {
FolderGit2Icon,
FolderGitIcon,
FolderIcon,
HistoryIcon,
MonitorIcon,
} from "lucide-react";
import { memo, useMemo } from "react";
import { memo, useCallback, useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useProject, useThread } from "../state/entities";
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
import { useIsMobile } from "../hooks/useMediaQuery";
import {
type EnvMode,
@@ -20,6 +21,8 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
@@ -66,6 +69,8 @@ interface MobileRunContextSelectorProps {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
onEnvModeChange: (mode: EnvMode) => void;
previousWorktreeLabel: string | null;
onUsePreviousWorktree: () => void;
}
const MobileRunContextSelector = memo(function MobileRunContextSelector({
@@ -79,6 +84,8 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
effectiveEnvMode,
activeWorktreePath,
onEnvModeChange,
previousWorktreeLabel,
onUsePreviousWorktree,
}: MobileRunContextSelectorProps) {
const activeEnvironment = useMemo(
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
@@ -166,7 +173,13 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<MenuGroupLabel>Workspace</MenuGroupLabel>
<MenuRadioGroup
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
onValueChange={(value) => {
if (value === "previous-worktree") {
onUsePreviousWorktree();
return;
}
onEnvModeChange(value as EnvMode);
}}
>
<MenuRadioItem disabled={envModeLocked} value="local">
<span className="flex min-w-0 items-center gap-1.5">
@@ -186,6 +199,14 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
</span>
</MenuRadioItem>
{previousWorktreeLabel ? (
<MenuRadioItem disabled={envModeLocked} value="previous-worktree">
<span className="flex min-w-0 items-center gap-1.5">
<HistoryIcon className="size-3" />
<span className="min-w-0 truncate">{previousWorktreeLabel}</span>
</span>
</MenuRadioItem>
) : null}
</MenuRadioGroup>
</MenuGroup>
</MenuPopup>
@@ -217,6 +238,7 @@ export const BranchToolbar = memo(function BranchToolbar({
const draftThread = useComposerDraftStore((store) =>
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const activeProjectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
: draftThread
@@ -234,6 +256,40 @@ export const BranchToolbar = memo(function BranchToolbar({
});
const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
// "Previous worktree" hops a draft into the most recently active worktree
// of this project — the "keep going where I just was" follow-up flow. Only
// drafts can hop; started server threads have their workspace pinned.
const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked;
const projectRefsForWorktreeLookup = useMemo(
() => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
[canUsePreviousWorktree, activeProjectRef],
);
const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
const previousWorktreeSeed = useMemo(
() =>
canUsePreviousWorktree
? resolvePreviousWorktreeSeed({
threads: projectThreads,
currentWorktreePath: activeWorktreePath,
})
: null,
[activeWorktreePath, canUsePreviousWorktree, projectThreads],
);
const previousWorktreeLabel = previousWorktreeSeed
? resolvePreviousWorktreeLabel(previousWorktreeSeed)
: null;
const onUsePreviousWorktree = useCallback(() => {
if (!previousWorktreeSeed || !activeProjectRef) return;
// Same shape the branch selector writes when picking a branch that
// already lives in a worktree: point the draft at the existing tree.
setDraftThreadContext(draftId ?? threadRef, {
branch: previousWorktreeSeed.branch,
worktreePath: previousWorktreeSeed.worktreePath,
envMode: "worktree",
projectRef: activeProjectRef,
});
}, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
@@ -261,6 +317,8 @@ export const BranchToolbar = memo(function BranchToolbar({
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
@@ -280,6 +338,8 @@ export const BranchToolbar = memo(function BranchToolbar({
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
</div>
)}
@@ -1,4 +1,4 @@
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
import { memo, useMemo } from "react";
import {
@@ -17,11 +17,15 @@ import {
SelectValue,
} from "./ui/select";
export const PREVIOUS_WORKTREE_SELECT_VALUE = "previous-worktree";
interface BranchToolbarEnvModeSelectorProps {
envLocked: boolean;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
onEnvModeChange: (mode: EnvMode) => void;
previousWorktreeLabel?: string | null;
onUsePreviousWorktree?: () => void;
}
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
@@ -29,13 +33,19 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
effectiveEnvMode,
activeWorktreePath,
onEnvModeChange,
previousWorktreeLabel,
onUsePreviousWorktree,
}: BranchToolbarEnvModeSelectorProps) {
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
const envModeItems = useMemo(
() => [
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
...(showPreviousWorktree && previousWorktreeLabel
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
: []),
],
[activeWorktreePath],
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
);
if (envLocked) {
@@ -60,7 +70,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
<Select
modal={false}
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
onValueChange={(value: string | null) => {
if (value === PREVIOUS_WORKTREE_SELECT_VALUE) {
onUsePreviousWorktree?.();
return;
}
onEnvModeChange(value as EnvMode);
}}
items={envModeItems}
>
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
@@ -92,6 +108,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
{resolveEnvModeLabel("worktree")}
</span>
</SelectItem>
{showPreviousWorktree && previousWorktreeLabel ? (
<SelectItem value={PREVIOUS_WORKTREE_SELECT_VALUE}>
<span className="inline-flex items-center gap-1.5">
<HistoryIcon className="size-3" />
{previousWorktreeLabel}
</span>
</SelectItem>
) : null}
</SelectGroup>
</SelectPopup>
</Select>
@@ -12,16 +12,20 @@ import type { Thread } from "../types";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
branchMismatchKey,
buildExpiredTerminalContextToastCopy,
buildThreadTurnInterruptInput,
createLocalDispatchSnapshot,
deriveComposerSendState,
dismissBranchMismatchForSession,
getStartedThreadModelChangeBlockReason,
hasServerAcknowledgedLocalDispatch,
isBranchMismatchDismissedForSession,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
shouldShowBranchMismatchBanner,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -292,6 +296,61 @@ describe("resolveSendEnvMode", () => {
});
});
describe("branchMismatchKey", () => {
it("builds a key from thread id and both branches", () => {
expect(branchMismatchKey("thread-1", { threadBranch: "feat/a", currentBranch: "feat/b" })).toBe(
"thread-1:feat/a:feat/b",
);
});
it("returns null without a thread or mismatch", () => {
expect(branchMismatchKey(null, { threadBranch: "a", currentBranch: "b" })).toBeNull();
expect(branchMismatchKey("thread-1", null)).toBeNull();
});
});
describe("shouldShowBranchMismatchBanner", () => {
const base = {
hasMismatch: true,
isDismissed: false,
composerHasContent: false,
wasShownForCurrentMismatch: false,
};
it("stays hidden during passive browsing (even though the composer autofocuses)", () => {
expect(shouldShowBranchMismatchBanner(base)).toBe(false);
});
it("shows once the composer has draft content", () => {
expect(shouldShowBranchMismatchBanner({ ...base, composerHasContent: true })).toBe(true);
});
it("stays mounted after the draft clears once shown for the current mismatch", () => {
expect(shouldShowBranchMismatchBanner({ ...base, wasShownForCurrentMismatch: true })).toBe(
true,
);
});
it("never shows when dismissed or without a mismatch", () => {
expect(
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, isDismissed: true }),
).toBe(false);
expect(
shouldShowBranchMismatchBanner({ ...base, composerHasContent: true, hasMismatch: false }),
).toBe(false);
});
});
describe("session branch mismatch dismissal", () => {
it("tracks dismissed keys and treats other keys as active", () => {
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
dismissBranchMismatchForSession("t1:a:b");
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(true);
expect(isBranchMismatchDismissedForSession("t1:a:c")).toBe(false);
expect(isBranchMismatchDismissedForSession(null)).toBe(false);
});
});
describe("reconcileMountedTerminalThreadIds", () => {
it("keeps open threads and makes the active thread most recent", () => {
expect(
+40
View File
@@ -289,6 +289,46 @@ export function buildExpiredTerminalContextToastCopy(
};
}
export function branchMismatchKey(
threadId: string | null,
mismatch: { threadBranch: string; currentBranch: string } | null,
): string | null {
if (!threadId || !mismatch) {
return null;
}
return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
}
// The mismatch banner only matters when the user is about to send: passive
// reading of an old thread carries no risk (the branch picker tint already
// covers ambient awareness). Draft content is the intent signal — composer
// focus is useless here because ChatView autofocuses the composer on every
// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
// revealed so it doesn't flicker away when the draft is cleared.
export function shouldShowBranchMismatchBanner(input: {
hasMismatch: boolean;
isDismissed: boolean;
composerHasContent: boolean;
wasShownForCurrentMismatch: boolean;
}): boolean {
if (!input.hasMismatch || input.isDismissed) {
return false;
}
return input.composerHasContent || input.wasShownForCurrentMismatch;
}
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
// changes). Durable cross-device dismissal is planned as a server-side ack.
const sessionDismissedBranchMismatchKeys = new Set<string>();
export function dismissBranchMismatchForSession(key: string): void {
sessionDismissedBranchMismatchKeys.add(key);
}
export function isBranchMismatchDismissedForSession(key: string | null): boolean {
return key !== null && sessionDismissedBranchMismatchKeys.has(key);
}
export function threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
+298 -87
View File
@@ -25,6 +25,7 @@ import {
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
parseScopedThreadKey,
scopedThreadKey,
@@ -138,7 +139,14 @@ import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
import {
AlarmClockIcon,
CheckCircle2Icon,
ChevronDownIcon,
GitBranchIcon,
TriangleAlertIcon,
WifiOffIcon,
} from "lucide-react";
import { cn, randomHex } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -153,7 +161,8 @@ import {
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
import { useEnvironmentSettings } from "../hooks/useSettings";
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
import { useNowMinute } from "../hooks/useNowMinute";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
@@ -202,6 +211,7 @@ import {
useThread,
useThreadProposedPlans,
useThreadRefs,
useThreadShell,
} from "../state/entities";
import { environmentShell } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -220,6 +230,7 @@ import {
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
@@ -231,13 +242,17 @@ import {
} from "./chat/draftHeroTransition";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
branchMismatchKey,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildThreadTurnInterruptInput,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
dismissBranchMismatchForSession,
hasServerAcknowledgedLocalDispatch,
isBranchMismatchDismissedForSession,
shouldShowBranchMismatchBanner,
getStartedThreadModelChangeBlockReason,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
@@ -260,6 +275,16 @@ import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { Button } from "./ui/button";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ServerUpdateAction } from "./ServerUpdateAction";
import {
buildVersionMismatchDismissalKey,
@@ -3809,52 +3834,159 @@ function ChatViewContent(props: ChatViewProps) {
: null,
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
);
const [branchRepairAction, setBranchRepairAction] = useState<
"update-thread" | "switch-checkout" | null
>(null);
const handleUpdateThreadToCheckout = useCallback(async () => {
if (!activeThread || !localCheckoutBranchMismatch || branchRepairAction !== null) {
return;
}
setBranchRepairAction("update-thread");
const updateResult = await updateThreadMetadata({
environmentId,
input: {
threadId: activeThread.id,
branch: localCheckoutBranchMismatch.currentBranch,
worktreePath: null,
},
// Settled state of the open thread, resolved exactly like the sidebar
// partition (same shell, same capability gate, same PR auto-settle input)
// so the banner and the sidebar row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const activeThreadPr = resolveThreadPr({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
});
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
const activeThreadSnoozed =
activeThreadShell !== null &&
supportsSnooze &&
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
void snoozeWakeTick;
if (!activeThreadSnoozed) return;
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
if (!Number.isFinite(wakeAtMs)) return;
const id = window.setTimeout(
() => bumpSnoozeWakeTick((tick) => tick + 1),
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
);
return () => window.clearTimeout(id);
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
const activeThreadSettled = useMemo(() => {
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
changeRequestState: activeThreadPr?.state ?? null,
});
setBranchRepairAction(null);
if (updateResult._tag === "Failure" && !isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to update thread branch",
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
}),
);
return;
}
scheduleComposerFocus();
}, [
activeThread,
branchRepairAction,
environmentId,
localCheckoutBranchMismatch,
scheduleComposerFocus,
updateThreadMetadata,
activeThreadPr?.state,
activeThreadShell,
autoSettleAfterDays,
nowMinute,
supportsSettlement,
]);
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
// Keyed by thread, not a boolean: the pending state must follow the thread
// it belongs to across navigation, and a request resolving for thread A
// must never clear (or re-enable) thread B's button.
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
const handleUnsettleActiveThread = useCallback(async () => {
if (!activeThreadRef) return;
const threadKey = scopedThreadKey(activeThreadRef);
setUnsettlingThreadKey(threadKey);
try {
const result = await unsettleThreadMutation({
environmentId: activeThreadRef.environmentId,
input: { threadId: activeThreadRef.threadId, reason: "user" },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to un-settle thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
} finally {
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
}
}, [activeThreadRef, unsettleThreadMutation]);
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
const handleUnsnoozeActiveThread = useCallback(async () => {
if (!activeThreadRef) return;
const threadKey = scopedThreadKey(activeThreadRef);
setUnsnoozingThreadKey(threadKey);
try {
const result = await unsnoozeThreadMutation({
environmentId: activeThreadRef.environmentId,
input: { threadId: activeThreadRef.threadId, reason: "user" },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to wake thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
} finally {
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
}
}, [activeThreadRef, unsnoozeThreadMutation]);
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
// Once revealed for a given mismatch, the banner stays mounted until the
// mismatch changes or resolves, so clearing the draft doesn't flicker it.
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
// Dismissal lives in a module-level set (survives remounts); this tick just
// forces a re-render so the banner leaves immediately.
const [, setBranchMismatchDismissTick] = useState(0);
const composerHasDraftContent = useComposerDraftStore((store) => {
const draft = store.getComposerDraft(composerDraftTarget);
return Boolean(
draft &&
(draft.prompt.trim().length > 0 ||
draft.images.length > 0 ||
draft.terminalContexts.length > 0 ||
draft.elementContexts.length > 0 ||
draft.previewAnnotations.length > 0 ||
draft.reviewComments.length > 0),
);
});
const activeBranchMismatchKey = branchMismatchKey(
activeThread?.id ?? null,
localCheckoutBranchMismatch,
);
const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
hasMismatch: localCheckoutBranchMismatch !== null,
isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
composerHasContent: composerHasDraftContent,
wasShownForCurrentMismatch:
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
});
useEffect(() => {
setRevealedBranchMismatchKey((revealed) => {
if (showBranchMismatchBanner) {
return activeBranchMismatchKey;
}
// Hysteresis is scoped to an uninterrupted mismatch: reset when the
// mismatch resolves or changes so a recurrence re-gates on intent.
return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
});
}, [activeBranchMismatchKey, showBranchMismatchBanner]);
const handleSwitchCheckoutToThread = useCallback(async () => {
if (
!activeProjectCwd ||
!activeThread ||
!localCheckoutBranchMismatch ||
branchRepairAction !== null
isRestoringThreadBranch
) {
return;
}
setBranchRepairAction("switch-checkout");
setIsRestoringThreadBranch(true);
const checkoutResult = await switchGitRef({
environmentId,
input: {
@@ -3863,7 +3995,7 @@ function ChatViewContent(props: ChatViewProps) {
},
});
if (checkoutResult._tag === "Failure") {
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
if (!isAtomCommandInterrupted(checkoutResult)) {
toastManager.add(
stackedThreadToast({
@@ -3883,7 +4015,7 @@ function ChatViewContent(props: ChatViewProps) {
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
});
if (updateResult._tag === "Failure") {
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
if (!isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
@@ -3898,76 +4030,125 @@ function ChatViewContent(props: ChatViewProps) {
}
}
gitStatusQuery.refresh();
setBranchRepairAction(null);
setIsRestoringThreadBranch(false);
scheduleComposerFocus();
}, [
activeProjectCwd,
activeThread,
branchRepairAction,
environmentId,
gitStatusQuery,
isRestoringThreadBranch,
localCheckoutBranchMismatch,
scheduleComposerFocus,
switchGitRef,
updateThreadMetadata,
]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
if (!localCheckoutBranchMismatch) {
return systemComposerBannerItems;
// The stack renders items[0] front-most and tucks the rest behind hover, so
// ordering is priority: system banners, then the branch-mismatch notice,
// and the informational parked-thread banner last — it must never cover another.
const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
if (!activeThreadSnoozed && !activeThreadSettled) {
return null;
}
const isSnoozed = activeThreadSnoozed;
return {
id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,
variant: "info",
icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,
title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,
description: isSnoozed
? "Sending a message wakes it and moves it back to Active in the sidebar."
: "Sending a message moves it back to Active in the sidebar.",
actions: (
<Button
size="xs"
variant="outline"
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
onClick={() =>
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
}
>
{isSnoozed
? isUnsnoozing
? "Waking..."
: "Wake now"
: isUnsettling
? "Un-settling..."
: "Un-settle"}
</Button>
),
};
}, [
activeThread?.id,
activeThreadSettled,
activeThreadSnoozed,
handleUnsnoozeActiveThread,
handleUnsettleActiveThread,
isUnsnoozing,
isUnsettling,
]);
const handleRestoreThreadBranch = useCallback(() => {
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
setBranchRestoreConfirmOpen(true);
return;
}
void handleSwitchCheckoutToThread();
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
return [...systemComposerBannerItems, ...parkedThreadItems];
}
const isRepairingBranch = branchRepairAction !== null;
return [
...systemComposerBannerItems,
{
id: `branch-mismatch:${activeThread?.id ?? "unknown"}:${localCheckoutBranchMismatch.threadBranch}:${localCheckoutBranchMismatch.currentBranch}`,
variant: "warning",
icon: <TriangleAlertIcon />,
title: "You're on a different branch",
className:
"text-base sm:text-sm [&>div]:items-start max-sm:[&>div]:flex-wrap max-sm:[&>div>div:last-child]:w-full max-sm:[&>div>div:last-child]:self-start dark:shadow-none",
actionClassName:
"max-sm:w-full max-sm:border-t max-sm:border-border/60 max-sm:pt-2 max-sm:pl-6 sm:border-l sm:border-border/60 sm:pl-3",
description: (
<p className="text-pretty">
This thread is on{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.threadBranch}
</code>
, but you're currently checked out at{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.currentBranch}
</code>
. Sending a message will update the thread.
</p>
id: `branch-mismatch:${activeBranchMismatchKey}`,
variant: "info",
icon: <GitBranchIcon />,
title: (
<span className="flex min-w-0 items-baseline gap-1.5">
<span className="shrink-0 font-normal text-muted-foreground">Branch changed — was</span>
<Tooltip>
<TooltipTrigger
render={
<code className="min-w-0 truncate font-medium text-foreground">
{localCheckoutBranchMismatch.threadBranch}
</code>
}
/>
<TooltipPopup side="top" className="max-w-80">
This thread last ran on {localCheckoutBranchMismatch.threadBranch}. Sending will
continue on {localCheckoutBranchMismatch.currentBranch}.
</TooltipPopup>
</Tooltip>
</span>
),
className: "dark:shadow-none",
actions: (
<>
<Button
size="xs"
variant="outline"
disabled={isRepairingBranch}
onClick={() => void handleUpdateThreadToCheckout()}
>
{branchRepairAction === "update-thread" ? "Moving..." : "Move thread here"}
</Button>
<Button
size="xs"
variant="ghost"
disabled={isRepairingBranch}
onClick={() => void handleSwitchCheckoutToThread()}
>
{branchRepairAction === "switch-checkout" ? "Switching..." : "Checkout thread branch"}
</Button>
</>
<Button
size="xs"
variant="ghost"
disabled={isRestoringThreadBranch}
onClick={handleRestoreThreadBranch}
>
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
</Button>
),
dismissLabel: "Dismiss branch change notice",
onDismiss: () => {
dismissBranchMismatchForSession(activeBranchMismatchKey);
setBranchMismatchDismissTick((tick) => tick + 1);
},
},
...parkedThreadItems,
];
}, [
activeThread?.id,
branchRepairAction,
handleSwitchCheckoutToThread,
handleUpdateThreadToCheckout,
activeBranchMismatchKey,
handleRestoreThreadBranch,
isRestoringThreadBranch,
localCheckoutBranchMismatch,
parkedThreadBannerItem,
showBranchMismatchBanner,
systemComposerBannerItems,
]);
@@ -5726,6 +5907,36 @@ function ChatViewContent(props: ChatViewProps) {
</div>
</div>
<AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>
Switch to{" "}
<code className="font-medium">
{localCheckoutBranchMismatch?.threadBranch ?? ""}
</code>
?
</AlertDialogTitle>
<AlertDialogDescription>
You have uncommitted changes. They'll carry over to the other branch, or block
the switch if they conflict.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="default"
onClick={() => {
setBranchRestoreConfirmOpen(false);
void handleSwitchCheckoutToThread();
}}
>
Switch branch
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
{pullRequestDialogState ? (
<PullRequestThreadDialog
key={pullRequestDialogState.key}
+3 -21
View File
@@ -58,11 +58,7 @@ import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import {
resolveThreadActionProjectRef,
startNewThreadInProjectFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
canNavigateUp,
@@ -837,13 +833,7 @@ function OpenCommandPaletteDialog(props: {
projectRef.environmentId === contextualProjectRef.environmentId &&
projectRef.projectId === contextualProjectRef.projectId,
);
await startNewThreadInProjectFromContext(
{
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
},
await handleNewThread(
contextualRefBelongsToGroup
? contextualProjectRef
: scopeProjectRef(project.environmentId, project.id),
@@ -851,15 +841,7 @@ function OpenCommandPaletteDialog(props: {
},
}),
),
[
activeDraftThread,
activeThread,
contextualProjectRef,
defaultProjectRef,
handleNewThread,
pickerProjects,
projectGroupByTargetKey,
],
[contextualProjectRef, handleNewThread, pickerProjects, projectGroupByTargetKey],
);
const allThreadItems = useMemo(
@@ -14,8 +14,6 @@ import {
isTrailingDoubleClick,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarV2Status,
@@ -371,112 +369,6 @@ describe("isTrailingDoubleClick", () => {
});
});
describe("resolveSidebarNewThreadEnvMode", () => {
it("uses the app default when the caller does not request a specific mode", () => {
expect(
resolveSidebarNewThreadEnvMode({
defaultEnvMode: "worktree",
}),
).toBe("worktree");
});
it("preserves an explicit requested mode over the app default", () => {
expect(
resolveSidebarNewThreadEnvMode({
requestedEnvMode: "local",
defaultEnvMode: "worktree",
}),
).toBe("local");
});
});
describe("resolveSidebarNewThreadSeedContext", () => {
it("prefers the default worktree mode over active thread context", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "worktree",
activeThread: {
projectId: "project-1",
branch: "feature/existing",
worktreePath: "/repo/.t3/worktrees/existing",
},
activeDraftThread: {
projectId: "project-1",
branch: "feature/draft",
worktreePath: "/repo/.t3/worktrees/draft",
envMode: "worktree",
startFromOrigin: true,
},
}),
).toEqual({
envMode: "worktree",
});
});
it("inherits the active server thread context when creating a new thread in the same project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
branch: "effect-atom",
worktreePath: null,
envMode: "local",
});
});
it("prefers the active draft thread context when it matches the target project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: {
projectId: "project-1",
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
startFromOrigin: true,
},
}),
).toEqual({
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
startFromOrigin: true,
});
});
it("falls back to the default env mode when there is no matching active thread context", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-2",
defaultEnvMode: "worktree",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
envMode: "worktree",
});
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
-57
View File
@@ -18,7 +18,6 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
title: string;
@@ -246,62 +245,6 @@ export function isTrailingDoubleClick(detail: number): boolean {
return detail > 1;
}
export function resolveSidebarNewThreadEnvMode(input: {
requestedEnvMode?: SidebarNewThreadEnvMode;
defaultEnvMode: SidebarNewThreadEnvMode;
}): SidebarNewThreadEnvMode {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function resolveSidebarNewThreadSeedContext(input: {
projectId: string;
defaultEnvMode: SidebarNewThreadEnvMode;
activeThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
} | null;
activeDraftThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
envMode: SidebarNewThreadEnvMode;
startFromOrigin: boolean;
} | null;
}): {
branch?: string | null;
worktreePath?: string | null;
envMode: SidebarNewThreadEnvMode;
startFromOrigin?: boolean;
} {
if (input.defaultEnvMode === "worktree") {
return {
envMode: "worktree",
};
}
if (input.activeDraftThread?.projectId === input.projectId) {
return {
branch: input.activeDraftThread.branch,
worktreePath: input.activeDraftThread.worktreePath,
envMode: input.activeDraftThread.envMode,
startFromOrigin: input.activeDraftThread.startFromOrigin,
};
}
if (input.activeThread?.projectId === input.projectId) {
return {
branch: input.activeThread.branch,
worktreePath: input.activeThread.worktreePath,
envMode: input.activeThread.worktreePath ? "worktree" : "local",
};
}
return {
envMode: input.defaultEnvMode,
};
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveSnoozePresets, snoozeWakeDescription, snoozeWakeLabel } from "./Sidebar.snooze";
// Local-time constructor so preset math is timezone-stable in tests.
function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
return new Date(year, month - 1, day, hour, minute, 0, 0);
}
describe("resolveSnoozePresets", () => {
it("offers hour, evening, tomorrow, next week in the morning", () => {
// Wednesday 2026-04-08 10:00 local.
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
expect(presets.map((preset) => preset.id)).toEqual([
"hour",
"evening",
"tomorrow",
"next-week",
]);
const evening = presets.find((preset) => preset.id === "evening");
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
const tomorrowDate = new Date(tomorrow!.snoozedUntil);
expect(tomorrowDate.getDate()).toBe(9);
expect(tomorrowDate.getHours()).toBe(9);
const nextWeek = presets.find((preset) => preset.id === "next-week");
const nextWeekDate = new Date(nextWeek!.snoozedUntil);
expect(nextWeekDate.getDay()).toBe(1);
expect(nextWeekDate.getDate()).toBe(13);
});
it("whenLabel complements the label instead of repeating it", () => {
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10));
for (const preset of presets) {
// Day words live in the label column; the time column is time-only
// (plus a weekday for next week, which names a different day).
expect(preset.whenLabel.toLowerCase()).not.toContain("tomorrow");
}
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
expect(tomorrow!.whenLabel).toMatch(/9/);
const nextWeek = presets.find((preset) => preset.id === "next-week");
expect(nextWeek!.whenLabel).toMatch(/Mon/);
});
it("drops the evening preset once evening is near or past", () => {
expect(resolveSnoozePresets(localDate(2026, 4, 8, 17, 30)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
expect(resolveSnoozePresets(localDate(2026, 4, 8, 21)).map((preset) => preset.id)).toEqual([
"hour",
"tomorrow",
"next-week",
]);
});
it("puts next week a full week out when today is Monday", () => {
// Monday 2026-04-06.
const presets = resolveSnoozePresets(localDate(2026, 4, 6, 10));
const nextWeek = new Date(presets.find((preset) => preset.id === "next-week")!.snoozedUntil);
expect(nextWeek.getDay()).toBe(1);
expect(nextWeek.getDate()).toBe(13);
});
});
describe("snoozeWakeLabel", () => {
const now = localDate(2026, 4, 8, 10);
it("formats minutes, hours, and days, rounding up", () => {
expect(snoozeWakeLabel(new Date(now.getTime() + 30 * 60_000).toISOString(), now)).toBe("30m");
expect(snoozeWakeLabel(new Date(now.getTime() + 90 * 60_000).toISOString(), now)).toBe("2h");
expect(snoozeWakeLabel(new Date(now.getTime() + 26 * 3_600_000).toISOString(), now)).toBe("2d");
});
it("reports now for past and malformed wake times", () => {
expect(snoozeWakeLabel(new Date(now.getTime() - 1000).toISOString(), now)).toBe("now");
expect(snoozeWakeLabel("not-a-date", now)).toBe("now");
});
});
describe("snoozeWakeDescription", () => {
const now = localDate(2026, 4, 8, 10);
it("uses bare time today, 'tomorrow' next day, weekday within the week", () => {
expect(snoozeWakeDescription(localDate(2026, 4, 8, 18).toISOString(), now)).not.toContain(
"tomorrow",
);
expect(snoozeWakeDescription(localDate(2026, 4, 9, 9).toISOString(), now)).toContain(
"tomorrow",
);
expect(snoozeWakeDescription(localDate(2026, 4, 13, 9).toISOString(), now)).toMatch(/Mon/);
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* Snooze preset resolution for the sidebar snooze menu. Pure functions so
* the preset math (evening/tomorrow/next-week boundaries) is unit-testable
* without a DOM.
*
* Presets deliberately skew short: agent-thread rhythms are hours (a CI
* run, a teammate review, the next work session), not days.
*/
import { parseTimestampDate } from "../timestampFormat";
type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
export interface SnoozePreset {
readonly id: SnoozePresetId;
readonly label: string;
/** Menu-row time column. Complements the label instead of repeating it:
"Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
readonly whenLabel: string;
/** ISO wake time. */
readonly snoozedUntil: string;
}
function timeOfDayLabel(date: Date): string {
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
}
const EVENING_HOUR = 18;
const MORNING_HOUR = 9;
const HOUR_MS = 60 * 60 * 1_000;
const DAY_MS = 24 * HOUR_MS;
function atHour(base: Date, hour: number): Date {
const next = new Date(base);
next.setHours(hour, 0, 0, 0);
return next;
}
// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
// land on the wrong local day across DST transitions (a spring-forward day
// is 23 hours, so 23:30 + 24h skips the whole next day).
function addDays(base: Date, days: number): Date {
const next = new Date(base);
next.setDate(next.getDate() + days);
return next;
}
/**
* Presets for "snooze until", computed against local time. "This evening"
* only appears while it is still meaningfully before evening; after that
* the list starts at "Tomorrow".
*/
export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
const inAnHour = new Date(now.getTime() + HOUR_MS);
const presets: SnoozePreset[] = [
{
id: "hour",
label: "In 1 hour",
whenLabel: timeOfDayLabel(inAnHour),
snoozedUntil: inAnHour.toISOString(),
},
];
const evening = atHour(now, EVENING_HOUR);
// Suppress the evening preset once it is within an hour (or past): it
// would duplicate "In 1 hour" or point at the past.
if (evening.getTime() - now.getTime() > HOUR_MS) {
presets.push({
id: "evening",
label: "This evening",
whenLabel: timeOfDayLabel(evening),
snoozedUntil: evening.toISOString(),
});
}
const tomorrow = atHour(addDays(now, 1), MORNING_HOUR);
presets.push({
id: "tomorrow",
label: "Tomorrow",
whenLabel: timeOfDayLabel(tomorrow),
snoozedUntil: tomorrow.toISOString(),
});
// Next Monday 9:00 (a week out when today is Monday).
const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
const nextWeek = atHour(addDays(now, daysUntilMonday), MORNING_HOUR);
presets.push({
id: "next-week",
label: "Next week",
whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${timeOfDayLabel(nextWeek)}`,
snoozedUntil: nextWeek.toISOString(),
});
return presets;
}
/**
* Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
* round up so a snooze never reads "0m" while still hidden.
*/
export function snoozeWakeLabel(snoozedUntil: string, now: Date): string {
const wake = parseTimestampDate(snoozedUntil);
if (wake === null) return "now";
const remainingMs = wake.getTime() - now.getTime();
if (remainingMs <= 0) return "now";
if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
return `${Math.ceil(remainingMs / DAY_MS)}d`;
}
/**
* Human wake time for menus and toasts: "tomorrow 9:00", "Mon 9:00",
* "17:30" (today).
*/
export function snoozeWakeDescription(snoozedUntil: string, now: Date): string {
const wake = parseTimestampDate(snoozedUntil);
if (wake === null) return "";
const time = wake.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
const startOfToday = new Date(now);
startOfToday.setHours(0, 0, 0, 0);
const dayDelta = Math.floor((wake.getTime() - startOfToday.getTime()) / DAY_MS);
if (dayDelta === 0) return time;
if (dayDelta === 1) return `tomorrow ${time}`;
const weekday = wake.toLocaleDateString(undefined, { weekday: "short" });
if (dayDelta < 7) return `${weekday} ${time}`;
const date = wake.toLocaleDateString(undefined, { month: "short", day: "numeric" });
return `${date}, ${time}`;
}
+33 -55
View File
@@ -177,8 +177,6 @@ import {
isContextMenuPointerDown,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -193,7 +191,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
import { primaryServerKeybindingsAtom } from "../state/server";
import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
@@ -1103,7 +1101,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
(settings) => settings.confirmThreadArchive,
);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const deleteProject = useAtomCommand(projectEnvironment.delete, {
reportFailure: false,
});
@@ -1875,61 +1872,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const createThreadForProjectMember = useCallback(
(member: SidebarProjectGroupMember) => {
const currentRouteParams =
router.state.matches[router.state.matches.length - 1]?.params ?? {};
const currentRouteTarget = resolveThreadRouteTarget(currentRouteParams);
const currentActiveThread =
currentRouteTarget?.kind === "server"
? readThreadShell(currentRouteTarget.threadRef)
: null;
const draftStore = useComposerDraftStore.getState();
const currentActiveDraftThread =
currentRouteTarget?.kind === "server"
? (draftStore.getDraftThread(currentRouteTarget.threadRef) ?? null)
: currentRouteTarget?.kind === "draft"
? (draftStore.getDraftSession(currentRouteTarget.draftId) ?? null)
: null;
const seedContext = resolveSidebarNewThreadSeedContext({
projectId: member.id,
// The default env mode is a user preference stored on the primary
// environment's settings.json; remote environments never carry it.
defaultEnvMode: resolveSidebarNewThreadEnvMode({
defaultEnvMode: primaryServerSettings.defaultThreadEnvMode,
}),
activeThread:
currentActiveThread && currentActiveThread.projectId === member.id
? {
projectId: currentActiveThread.projectId,
branch: currentActiveThread.branch,
worktreePath: currentActiveThread.worktreePath,
}
: null,
activeDraftThread:
currentActiveDraftThread && currentActiveDraftThread.projectId === member.id
? {
projectId: currentActiveDraftThread.projectId,
branch: currentActiveDraftThread.branch,
worktreePath: currentActiveDraftThread.worktreePath,
envMode: currentActiveDraftThread.envMode,
startFromOrigin: currentActiveDraftThread.startFromOrigin,
}
: null,
});
if (isMobile) {
setOpenMobile(false);
}
void (async () => {
// No options: branch, worktree, and env mode come from the user's
// configured defaults, never from the currently viewed thread.
const result = await settlePromise(() =>
handleNewThread(scopeProjectRef(member.environmentId, member.id), {
...(seedContext.branch !== undefined ? { branch: seedContext.branch } : {}),
...(seedContext.worktreePath !== undefined
? { worktreePath: seedContext.worktreePath }
: {}),
envMode: seedContext.envMode,
...(seedContext.startFromOrigin !== undefined
? { startFromOrigin: seedContext.startFromOrigin }
: {}),
}),
handleNewThread(scopeProjectRef(member.environmentId, member.id)),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
@@ -1943,7 +1893,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
})();
},
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
[handleNewThread, isMobile, setOpenMobile],
);
const handleCreateThreadClick = useCallback(
@@ -2164,6 +2114,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
const clicked = await api.contextMenu.show(
[
...(thread.branch
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
@@ -2173,6 +2126,30 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
position,
);
if (clicked === "new-thread-on-branch") {
// Explicit branch carry-over: reuse the thread's worktree when it
// has one, otherwise its branch on the local checkout.
const result = await settlePromise(() =>
handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
branch: thread.branch,
worktreePath: thread.worktreePath,
envMode: thread.worktreePath ? "worktree" : "local",
startFromOrigin: false,
}),
);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not create thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
if (clicked === "rename") {
startThreadRename(threadKey, thread.title);
return;
@@ -2229,6 +2206,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyPathToClipboard,
copyThreadIdToClipboard,
deleteThread,
handleNewThread,
markThreadUnread,
memberProjectByScopedKey,
project.workspaceRoot,
File diff suppressed because it is too large. Load diff
@@ -10,23 +10,86 @@ describe("ChangedFilesCard", () => {
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
expanded
showCompactPreview={false}
allDirectoriesExpanded
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('class="sticky top-0 z-10');
expect(markup).not.toContain("self-start");
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all"');
expect(markup).toContain('aria-label="View diff"');
expect(markup).toContain('aria-label="Collapse all folders"');
expect(markup).toContain('aria-label="Open diff"');
expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
expect(markup).toContain("1 changed file");
expect(markup).not.toContain("1 changed files");
});
it("renders a scope and representative-file preview for a large latest change", () => {
const markup = renderToStaticMarkup(
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
{
path: "packages/shared/src/git.ts",
kind: "modified",
additions: 15,
deletions: 4,
},
{ path: "README.md", kind: "modified", additions: 3, deletions: 0 },
]}
expanded={false}
showCompactPreview
allDirectoriesExpanded={false}
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('data-changed-files-state="preview"');
expect(markup).toContain('aria-expanded="false"');
expect(markup).toContain("apps");
expect(markup).toContain("2 files");
expect(markup).toContain("packages");
expect(markup).toContain("root");
expect(markup).toContain("App.tsx");
expect(markup).toContain("git.ts");
expect(markup).toContain("README.md");
expect(markup).toContain("Show all 4 files");
expect(markup).not.toContain("App.test.tsx");
});
it("keeps older collapsed changes to a one-line receipt", () => {
const markup = renderToStaticMarkup(
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
expanded={false}
showCompactPreview={false}
allDirectoriesExpanded={false}
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('data-changed-files-state="collapsed"');
expect(markup).toContain("1 changed file");
expect(markup).not.toContain("Show all");
expect(markup).not.toContain("App.tsx");
});
});
describe("ChangedFilesTree", () => {
+139 -50
View File
@@ -19,95 +19,184 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { PierreEntryIcon } from "./PierreEntryIcon";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
changedFileName,
selectChangedFilePreview,
summarizeChangedFileScopes,
} from "./changedFilesPresentation";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
expanded: boolean;
showCompactPreview: boolean;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onExpandedChange: (expanded: boolean) => void;
onToggleAllDirectories: () => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const {
turnId,
files,
expanded,
showCompactPreview,
allDirectoriesExpanded,
resolvedTheme,
onExpandedChange,
onToggleAllDirectories,
onOpenTurnDiff,
} = props;
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
const compactPreviewVisible = showCompactPreview && !expanded;
return (
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
<div
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
data-changed-files-state={
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
}
>
<div
className={cn(
"flex items-center justify-between gap-2 rounded-xl px-1",
expanded &&
"sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
)}
>
<button
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(!expanded)}
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0 text-muted-foreground transition-transform",
expanded && "rotate-90",
)}
/>
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
{expanded ? "Hide files" : "Show files"}
</span>
</button>
<div className="flex items-center gap-1.5">
{expanded ? (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label={
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
}
data-scroll-anchor-ignore
onClick={onToggleAllDirectories}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
size="xs"
variant="outline"
className="!size-[22px]"
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
data-scroll-anchor-ignore
onClick={onToggleAllDirectories}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label="View diff"
aria-label="Open diff"
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
{expanded ? (
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
) : compactPreviewVisible ? (
<div className="px-2 pb-1.5 pt-1">
<p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
{scopeSummary.map((scope, index) => (
<span key={scope.label} className="inline-flex items-center gap-1">
{index > 0 ? <span aria-hidden="true">·</span> : null}
<span className="font-mono text-foreground/75">{scope.label}</span>
<span>
{scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
</span>
</span>
))}
</p>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{previewFiles.map((file) => (
<button
key={file.path}
type="button"
title={file.path}
className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onOpenTurnDiff(turnId, file.path)}
>
<PierreEntryIcon
pathValue={file.path}
kind="file"
theme={resolvedTheme}
className="size-3 shrink-0 text-muted-foreground/70"
/>
<span className="truncate">{changedFileName(file.path)}</span>
</button>
))}
<button
type="button"
className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(true)}
>
Show all {files.length} files
</button>
</div>
</div>
) : null}
</div>
);
});
@@ -31,6 +31,8 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span
role="group"
aria-label={`${additions} additions, ${deletions} deletions`}
className={cn(
layout === "inline"
? "inline-flex items-center gap-1 tabular-nums align-middle"
@@ -38,8 +40,12 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
className,
)}
>
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
<span aria-hidden="true" className="font-mono text-success">
+{formatCompactDiffCount(additions)}
</span>
<span aria-hidden="true" className="font-mono text-destructive">
-{formatCompactDiffCount(deletions)}
</span>
</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
@@ -245,6 +245,12 @@ describe("MessagesTimeline", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
latestTurn={{
turnId,
state: "completed",
startedAt: MESSAGE_CREATED_AT,
completedAt: MESSAGE_CREATED_AT,
}}
timelineEntries={[
{
id: "entry-assistant-with-files",
@@ -280,13 +286,13 @@ describe("MessagesTimeline", () => {
/>,
);
expect(markup).toContain('class="sticky top-2 z-10');
expect(markup).toContain("sticky top-2 z-10");
expect(markup).not.toContain("self-start");
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all"');
expect(markup).toContain('aria-label="View diff"');
expect(markup).toContain('aria-label="Collapse all folders"');
expect(markup).toContain('aria-label="Open diff"');
expect(markup).toContain("1 changed file");
});
@@ -32,7 +32,6 @@ import {
workLogEntryIsToolLike,
} from "../../session-logic";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -44,11 +43,8 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -65,8 +61,8 @@ import {
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
@@ -145,6 +141,7 @@ interface TimelineRowActivityState {
isWorking: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
latestTurnId: TurnId | null;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
@@ -454,8 +451,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
isRevertingCheckpoint,
activeTurnInProgress,
latestTurnId: latestTurn?.turnId ?? null,
}),
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
);
// Stable renderItem — no closure deps. Row components read shared state
@@ -1278,83 +1276,32 @@ function AssistantChangedFilesSectionInner({
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const allDirectoriesExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
const activity = use(TimelineRowActivityCtx);
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
const persistedExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const [autoExpanded] = useState(() =>
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
);
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
return (
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<div className="flex items-center gap-1.5">
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
data-scroll-anchor-ignore
onClick={() =>
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label="View diff"
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
<ChangedFilesCard
turnId={turnSummary.turnId}
files={checkpointFiles}
expanded={expanded}
showCompactPreview={isLatestTurn}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onExpandedChange={(nextExpanded) =>
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
}
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
onOpenTurnDiff={onOpenTurnDiff}
/>
);
}
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vite-plus/test";
import {
changedFileName,
selectChangedFilePreview,
shouldAutoExpandChangedFiles,
summarizeChangedFileScopes,
} from "./changedFilesPresentation";
describe("changed-files presentation", () => {
it("auto-expands only small, low-churn latest changes", () => {
const smallFiles = [
{ path: "src/a.ts", kind: "modified", additions: 80, deletions: 20 },
{ path: "src/b.ts", kind: "modified", additions: 60, deletions: 20 },
];
expect(shouldAutoExpandChangedFiles(smallFiles, true)).toBe(true);
expect(shouldAutoExpandChangedFiles(smallFiles, false)).toBe(false);
expect(
shouldAutoExpandChangedFiles(
[{ path: "src/a.ts", kind: "modified", additions: 201, deletions: 0 }],
true,
),
).toBe(false);
expect(
shouldAutoExpandChangedFiles(
Array.from({ length: 6 }, (_, index) => ({
path: `src/${index}.ts`,
kind: "modified",
additions: 1,
deletions: 0,
})),
true,
),
).toBe(false);
});
it("summarizes the most prominent top-level scopes", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/server/src/index.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps\\mobile\\App.tsx", kind: "modified", additions: 1, deletions: 0 },
];
expect(summarizeChangedFileScopes(files)).toEqual([
{ label: "apps", fileCount: 3 },
{ label: "root", fileCount: 1 },
{ label: "packages", fileCount: 1 },
]);
});
it("previews files across different scopes before filling from one scope", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
];
expect(selectChangedFilePreview(files).map((file) => file.path)).toEqual([
"apps/web/src/App.tsx",
"packages/shared/src/git.ts",
"README.md",
]);
expect(changedFileName("apps\\web\\src\\App.tsx")).toBe("App.tsx");
});
});
@@ -0,0 +1,102 @@
import { type TurnDiffFileChange } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
export interface ChangedFilesScopeSummary {
readonly label: string;
readonly fileCount: number;
}
function pathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
export function changedFileName(pathValue: string): string {
return pathSegments(pathValue).at(-1) ?? pathValue;
}
function changedFileScope(pathValue: string): string {
const segments = pathSegments(pathValue);
return segments.length > 1 ? (segments[0] ?? "root") : "root";
}
export function shouldAutoExpandChangedFiles(
files: ReadonlyArray<TurnDiffFileChange>,
isLatestTurn: boolean,
): boolean {
if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
return false;
}
const stat = summarizeTurnDiffStats(files);
return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
}
export function summarizeChangedFileScopes(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
): ChangedFilesScopeSummary[] {
const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
files.forEach((file, index) => {
const label = changedFileScope(file.path);
const current = scopes.get(label);
scopes.set(label, {
fileCount: (current?.fileCount ?? 0) + 1,
firstIndex: current?.firstIndex ?? index,
});
});
return Array.from(scopes, ([label, scope]) => ({
label,
fileCount: scope.fileCount,
firstIndex: scope.firstIndex,
}))
.toSorted(
(left, right) =>
right.fileCount - left.fileCount ||
left.firstIndex - right.firstIndex ||
left.label.localeCompare(right.label),
)
.slice(0, limit)
.map(({ label, fileCount }) => ({ label, fileCount }));
}
export function selectChangedFilePreview(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
): TurnDiffFileChange[] {
const selected: TurnDiffFileChange[] = [];
const selectedPaths = new Set<string>();
const selectedScopes = new Set<string>();
for (const file of files) {
const scope = changedFileScope(file.path);
if (selectedScopes.has(scope)) {
continue;
}
selected.push(file);
selectedPaths.add(file.path);
selectedScopes.add(scope);
if (selected.length === limit) {
return selected;
}
}
for (const file of files) {
if (selectedPaths.has(file.path)) {
continue;
}
selected.push(file);
if (selected.length === limit) {
break;
}
}
return selected;
}
+14 -3
View File
@@ -406,6 +406,15 @@ interface ComposerDraftStoreState {
setModelSelection: (
threadRef: ComposerThreadTarget,
modelSelection: ModelSelection | null | undefined,
opts?: {
/**
* Replace the stored entry outright instead of preserving its
* existing options when the incoming selection has none. Used when
* the selection is a complete snapshot (e.g. carried from another
* thread) rather than a model-only change.
*/
replaceOptions?: boolean;
},
) => void;
/** Replace the model options for one or more providers in the draft. */
setModelOptions: (
@@ -2594,7 +2603,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
setModelSelection: (threadRef, modelSelection) => {
setModelSelection: (threadRef, modelSelection, opts) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0) {
return;
@@ -2609,8 +2618,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const nextMap = { ...base.modelSelectionByProvider };
if (normalized) {
const current = nextMap[normalized.instanceId];
if (normalized.options !== undefined) {
// Explicit options provided → use them
if (normalized.options !== undefined || opts?.replaceOptions) {
// Explicit options provided (or the caller passed a complete
// snapshot whose absent options mean "no options") → use the
// selection as-is.
nextMap[normalized.instanceId] = normalized as ModelSelection;
} else {
// No options in selection → preserve existing options, update provider+model
+100 -8
View File
@@ -54,14 +54,52 @@ export function useNewThreadHandler() {
},
): Promise<void> => {
const {
getComposerDraft,
getDraftSessionByLogicalProjectKey,
getDraftSession,
getDraftThread,
applyStickyState,
setDraftThreadContext,
setLogicalProjectDraftThreadId,
setModelSelection,
} = useComposerDraftStore.getState();
const currentRouteTarget = getCurrentRouteTarget();
// A new thread carries the user's *working mode* from the thread being
// viewed: model (including options like reasoning effort and context
// window), permission mode, and interaction mode. Branch, worktree, and
// env mode never carry implicitly — those come from the configured
// defaults unless the caller passes them explicitly.
const carrySourceShell =
currentRouteTarget?.kind === "server"
? readThreadShell(currentRouteTarget.threadRef)
: null;
const carrySourceDraft =
currentRouteTarget?.kind === "draft" ? getDraftSession(currentRouteTarget.draftId) : null;
// Composer overrides win over the persisted thread state — they are
// what the user currently sees in the composer controls.
const carrySourceComposer = currentRouteTarget
? getComposerDraft(
currentRouteTarget.kind === "server"
? currentRouteTarget.threadRef
: currentRouteTarget.draftId,
)
: null;
const composerActiveProvider = carrySourceComposer?.activeProvider ?? null;
const composerModelSelection = composerActiveProvider
? (carrySourceComposer?.modelSelectionByProvider[composerActiveProvider] ?? null)
: null;
const carryModelSelection =
composerModelSelection ?? carrySourceShell?.modelSelection ?? null;
const carryRuntimeMode =
carrySourceComposer?.runtimeMode ??
carrySourceShell?.runtimeMode ??
carrySourceDraft?.runtimeMode ??
null;
const carryInteractionMode =
carrySourceComposer?.interactionMode ??
carrySourceShell?.interactionMode ??
carrySourceDraft?.interactionMode ??
null;
const project = projects.find(
(candidate) =>
candidate.id === projectRef.projectId &&
@@ -92,25 +130,70 @@ export function useNewThreadHandler() {
: null;
if (reusableStoredDraftThread) {
return (async () => {
if (
const isDraftAlreadyOpen =
currentRouteTarget?.kind === "draft" &&
currentRouteTarget.draftId === reusableStoredDraftThread.draftId;
const hasExplicitWorkspaceOption =
hasBranchOption ||
hasWorktreePathOption ||
hasEnvModeOption ||
hasStartFromOriginOption
) {
hasStartFromOriginOption;
// Resurrecting a stored draft must not resurrect its stale context:
// explicit workspace options win outright; otherwise the env context
// resets to the configured defaults so drafts seeded before a
// defaults change (or by the old carry-over behavior) stop landing
// on "current checkout" branches forever. Composer text is
// preserved. When the draft is already open and no options were
// passed, leave it alone entirely — the user may have just picked a
// branch in the composer.
const defaultEnvMode = primaryServerSettings.defaultThreadEnvMode;
const workspaceContext = hasExplicitWorkspaceOption
? {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
}
: isDraftAlreadyOpen
? null
: {
branch: null,
worktreePath: null,
envMode: defaultEnvMode,
startFromOrigin: resolveNewDraftStartFromOrigin({
envMode: defaultEnvMode,
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
}),
};
if (workspaceContext) {
setDraftThreadContext(reusableStoredDraftThread.draftId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
...workspaceContext,
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
});
if (carryModelSelection) {
// The carried selection is a complete snapshot of the viewed
// thread's model state: absent options mean "no options", not
// "keep the stale draft's options".
setModelSelection(reusableStoredDraftThread.draftId, carryModelSelection, {
replaceOptions: true,
});
}
}
// The workspace context must also ride along here: when projectRef
// targets a different physical member of the logical project,
// createDraftThreadState treats the remap as a project change and
// would otherwise wipe branch/worktree and force "local" mode,
// undoing the write above.
setLogicalProjectDraftThreadId(
logicalProjectKey,
projectRef,
reusableStoredDraftThread.draftId,
{
threadId: reusableStoredDraftThread.threadId,
...(workspaceContext ?? {}),
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
},
);
if (
@@ -176,9 +259,18 @@ export function useNewThreadHandler() {
envMode: initialEnvMode,
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
}),
runtimeMode: DEFAULT_RUNTIME_MODE,
runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
});
applyStickyState(draftId);
if (carryModelSelection) {
// After sticky state so the viewed thread's exact selection
// (model + options like effort and context window) wins over the
// globally sticky one. replaceOptions: the carried selection is a
// complete snapshot — absent options mean "no options", not "keep
// whatever sticky state just wrote".
setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
}
await router.navigate({
to: "/draft/$draftId",
+69
View File
@@ -0,0 +1,69 @@
import { useSyncExternalStore } from "react";
/** Minute-quantized clock ("YYYY-MM-DDTHH:MM") for settled-state resolution.
One module-level timer feeds every consumer through useSyncExternalStore,
so all surfaces resolving effectiveSettled against it (sidebar partition,
composer banner) share a single value by construction and tick on UTC
minute boundaries together. */
function currentMinute(): string {
return new Date().toISOString().slice(0, 16);
}
let nowMinute = currentMinute();
let timerId: number | null = null;
let timerIsInterval = false;
const listeners = new Set<() => void>();
function tick(): void {
const next = currentMinute();
if (next !== nowMinute) {
nowMinute = next;
for (const listener of listeners) listener();
}
}
function startTimer(): void {
// Align to the next UTC minute boundary, then tick every 60s. Ticks re-read
// the clock, so a throttled or late timer self-corrects when it fires.
timerIsInterval = false;
timerId = window.setTimeout(
() => {
tick();
timerIsInterval = true;
timerId = window.setInterval(tick, 60_000);
},
60_000 - (Date.now() % 60_000),
);
}
function subscribe(listener: () => void): () => void {
if (listeners.size === 0) {
startTimer();
}
listeners.add(listener);
return () => {
listeners.delete(listener);
if (listeners.size === 0 && timerId !== null) {
if (timerIsInterval) window.clearInterval(timerId);
else window.clearTimeout(timerId);
timerId = null;
}
};
}
function getSnapshot(): string {
// With no timer running (no subscribers yet — e.g. the first render after
// a full unmount), the stored minute may be stale; re-read it so a fresh
// mount renders the current minute instead of waiting for the first tick.
// While the timer runs the cached value is returned untouched, as
// useSyncExternalStore requires between change notifications.
if (timerId === null) {
nowMinute = currentMinute();
}
return nowMinute;
}
export function useNowMinute(): string {
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
+91 -1
View File
@@ -4,7 +4,7 @@ import {
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
@@ -22,6 +22,7 @@ import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsStat
import { readLocalApi } from "../localApi";
import {
readEnvironmentSupportsSettlement,
readEnvironmentSupportsSnooze,
readEnvironmentThreadRefs,
readProject,
readThreadShell,
@@ -69,6 +70,30 @@ export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSett
}
}
export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
"ThreadSnoozeUnsupportedError",
{
environmentId: EnvironmentId,
threadId: ThreadId,
},
) {
override get message(): string {
return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
}
}
export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
"ThreadSnoozeBlockedError",
{
environmentId: EnvironmentId,
threadId: ThreadId,
},
) {
override get message(): string {
return "This thread is waiting on you. Respond to the pending request before snoozing it.";
}
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
@@ -86,6 +111,12 @@ export function useThreadActions() {
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
reportFailure: false,
});
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
@@ -441,6 +472,61 @@ export function useThreadActions() {
[unsettleThreadMutation],
);
const snoozeThread = useCallback(
async (target: ScopedThreadRef, snoozedUntil: string) => {
// Version skew: never send the command to a server that predates it.
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
return AsyncResult.failure(
Cause.fail(
new ThreadSnoozeUnsupportedError({
environmentId: target.environmentId,
threadId: target.threadId,
}),
),
);
}
const resolved = resolveThreadTarget(target);
// Blocked-on-you work and queued turns can't be snoozed away —
// client-side twin of the server invariants so the UI rejects before
// a round trip.
if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
return AsyncResult.failure(
Cause.fail(
new ThreadSnoozeBlockedError({
environmentId: resolved.threadRef.environmentId,
threadId: resolved.threadRef.threadId,
}),
),
);
}
return snoozeThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId, snoozedUntil },
});
},
[resolveThreadTarget, snoozeThreadMutation],
);
const unsnoozeThread = useCallback(
async (target: ScopedThreadRef) => {
if (!readEnvironmentSupportsSnooze(target.environmentId)) {
return AsyncResult.failure(
Cause.fail(
new ThreadSnoozeUnsupportedError({
environmentId: target.environmentId,
threadId: target.threadId,
}),
),
);
}
return unsnoozeThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId, reason: "user" },
});
},
[unsnoozeThreadMutation],
);
const confirmAndDeleteThread = useCallback(
async (target: ScopedThreadRef) => {
const localApi = readLocalApi();
@@ -477,14 +563,18 @@ export function useThreadActions() {
confirmAndDeleteThread,
settleThread,
unsettleThread,
snoozeThread,
unsnoozeThread,
}),
[
archiveThread,
confirmAndDeleteThread,
deleteThread,
settleThread,
snoozeThread,
unarchiveThread,
unsettleThread,
unsnoozeThread,
],
);
}
+15 -76
View File
@@ -4,9 +4,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
import {
resolveThreadActionProjectRef,
resolveNewDraftStartFromOrigin,
startNewLocalThreadFromContext,
startNewThreadFromContext,
startNewThreadInProjectFromContext,
type ChatThreadActionContext,
} from "./chatThreadActions";
@@ -40,16 +38,25 @@ describe("chatThreadActions", () => {
).toBe(false);
});
it("prefers the active draft thread project when resolving thread actions", () => {
it("prefers the active thread project when resolving thread actions", () => {
const projectRef = resolveThreadActionProjectRef(
createContext({
activeThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
},
}),
);
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
});
it("falls back to the active draft thread project when there is no active thread", () => {
const projectRef = resolveThreadActionProjectRef(
createContext({
activeDraftThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
envMode: "worktree",
startFromOrigin: true,
},
}),
);
@@ -67,85 +74,17 @@ describe("chatThreadActions", () => {
expect(projectRef).toEqual(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID));
});
it("starts a contextual new thread from the active draft thread", async () => {
it("inherits only the project from context, never branch or worktree state", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
const didStart = await startNewThreadFromContext(
createContext({
activeDraftThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
envMode: "worktree",
startFromOrigin: true,
},
handleNewThread,
}),
);
expect(didStart).toBe(true);
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
envMode: "worktree",
startFromOrigin: true,
});
});
it("preserves an explicitly disabled origin base in contextual thread options", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
await startNewThreadFromContext(
createContext({
activeDraftThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
envMode: "worktree",
startFromOrigin: false,
},
handleNewThread,
}),
);
expect(handleNewThread).toHaveBeenCalledWith(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), {
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
envMode: "worktree",
startFromOrigin: false,
});
});
it("does not carry branch or worktree context into a different project", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
const targetProjectRef = scopeProjectRef(ENVIRONMENT_ID, FALLBACK_PROJECT_ID);
await startNewThreadInProjectFromContext(
createContext({
activeThread: {
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
branch: "feature/refactor",
worktreePath: "/tmp/worktree",
},
handleNewThread,
}),
targetProjectRef,
);
expect(handleNewThread).toHaveBeenCalledWith(targetProjectRef);
});
it("delegates the target environment defaults to the new-thread handler", async () => {
const handleNewThread = vi.fn<ChatThreadActionContext["handleNewThread"]>(async () => {});
const didStart = await startNewLocalThreadFromContext(
createContext({
defaultProjectRef: scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID),
handleNewThread,
}),
);
expect(didStart).toBe(true);
+7 -51
View File
@@ -5,13 +5,6 @@ import type { DraftThreadEnvMode } from "../composerDraftStore";
interface ThreadContextLike {
environmentId: EnvironmentId;
projectId: ProjectId;
branch: string | null;
worktreePath: string | null;
}
interface DraftThreadContextLike extends ThreadContextLike {
envMode: DraftThreadEnvMode;
startFromOrigin: boolean;
}
interface NewThreadHandler {
@@ -26,10 +19,8 @@ interface NewThreadHandler {
): Promise<void>;
}
type NewThreadOptions = NonNullable<Parameters<NewThreadHandler>[1]>;
export interface ChatThreadActionContext {
readonly activeDraftThread: DraftThreadContextLike | null;
readonly activeDraftThread: ThreadContextLike | null;
readonly activeThread: ThreadContextLike | undefined;
readonly defaultProjectRef: ScopedProjectRef | null;
readonly handleNewThread: NewThreadHandler;
@@ -57,35 +48,12 @@ export function resolveThreadActionProjectRef(
return context.defaultProjectRef;
}
function buildContextualThreadOptions(context: ChatThreadActionContext): NewThreadOptions {
return {
branch: context.activeThread?.branch ?? context.activeDraftThread?.branch ?? null,
worktreePath:
context.activeThread?.worktreePath ?? context.activeDraftThread?.worktreePath ?? null,
envMode:
context.activeDraftThread?.envMode ??
(context.activeThread?.worktreePath ? "worktree" : "local"),
...(context.activeDraftThread
? { startFromOrigin: context.activeDraftThread.startFromOrigin }
: {}),
};
}
export async function startNewThreadInProjectFromContext(
context: ChatThreadActionContext,
projectRef: ScopedProjectRef,
): Promise<void> {
const contextualProjectRef = resolveThreadActionProjectRef(context);
const matchesContext =
contextualProjectRef?.environmentId === projectRef.environmentId &&
contextualProjectRef.projectId === projectRef.projectId;
if (!matchesContext) {
await context.handleNewThread(projectRef);
return;
}
await context.handleNewThread(projectRef, buildContextualThreadOptions(context));
}
// New threads inherit only the *project* from the current context. Branch,
// worktree, and env mode always come from the user's configured defaults —
// carrying them over from the viewed thread meant "new thread" silently
// reused checkouts and branches. Explicit affordances (branch toolbar's
// "new thread in this worktree") pass those options to handleNewThread
// directly instead.
export async function startNewThreadFromContext(
context: ChatThreadActionContext,
): Promise<boolean> {
@@ -94,18 +62,6 @@ export async function startNewThreadFromContext(
return false;
}
await startNewThreadInProjectFromContext(context, projectRef);
return true;
}
export async function startNewLocalThreadFromContext(
context: ChatThreadActionContext,
): Promise<boolean> {
const projectRef = resolveThreadActionProjectRef(context);
if (!projectRef) {
return false;
}
await context.handleNewThread(projectRef);
return true;
}
+2 -5
View File
@@ -11,10 +11,7 @@ import { selectProjectGroupingSettings } from "../logicalProject";
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
startNewLocalThreadFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
@@ -83,7 +80,7 @@ function ChatRouteGlobalShortcuts() {
if (command === "chat.newLocal") {
event.preventDefault();
event.stopPropagation();
void startNewLocalThreadFromContext({
void startNewThreadFromContext({
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
+9
View File
@@ -207,6 +207,15 @@ export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId):
);
}
/** Whether the environment's server understands thread.snooze/unsnooze.
Same version-skew contract as settlement. */
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSnooze === true
);
}
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
}
+1 -1
View File
@@ -40,7 +40,7 @@ function getTimestampFormatter(
return formatter;
}
function parseTimestampDate(isoDate: string): Date | null {
export function parseTimestampDate(isoDate: string): Date | null {
const date = new Date(isoDate);
return Number.isNaN(date.getTime()) ? null : date;
}
+22 -7
View File
@@ -116,7 +116,7 @@ describe("uiStateStore pure functions", () => {
);
});
it("stores only collapsed changed-file turns", () => {
it("stores explicit changed-file expansion choices", () => {
const threadId = ThreadId.make("thread-1");
const collapsed = setThreadChangedFilesExpanded(makeUiState(), threadId, "turn-1", false);
@@ -128,7 +128,11 @@ describe("uiStateStore pure functions", () => {
expect(
setThreadChangedFilesExpanded(collapsed, threadId, "turn-1", true)
.threadChangedFilesExpandedById,
).toEqual({});
).toEqual({
[threadId]: {
"turn-1": true,
},
});
});
it("stores the endpoint preference by stable key", () => {
@@ -155,6 +159,7 @@ describe("parsePersistedState", () => {
invalid: "not-a-date",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
@@ -175,11 +180,24 @@ describe("parsePersistedState", () => {
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
"turn-2": true,
},
},
});
});
it("ignores changed-file expansion values saved with legacy folder semantics", () => {
const parsed = parsePersistedState({
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
},
},
});
expect(parsed.threadChangedFilesExpandedById).toEqual({});
});
it("migrates legacy CWD project preferences into local alias keys", () => {
const parsed = parsePersistedState({
collapsedProjectCwds: ["/repo/b"],
@@ -278,19 +296,16 @@ describe("uiStateStore persistence", () => {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
"turn-2": true,
},
},
});
expect(parsePersistedState(persisted)).toEqual({
...state,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
},
},
});
});
+12 -42
View File
@@ -3,6 +3,7 @@ import { create } from "zustand";
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
export const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const THREAD_CHANGED_FILES_EXPANSION_VERSION = 1;
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
@@ -24,6 +25,7 @@ export interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
defaultAdvertisedEndpointKey?: string | null;
threadChangedFilesExpansionVersion?: typeof THREAD_CHANGED_FILES_EXPANSION_VERSION;
threadChangedFilesExpandedById?: Record<string, Record<string, boolean>>;
}
@@ -124,9 +126,10 @@ export function parsePersistedState(parsed: PersistedUiState): UiState {
projectExpandedById,
projectOrder,
threadLastVisitedAtById: sanitizeTimestampRecord(parsed.threadLastVisitedAtById),
threadChangedFilesExpandedById: sanitizePersistedThreadChangedFilesExpanded(
parsed.threadChangedFilesExpandedById,
),
threadChangedFilesExpandedById:
parsed.threadChangedFilesExpansionVersion === THREAD_CHANGED_FILES_EXPANSION_VERSION
? sanitizePersistedThreadChangedFilesExpanded(parsed.threadChangedFilesExpandedById)
: {},
defaultAdvertisedEndpointKey:
typeof parsed.defaultAdvertisedEndpointKey === "string" &&
parsed.defaultAdvertisedEndpointKey.length > 0
@@ -172,8 +175,8 @@ function sanitizePersistedThreadChangedFilesExpanded(
const nextTurns: Record<string, boolean> = {};
for (const [turnId, expanded] of Object.entries(turns)) {
if (turnId && typeof expanded === "boolean" && expanded === false) {
nextTurns[turnId] = false;
if (turnId && typeof expanded === "boolean") {
nextTurns[turnId] = expanded;
}
}
@@ -195,14 +198,6 @@ export function persistState(state: UiState): void {
([key]) => key !== LEGACY_PROJECT_EXPANSION_DEFAULT_KEY,
),
);
const threadChangedFilesExpandedById = Object.fromEntries(
Object.entries(state.threadChangedFilesExpandedById).flatMap(([threadId, turns]) => {
const nextTurns = Object.fromEntries(
Object.entries(turns).filter(([, expanded]) => expanded === false),
);
return Object.keys(nextTurns).length > 0 ? [[threadId, nextTurns]] : [];
}),
);
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
@@ -210,7 +205,8 @@ export function persistState(state: UiState): void {
projectOrder: state.projectOrder,
threadLastVisitedAtById: state.threadLastVisitedAtById,
defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey,
threadChangedFilesExpandedById,
threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION,
threadChangedFilesExpandedById: state.threadChangedFilesExpandedById,
} satisfies PersistedUiState),
);
if (!legacyKeysCleanedUp) {
@@ -281,43 +277,17 @@ export function setThreadChangedFilesExpanded(
expanded: boolean,
): UiState {
const currentThreadState = state.threadChangedFilesExpandedById[threadId] ?? {};
const currentExpanded = currentThreadState[turnId] ?? true;
if (currentExpanded === expanded) {
if (currentThreadState[turnId] === expanded) {
return state;
}
if (expanded) {
if (!(turnId in currentThreadState)) {
return state;
}
const nextThreadState = { ...currentThreadState };
delete nextThreadState[turnId];
if (Object.keys(nextThreadState).length === 0) {
const nextState = { ...state.threadChangedFilesExpandedById };
delete nextState[threadId];
return {
...state,
threadChangedFilesExpandedById: nextState,
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: nextThreadState,
},
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: {
...currentThreadState,
[turnId]: false,
[turnId]: expanded,
},
},
};
@@ -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 SnoozeThreadInput = CommandInput<"thread.snooze">;
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
@@ -175,6 +177,26 @@ export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Eff
});
});
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.snoozeThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.snooze",
commandId: yield* commandId(input),
});
});
export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.unsnoozeThread",
)(function* (input) {
return yield* dispatch({
...input,
type: "thread.unsnooze",
commandId: yield* commandId(input),
});
});
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.updateThreadMetadata",
)(function* (input) {
@@ -13,10 +13,12 @@ import {
type SetThreadInteractionModeInput,
type SetThreadRuntimeModeInput,
type SettleThreadInput,
type SnoozeThreadInput,
type StartThreadTurnInput,
type StopThreadSessionInput,
type UnarchiveThreadInput,
type UnsettleThreadInput,
type UnsnoozeThreadInput,
type UpdateThreadMetadataInput,
archiveThread,
createThread,
@@ -28,10 +30,12 @@ import {
setThreadInteractionMode,
setThreadRuntimeMode,
settleThread,
snoozeThread,
startThreadTurn,
stopThreadSession,
unarchiveThread,
unsettleThread,
unsnoozeThread,
updateThreadMetadata,
} from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -47,10 +51,12 @@ export type {
SetThreadInteractionModeInput,
SetThreadRuntimeModeInput,
SettleThreadInput,
SnoozeThreadInput,
StartThreadTurnInput,
StopThreadSessionInput,
UnarchiveThreadInput,
UnsettleThreadInput,
UnsnoozeThreadInput,
UpdateThreadMetadataInput,
} from "../operations/commands.ts";
@@ -100,6 +106,18 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
snooze: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:snooze",
execute: (input: SnoozeThreadInput) => snoozeThread(input),
scheduler,
concurrency,
}),
unsnooze: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:unsnooze",
execute: (input: UnsnoozeThreadInput) => unsnoozeThread(input),
scheduler,
concurrency,
}),
updateMetadata: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:update-metadata",
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
@@ -59,6 +59,8 @@ export function mergeEnvironmentThread(
archivedAt: shell.archivedAt,
settledOverride: shell.settledOverride,
settledAt: shell.settledAt,
snoozedUntil: shell.snoozedUntil,
snoozedAt: shell.snoozedAt,
session: shell.session,
};
}
@@ -74,6 +74,8 @@ export function applyThreadDetailEvent(
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -124,6 +126,28 @@ export function applyThreadDetailEvent(
},
};
case "thread.snoozed":
return {
kind: "updated",
thread: {
...thread,
snoozedUntil: event.payload.snoozedUntil,
snoozedAt: event.payload.snoozedAt,
updatedAt: event.payload.updatedAt,
},
};
case "thread.unsnoozed":
return {
kind: "updated",
thread: {
...thread,
snoozedUntil: null,
snoozedAt: null,
updatedAt: event.payload.updatedAt,
},
};
// ── Thread metadata ─────────────────────────────────────────────
case "thread.meta-updated":
return {
@@ -90,6 +90,130 @@ export function canSettle(
return true;
}
/**
* The snooze lifecycle fields plus everything needed to detect a raised
* hand. Snooze is an overlay on the active state: a snoozed thread stays
* "active" in the data model and is only suppressed from the inbox until
* its wake time passes or the thread demands attention.
*/
export type ThreadSnoozeShell = Pick<
OrchestrationThreadShell,
| "snoozedUntil"
| "snoozedAt"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "session"
| "latestTurn"
>;
/**
* A snoozed thread "raises its hand" when something happens that outranks
* the user's snooze: the agent is blocked on them (approval / user input),
* the session failed, or a run completed after the snooze was set — the
* v1 taste of event-based snooze ("something happened" wakes early).
* Raising a hand never clears the server-side snooze fields; it only stops
* the thread from CLASSIFYING as snoozed, exactly like blocked work and
* effectiveSettled.
*/
export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
// Only a FRESH failure raises the hand: a thread snoozed while already
// failed stays snoozed — that snooze was the user saying "I saw it, not
// now". session.updatedAt stamps the status edge, so an error newer than
// the snooze is new information.
if (
shell.session?.status === "error" &&
(shell.snoozedAt == null || Date.parse(shell.session.updatedAt) > Date.parse(shell.snoozedAt))
) {
return true;
}
if (
shell.snoozedAt != null &&
shell.latestTurn?.state === "completed" &&
shell.latestTurn.completedAt != null &&
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
) {
return true;
}
return false;
}
/**
* A thread may be snoozed unless the agent is blocked on the user: hiding a
* pending approval or user-input request defeats the request, and a queued
* turn start (a message no turn has adopted yet) is invisible pending work
* the same way it is for settle. A running session IS snoozable — snooze
* only affects visibility, never the agent. Client-side twin of the server
* invariants so the UI can reject before a round trip.
*/
export function canSnooze(
shell: Pick<
OrchestrationThreadShell,
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
>,
options: { readonly now: string },
): boolean {
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
if (hasQueuedTurnStart(shell, options)) return false;
return true;
}
/**
* Snoozed resolution: hidden from the inbox while the wake time is in the
* future and the thread has not raised its hand. Timer wakes are derived —
* no server event fires when snoozedUntil passes; the stale fields simply
* stop classifying as snoozed (and feed the woke indicator until the user
* visits or re-engages).
*/
export function effectiveSnoozed(
shell: ThreadSnoozeShell,
options: { readonly now: string },
): boolean {
if (shell.snoozedUntil == null) return false;
const wakeAtMs = Date.parse(shell.snoozedUntil);
// Malformed data never hides a thread.
if (Number.isNaN(wakeAtMs)) return false;
if (wakeAtMs <= Date.parse(options.now)) return false;
return !threadRaisedHandWhileSnoozed(shell);
}
/**
* When a previously-snoozed thread woke, or null if it never snoozed / is
* still snoozed. Used for the "Woke" indicator: the thread reappears in its
* original sort position (the inbox sort is deliberately static), so the
* wake signal has to carry the weight. Compare against the client's
* lastVisitedAt — visiting clears the indicator like it clears unread.
*
* Timer wakes report the wake time itself; raised-hand wakes report the
* triggering timestamp so a visit BEFORE the early wake doesn't suppress
* the indicator.
*/
export function threadWokeAt(
shell: ThreadSnoozeShell,
options: { readonly now: string },
): string | null {
if (shell.snoozedUntil == null) return null;
const wakeAtMs = Date.parse(shell.snoozedUntil);
if (Number.isNaN(wakeAtMs)) return null;
// An early hand-raise wake stays authoritative even after the scheduled
// wake time passes: reporting snoozedUntil then would resurface a Woke
// indicator the user already cleared by visiting (snoozedUntil is newer
// than that visit's lastVisitedAt).
if (threadRaisedHandWhileSnoozed(shell)) {
if (
shell.snoozedAt != null &&
shell.latestTurn?.state === "completed" &&
shell.latestTurn.completedAt != null &&
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
) {
return shell.latestTurn.completedAt;
}
return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
}
// No raised hand: woke iff the timer elapsed (still-snoozed → null).
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
}
/**
* A merged/closed change request settles its thread only once the thread has
* been idle this long. Without the idle guard the merge signal is permanent:
@@ -0,0 +1,237 @@
import { ThreadId } from "@t3tools/contracts";
import { TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
canSnooze,
effectiveSnoozed,
threadRaisedHandWhileSnoozed,
threadWokeAt,
type ThreadSnoozeShell,
} from "./threadSettled.ts";
const NOW = "2026-04-10T12:00:00.000Z";
const SNOOZED_AT = "2026-04-10T09:00:00.000Z";
const FUTURE_WAKE = "2026-04-11T09:00:00.000Z";
const PAST_WAKE = "2026-04-10T10:00:00.000Z";
function makeShell(input: {
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
readonly sessionStatus?: "starting" | "running" | "ready" | "error";
readonly pending?: "approval" | "user-input";
readonly turnCompletedAt?: string | null;
}): ThreadSnoozeShell {
const threadId = ThreadId.make("thread-1");
return {
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
hasPendingApprovals: input.pending === "approval",
hasPendingUserInput: input.pending === "user-input",
session:
input.sessionStatus === undefined
? null
: {
threadId,
status: input.sessionStatus,
providerName: "Codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: input.sessionStatus === "error" ? "boom" : null,
updatedAt: "2026-04-10T11:00:00.000Z",
},
latestTurn:
input.turnCompletedAt === undefined
? null
: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: SNOOZED_AT,
startedAt: null,
completedAt: input.turnCompletedAt,
assistantMessageId: null,
},
};
}
describe("effectiveSnoozed", () => {
it("hides a thread whose wake time is in the future", () => {
expect(effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(true);
});
it("stops classifying as snoozed once the wake time passes (timer wake, no event)", () => {
expect(effectiveSnoozed(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(false);
});
it("never snoozes a thread with no snooze state", () => {
expect(effectiveSnoozed(makeShell({}), { now: NOW })).toBe(false);
});
it("never hides on malformed wake data", () => {
expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false);
});
it("wakes early when the agent is blocked on the user", () => {
expect(
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" }), {
now: NOW,
}),
).toBe(false);
expect(
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" }), {
now: NOW,
}),
).toBe(false);
});
it("wakes early on a failure that happened after the snooze", () => {
// makeShell stamps session.updatedAt at 11:00, after SNOOZED_AT (9:00).
expect(
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
now: NOW,
}),
).toBe(false);
});
it("stays snoozed when the failure predates the snooze — the user saw it", () => {
expect(
effectiveSnoozed(
makeShell({
snoozedUntil: FUTURE_WAKE,
sessionStatus: "error",
// Snoozed AFTER the error's status edge.
snoozedAt: "2026-04-10T11:30:00.000Z",
}),
{ now: NOW },
),
).toBe(true);
});
it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
expect(
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {
now: NOW,
}),
).toBe(true);
});
it("wakes early when a run completes after the snooze was set", () => {
expect(
effectiveSnoozed(
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
{ now: NOW },
),
).toBe(false);
});
it("ignores runs that completed before the snooze — the user saw that result", () => {
expect(
effectiveSnoozed(
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T08:00:00.000Z" }),
{ now: NOW },
),
).toBe(true);
});
});
describe("threadRaisedHandWhileSnoozed", () => {
it("is false for a quiet snoozed thread", () => {
expect(threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE }))).toBe(false);
});
it("is true for approvals, input, and failures", () => {
expect(
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" })),
).toBe(true);
expect(
threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" })),
).toBe(true);
expect(
threadRaisedHandWhileSnoozed(
makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }),
),
).toBe(true);
});
});
describe("canSnooze", () => {
it("allows snoozing quiet and working threads alike", () => {
expect(canSnooze({ ...makeShell({}), latestUserMessageAt: null }, { now: NOW })).toBe(true);
expect(
canSnooze(
{ ...makeShell({ sessionStatus: "running" }), latestUserMessageAt: null },
{ now: NOW },
),
).toBe(true);
});
it("refuses blocked-on-you work", () => {
expect(
canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
).toBe(false);
expect(
canSnooze(
{ ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
{ now: NOW },
),
).toBe(false);
});
it("refuses a queued turn start — same invisible-pending-work rule as settle", () => {
// Fresh user message, no turn has adopted it, within the grace window.
expect(
canSnooze(
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:59:30.000Z" },
{ now: NOW },
),
).toBe(false);
// Outside the grace window the message is stale data, not queued work.
expect(
canSnooze(
{ ...makeShell({}), latestUserMessageAt: "2026-04-10T11:00:00.000Z" },
{ now: NOW },
),
).toBe(true);
});
});
describe("threadWokeAt", () => {
it("is null for never-snoozed and still-snoozed threads", () => {
expect(threadWokeAt(makeShell({}), { now: NOW })).toBe(null);
expect(threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE }), { now: NOW })).toBe(null);
});
it("reports the wake time for a timer wake", () => {
expect(threadWokeAt(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(PAST_WAKE);
});
it("reports the completion time for an early run-completed wake", () => {
expect(
threadWokeAt(
makeShell({ snoozedUntil: FUTURE_WAKE, turnCompletedAt: "2026-04-10T10:30:00.000Z" }),
{ now: NOW },
),
).toBe("2026-04-10T10:30:00.000Z");
});
it("falls back to session activity for blocked/failed early wakes", () => {
expect(
threadWokeAt(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }), {
now: NOW,
}),
).toBe("2026-04-10T11:00:00.000Z");
});
it("keeps the early wake authoritative after the scheduled time passes", () => {
// Woke early at 10:30 via run-completed; the scheduled wake (PAST_WAKE
// 10:00 relative to a later now) has ALSO passed. Reporting the
// scheduled time would resurface a Woke pill the user already cleared
// by visiting between the early wake and now.
expect(
threadWokeAt(
makeShell({ snoozedUntil: PAST_WAKE, turnCompletedAt: "2026-04-10T09:30:00.000Z" }),
{ now: NOW },
),
).toBe("2026-04-10T09:30:00.000Z");
});
});
+3
View File
@@ -44,6 +44,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
pre-settlement servers, so clients treat missing as unsupported and
never send the commands under version skew. */
threadSettlement: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.snooze / thread.unsnooze commands. Same
version-skew contract as threadSettlement. */
threadSnooze: Schema.optionalKey(Schema.Boolean),
/** Server understands the review.summarizeThread RPC used by the sidebar
work-review sweep. Absent on older servers, so clients skip their
threads instead of sending an unknown method. */
+62
View File
@@ -361,6 +361,12 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
// 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).
// Optional so payloads from pre-snooze servers still decode.
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
deletedAt: Schema.NullOr(IsoDateTime),
messages: Schema.Array(OrchestrationMessage),
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
@@ -411,6 +417,8 @@ export const OrchestrationThreadShell = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
session: Schema.NullOr(OrchestrationSession),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
hasPendingApprovals: Schema.Boolean,
@@ -583,6 +591,27 @@ const ThreadUnsettleCommand = Schema.Struct({
reason: Schema.Literal("user"),
});
const ThreadSnoozeCommand = Schema.Struct({
type: Schema.Literal("thread.snooze"),
commandId: CommandId,
threadId: ThreadId,
// The wake time. Event-based wake conditions (PR merged, review posted)
// will arrive as an optional condition field alongside this; time-based
// snooze is just the first kind of condition.
snoozedUntil: IsoDateTime,
});
const ThreadUnsnoozeCommand = Schema.Struct({
type: Schema.Literal("thread.unsnooze"),
commandId: CommandId,
threadId: ThreadId,
// Commands only carry "user": activity wakes are decided server-side (the
// decider emits thread.unsnoozed(reason: "activity") directly), and timer
// wakes need no event at all — clients derive visibility from snoozedUntil,
// so a passed wake time simply stops classifying as snoozed.
reason: Schema.Literal("user"),
});
const ThreadMetaUpdateCommand = Schema.Struct({
type: Schema.Literal("thread.meta.update"),
commandId: CommandId,
@@ -727,6 +756,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
@@ -750,6 +781,8 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadUnarchiveCommand,
ThreadSettleCommand,
ThreadUnsettleCommand,
ThreadSnoozeCommand,
ThreadUnsnoozeCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
@@ -854,6 +887,8 @@ export const OrchestrationEventType = Schema.Literals([
"thread.unarchived",
"thread.settled",
"thread.unsettled",
"thread.snoozed",
"thread.unsnoozed",
"thread.meta-updated",
"thread.runtime-mode-set",
"thread.interaction-mode-set",
@@ -945,6 +980,23 @@ export const ThreadUnsettledPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
export const ThreadSnoozedPayload = Schema.Struct({
threadId: ThreadId,
snoozedUntil: IsoDateTime,
snoozedAt: IsoDateTime,
updatedAt: IsoDateTime,
});
export const ThreadUnsnoozedPayload = Schema.Struct({
threadId: ThreadId,
// user: explicit "wake now". activity: real work arrived (user message /
// session coming alive) and the decider cleared the snooze — mirrors
// thread.unsettled's activity resets. Timer wakes emit no event: clients
// derive them from snoozedUntil passing.
reason: Schema.Literals(["user", "activity"]),
updatedAt: IsoDateTime,
});
export const ThreadMetaUpdatedPayload = Schema.Struct({
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
@@ -1122,6 +1174,16 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.unsettled"),
payload: ThreadUnsettledPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.snoozed"),
payload: ThreadSnoozedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.unsnoozed"),
payload: ThreadUnsnoozedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.meta-updated"),
+3
View File
@@ -471,6 +471,9 @@ importers:
node-pty:
specifier: ^1.1.0
version: 1.1.0
yaml:
specifier: ^2.9.0
version: 2.9.0
devDependencies:
'@effect/vitest':
specifier: 4.0.0-beta.78