Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(sidebar-v2): thread pinning for sidebar v2 (#5312)
Theo Browneda6e1a967825
diff --git a/apps/mobile/src/components/AppSymbol.tsx b/apps/mobile/src/components/AppSymbol.tsxindex d4c7088fe..b1e83607d 100644--- a/apps/mobile/src/components/AppSymbol.tsx+++ b/apps/mobile/src/components/AppSymbol.tsx@@ -50,6 +50,8 @@ import {IconMinus,IconNetwork,IconPalette,+ IconPin,+ IconPinnedOff,IconPlayerPlay,IconPlayerStopFilled,IconPlus,@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {magnifyingglass: IconSearch,paintbrush: IconPalette,"person.crop.circle": IconUserCircle,+ pin: IconPin,+ "pin.slash": IconPinnedOff,play: IconPlayerPlay,plus: IconPlus,"qrcode.viewfinder": IconQrcode,diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsxindex 0aefde991..16a3efde6 100644--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx@@ -42,6 +42,8 @@ export function HomeRouteScreen() {settleThread,snoozeThread,unsnoozeThread,+ pinThread,+ unpinThread,unsettleThread,} = useThreadListActions();const pendingTasks = usePendingNewTasks();@@ -155,6 +157,8 @@ export function HomeRouteScreen() {onSnoozeThread={snoozeThread}onUnsnoozeThread={unsnoozeThread}onUnsettleThread={unsettleThread}+ onPinThread={pinThread}+ onUnpinThread={unpinThread}onEnvironmentChange={setSelectedEnvironmentId}onProjectChange={setSelectedProjectKey}onOpenEnvironments={() =>diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex d54fb7d48..2b58bc342 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -111,6 +111,8 @@ interface HomeScreenProps {) => Promise<boolean>;readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;+ readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;+ readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;readonly onNewThreadInProject: (project: EnvironmentProject) => void;@@ -516,6 +518,18 @@ export function HomeScreen(props: HomeScreenProps) {},[props.onUnsnoozeThread],);+ const handlePinThread = useCallback(+ (thread: EnvironmentThreadShell) => {+ void props.onPinThread(thread);+ },+ [props.onPinThread],+ );+ const handleUnpinThread = useCallback(+ (thread: EnvironmentThreadShell) => {+ void props.onUnpinThread(thread);+ },+ [props.onUnpinThread],+ );const handleDeleteThread = props.onDeleteThread;const handleUnsettleThread = props.onUnsettleThread;// The settled tail renders in pages; expansion resets when the filter@@ -575,6 +589,15 @@ export function HomeScreen(props: HomeScreenProps) {}return supported;}, [serverConfigs]);+ const pinningEnvironmentIds = useMemo(() => {+ const supported = new Set<EnvironmentId>();+ for (const [environmentId, config] of serverConfigs) {+ if (config.environment.capabilities.threadPinning === true) {+ supported.add(environmentId);+ }+ }+ return supported;+ }, [serverConfigs]);const threadListV2Layout = useMemo(() => {if (!threadListV2Enabled)return {@@ -718,6 +741,7 @@ export function HomeScreen(props: HomeScreenProps) {thread={thread}variant={item.item.variant}snoozed={item.item.snoozed}+ pinned={item.item.pinned}snoozePresetMinute={nowMinute}snoozeWakeLabelText={item.snoozeWakeLabelText}project={@@ -753,9 +777,12 @@ export function HomeScreen(props: HomeScreenProps) {settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}onSettleThread={handleSettleThread}snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}+ pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}onSnoozeThread={handleSnoozeThread}onUnsnoozeThread={handleUnsnoozeThread}onUnsettleThread={handleUnsettleThread}+ onPinThread={handlePinThread}+ onUnpinThread={handleUnpinThread}onChangeRequestState={handleChangeRequestState}projectCwd={projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null@@ -768,12 +795,15 @@ export function HomeScreen(props: HomeScreenProps) {[handleChangeRequestState,handleDeleteThread,+ handlePinThread,handleSettleThread,handleSnoozeThread,+ handleUnpinThread,handleUnsnoozeThread,handleSwipeableClose,handleSwipeableWillOpen,handleUnsettleThread,+ pinningEnvironmentIds,projectByKey,projectCwdByKey,props.onArchiveThread,diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.tsindex 0c621a04e..dcea2b679 100644--- a/apps/mobile/src/features/home/useThreadListActions.ts+++ b/apps/mobile/src/features/home/useThreadListActions.ts@@ -29,6 +29,13 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro);}+function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {+ return (+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities+ .threadPinning === true+ );+}+type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";const ACTION_VERBS: Record<ThreadListAction, string> = {@@ -202,10 +209,14 @@ export function useThreadListActions(): {readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;+ readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;+ readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;} {const executeAction = useThreadActionExecutor();const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });+ const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });+ const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });const snoozeInFlightThreadKeys = useRef(new Set<string>());const archiveThread = useCallback(@@ -310,6 +321,62 @@ export function useThreadListActions(): {async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,[executeAction],);+ const pinThread = useCallback(+ async (thread: EnvironmentThreadShell) => {+ if (!environmentSupportsPinning(thread.environmentId)) {+ Alert.alert(+ "Could not pin thread",+ "This environment's server does not support pinning yet. Update the server to use Pin.",+ );+ return false;+ }+ selectionHaptic();+ const result = await pinMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Alert.alert(+ "Could not pin thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be pinned.",+ );+ return false;+ }+ return true;+ },+ [pinMutation],+ );+ const unpinThread = useCallback(+ async (thread: EnvironmentThreadShell) => {+ if (!environmentSupportsPinning(thread.environmentId)) {+ Alert.alert(+ "Could not unpin thread",+ "This environment's server does not support pinning yet. Update the server to use Pin.",+ );+ return false;+ }+ selectionHaptic();+ const result = await unpinMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Alert.alert(+ "Could not unpin thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be unpinned.",+ );+ return false;+ }+ return true;+ },+ [unpinMutation],+ );const confirmDeleteThread = useConfirmDeleteThread(executeAction);@@ -320,6 +387,8 @@ export function useThreadListActions(): {snoozeThread,unsnoozeThread,unsettleThread,+ pinThread,+ unpinThread,};}diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 8a7fc2ed6..322ac6075 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -205,6 +205,8 @@ function ThreadNavigationSidebarPane(snoozeThread,unsnoozeThread,unsettleThread,+ pinThread,+ unpinThread,} = useThreadListActions();const threadListV2Enabled = useThreadListV2Enabled();const pendingTasks = usePendingNewTasks();@@ -481,6 +483,15 @@ function ThreadNavigationSidebarPane(}return supported;}, [serverConfigs]);+ const pinningEnvironmentIds = useMemo(() => {+ const supported = new Set<EnvironmentId>();+ for (const [environmentId, config] of serverConfigs) {+ if (config.environment.capabilities.threadPinning === true) {+ supported.add(environmentId);+ }+ }+ return supported;+ }, [serverConfigs]);const threadListV2Layout = useMemo(() => {if (!threadListV2Enabled)return {@@ -792,6 +803,7 @@ function ThreadNavigationSidebarPane(previous.item.thread === item.item.thread &&previous.item.variant === item.item.variant &&previous.item.snoozed === item.item.snoozed &&+ previous.item.pinned === item.item.pinned &&previous.snoozeWakeLabelText === item.snoozeWakeLabelText);}@@ -879,6 +891,7 @@ function ThreadNavigationSidebarPane(thread={thread}variant={item.item.variant}snoozed={item.item.snoozed}+ pinned={item.item.pinned}snoozePresetMinute={nowMinute}snoozeWakeLabelText={item.snoozeWakeLabelText}project={projectByKey.get(scopeKey) ?? null}@@ -915,9 +928,12 @@ function ThreadNavigationSidebarPane(settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}onSettleThread={settleThread}snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}+ pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}onSnoozeThread={snoozeThread}onUnsnoozeThread={unsnoozeThread}onUnsettleThread={unsettleThread}+ onPinThread={pinThread}+ onUnpinThread={unpinThread}onChangeRequestState={handleChangeRequestState}projectCwd={projectCwdByKey.get(scopeKey) ?? null}onSwipeableClose={handleSwipeableClose}@@ -1045,6 +1061,8 @@ function ThreadNavigationSidebarPane(handleSwipeableClose,handleSwipeableWillOpen,openPendingTask,+ pinThread,+ pinningEnvironmentIds,projectByKey,projectCwdByKey,projectTitleByProjectKey,@@ -1064,6 +1082,7 @@ function ThreadNavigationSidebarPane(nowMinute,toggleSettledShelf,toggleSnoozedShelf,+ unpinThread,unsettleThread,unsnoozeThread,updateGroupDisplay,diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex 8d6874c78..6b9dd5251 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -305,6 +305,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {readonly variant: "card" | "slim";/** Snoozed-shelf row: shows its wake time and offers Wake. */readonly snoozed?: boolean;+ /** Pinned-block row: shows the pin glyph and offers Unpin. */+ readonly pinned?: boolean;/** Preformatted against the parent minute tick so this memoized row'scountdown keeps moving. */readonly snoozeWakeLabelText?: string;@@ -337,11 +339,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;+ readonly onPinThread: (thread: EnvironmentThreadShell) => void;+ readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;/** False on environments whose server predates thread.settle/unsettle:swipe + menu fall back to Archive instead of failing on use. */readonly settlementSupported: boolean;/** False on servers that predate thread.snooze/unsnooze. */readonly snoozeSupported: boolean;+ /** False on servers that predate thread.pin/unpin. */+ readonly pinningSupported: boolean;readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;readonly onSwipeableClose: (methods: SwipeableMethods) => void;/** Reports this row's live PR state up so the partition can auto-settle@@ -368,9 +374,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {onUnsnoozeThread,onUnsettleThread,onArchiveThread,+ onPinThread,+ onUnpinThread,onChangeRequestState,} = props;const snoozedRow = props.snoozed === true;+ const pinnedRow = props.pinned === true;const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);const prState = pr?.state ?? null;@@ -383,6 +392,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {const drawerColor = useThemeColor("--color-drawer");const pressedBackgroundColor = useThemeColor("--color-subtle");const selectedBackgroundColor = useThemeColor("--color-user-bubble");+ const pinTintColor = useThemeColor("--color-foreground-muted");const sidebarPane = props.pane === "sidebar";const selected = props.selected === true;@@ -398,6 +408,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {);const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);+ const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);+ const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);// Swipe: the v2 primary action is the lifecycle transition. Every settled@@ -434,6 +446,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {})),[snoozePresets],);+ // Pinned cards keep the full lifecycle menu; only the pin item flips to+ // Unpin. (Settling a pinned thread clears the pin server-side; snoozing+ // hides the card until wake with the pin intact.)+ const pinMenuItem = useMemo<MenuAction[]>(+ () =>+ props.pinningSupported+ ? [+ pinnedRow+ ? { id: "unpin", title: "Unpin", image: "pin.slash" }+ : { id: "pin", title: "Pin", image: "pin" },+ ]+ : [],+ [pinnedRow, props.pinningSupported],+ );const snoozableCardMenuActions = useMemo<MenuAction[]>(() => [{ id: "settle", title: "Settle", image: "checkmark" },@@ -443,15 +469,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {image: "clock",subactions: snoozePresetActions,},+ ...pinMenuItem,{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },],- [snoozePresetActions],+ [pinMenuItem, snoozePresetActions],+ );+ const cardMenuActions = useMemo<MenuAction[]>(+ () => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],+ [pinMenuItem],);const handleMenuAction = useCallback(({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {if (nativeEvent.event === "settle") handleSettle();if (nativeEvent.event === "unsettle") handleUnsettle();if (nativeEvent.event === "unsnooze") handleUnsnooze();+ if (nativeEvent.event === "pin") handlePin();+ if (nativeEvent.event === "unpin") handleUnpin();if (nativeEvent.event === "archive") handleArchive();if (nativeEvent.event === "delete") handleDelete();const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({@@ -468,8 +501,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {[handleArchive,handleDelete,+ handlePin,handleSettle,handleSnooze,+ handleUnpin,handleUnsettle,handleUnsnooze,snoozePresets,@@ -560,6 +595,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {>{props.projectTitle ?? props.project?.title ?? ""}</Text>+ {pinnedRow ? (+ <SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />+ ) : null}<TextclassName={cn("text-xs tabular-nums",@@ -805,7 +843,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {? SLIM_MENU_ACTIONS: swipeActions.secondary === "snooze"? snoozableCardMenuActions- : CARD_MENU_ACTIONS+ : cardMenuActions}onPressAction={handleMenuAction}shouldOpenOnLongPressdiff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.tsindex 99b5700f7..1316b3480 100644--- a/apps/mobile/src/features/threads/threadListV2.test.ts+++ b/apps/mobile/src/features/threads/threadListV2.test.ts@@ -288,6 +288,57 @@ describe("buildThreadListV2Items", () => {expect(layout.snoozedCount).toBe(1);});+ it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {+ const layout = buildThreadListV2Items({+ threads: [+ makeThread({ id: ThreadId.make("active"), title: "Active" }),+ makeThread({+ id: ThreadId.make("pinned-settled"),+ title: "Pinned while settled",+ pinnedAt: "2026-06-01T12:00:00.000Z",+ // Stale settled state (the decider clears it on pin): the pin wins.+ settledOverride: "settled",+ settledAt: "2026-06-01T12:00:00.000Z",+ }),+ ],+ environmentId: null,+ searchQuery: "",+ now: NOW,+ });++ expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);+ expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);+ expect(layout.settledCount).toBe(0);+ });++ it("snooze hides a pinned thread and wake restores it to the pinned block", () => {+ const snoozedInput = {+ threads: [+ makeThread({ id: ThreadId.make("active"), title: "Active" }),+ makeThread({+ id: ThreadId.make("pinned-snoozed"),+ title: "Pinned and snoozed",+ pinnedAt: "2026-06-01T12:00:00.000Z",+ snoozedUntil: "2026-06-03T09:00:00.000Z",+ snoozedAt: "2026-06-01T11:00:00.000Z",+ }),+ ],+ environmentId: null,+ searchQuery: "",+ };++ // Before the wake time: the snooze wins; the pin holds underneath.+ const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });+ expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);+ expect(whileSnoozed.snoozedCount).toBe(1);++ // After the wake time: the thread returns pinned, back on top.+ const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });+ expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);+ expect(afterWake.items[0]?.pinned).toBe(true);+ expect(afterWake.snoozedCount).toBe(0);+ });+it("classifies snooze with the second-precise clock and reports the next wake", () => {const layout = buildThreadListV2Items({threads: [diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.tsindex c88aff4ec..fa5f58d5d 100644--- a/apps/mobile/src/features/threads/threadListV2.ts+++ b/apps/mobile/src/features/threads/threadListV2.ts@@ -180,6 +180,8 @@ export interface ThreadListV2Item {readonly variant: "card" | "slim";/** Snoozed-shelf row: shows the wake countdown and offers Wake. */readonly snoozed: boolean;+ /** Pinned-block row: renders the pin glyph and offers Unpin. */+ readonly pinned: boolean;readonly isLast: boolean;}@@ -351,6 +353,7 @@ export function buildThreadListV2Items(input: {? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`)): null;+ const pinned: EnvironmentThreadShell[] = [];const active: EnvironmentThreadShell[] = [];const settled: EnvironmentThreadShell[] = [];const snoozed: EnvironmentThreadShell[] = [];@@ -378,9 +381,10 @@ export function buildThreadListV2Items(input: {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.+ // Visibility parity with web: snooze outranks everything, including a+ // pin — a snoozed thread leaves the list until it wakes (or raises its+ // hand). The pin survives underneath, so a woken thread reappears at+ // its original spot in the creation-ordered pinned block.if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {snoozed.push(thread);if (@@ -392,6 +396,12 @@ export function buildThreadListV2Items(input: {}continue;}+ // A pin otherwise overrides the lifecycle: pinned threads render above+ // the inbox and never auto-settle out of sight.+ if (thread.pinnedAt != null) {+ pinned.push(thread);+ continue;+ }if (supportsSettlement &&effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })@@ -434,11 +444,21 @@ export function buildThreadListV2Items(input: {);const items: ThreadListV2Item[] = [];+ for (const thread of sortThreadsForListV2(pinned)) {+ items.push({+ thread,+ variant: "card",+ snoozed: false,+ pinned: true,+ isLast: false,+ });+ }for (const thread of orderedActive) {items.push({thread,variant: "card",snoozed: false,+ pinned: false,isLast: false,});}@@ -448,6 +468,7 @@ export function buildThreadListV2Items(input: {thread,variant: "slim",snoozed: true,+ pinned: false,isLast: false,});}@@ -457,6 +478,7 @@ export function buildThreadListV2Items(input: {thread,variant: "slim",snoozed: false,+ pinned: false,isLast: false,});}diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex a14f89fd0..b6eedb87e 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -145,6 +145,7 @@ export const make = Effect.gen(function* () {connectionProbe: true,threadSettlement: true,threadSnooze: true,+ threadPinning: true,threadTitleRegeneration: true,...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 1a08f7aee..fe683b08a 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -611,6 +611,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectisettledAt: null,snoozedUntil: null,snoozedAt: null,+ pinnedAt: null,titleRegenerationRequestId: null,titleRegenerationStartedAt: null,latestUserMessageAt: null,@@ -717,6 +718,36 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectireturn;}+ case "thread.pinned": {+ const existingRow = yield* projectionThreadRepository.getById({+ threadId: event.payload.threadId,+ });+ if (Option.isNone(existingRow)) {+ return;+ }+ yield* projectionThreadRepository.upsert({+ ...existingRow.value,+ pinnedAt: event.payload.pinnedAt,+ updatedAt: event.payload.updatedAt,+ });+ return;+ }++ case "thread.unpinned": {+ const existingRow = yield* projectionThreadRepository.getById({+ threadId: event.payload.threadId,+ });+ if (Option.isNone(existingRow)) {+ return;+ }+ yield* projectionThreadRepository.upsert({+ ...existingRow.value,+ pinnedAt: null,+ updatedAt: event.payload.updatedAt,+ });+ return;+ }+case "thread.meta-updated": {const existingRow = yield* projectionThreadRepository.getById({threadId: event.payload.threadId,diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 6fe7f831a..9c4a81b18 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -312,6 +312,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {settledAt: null,snoozedUntil: null,snoozedAt: null,+ pinnedAt: null,titleRegeneration: null,deletedAt: null,messages: [@@ -427,6 +428,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {settledAt: null,snoozedUntil: null,snoozedAt: null,+ pinnedAt: null,titleRegeneration: null,session: {threadId: ThreadId.make("thread-1"),diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 4dcc43913..766f8a93d 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -384,6 +384,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -418,6 +419,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -454,6 +456,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -890,6 +893,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -1328,6 +1332,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: row.settledAt,snoozedUntil: row.snoozedUntil,snoozedAt: row.snoozedAt,+ pinnedAt: row.pinnedAt,titleRegeneration: mapTitleRegeneration(row),deletedAt: row.deletedAt,messages: messagesByThread.get(row.threadId) ?? [],@@ -1531,6 +1536,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: row.settledAt,snoozedUntil: row.snoozedUntil,snoozedAt: row.snoozedAt,+ pinnedAt: row.pinnedAt,titleRegeneration: mapTitleRegeneration(row),deletedAt: row.deletedAt,messages: [],@@ -1665,6 +1671,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: row.settledAt,snoozedUntil: row.snoozedUntil,snoozedAt: row.snoozedAt,+ pinnedAt: row.pinnedAt,titleRegeneration: mapTitleRegeneration(row),session: sessionByThread.get(row.threadId) ?? null,latestUserMessageAt: row.latestUserMessageAt,@@ -1804,6 +1811,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: row.settledAt,snoozedUntil: row.snoozedUntil,snoozedAt: row.snoozedAt,+ pinnedAt: row.pinnedAt,titleRegeneration: mapTitleRegeneration(row),session: sessionByThread.get(row.threadId) ?? null,latestUserMessageAt: row.latestUserMessageAt,@@ -2075,6 +2083,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: threadRow.value.settledAt,snoozedUntil: threadRow.value.snoozedUntil,snoozedAt: threadRow.value.snoozedAt,+ pinnedAt: threadRow.value.pinnedAt,titleRegeneration: mapTitleRegeneration(threadRow.value),session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,latestUserMessageAt: threadRow.value.latestUserMessageAt,@@ -2174,6 +2183,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {settledAt: threadRow.value.settledAt,snoozedUntil: threadRow.value.snoozedUntil,snoozedAt: threadRow.value.snoozedAt,+ pinnedAt: threadRow.value.pinnedAt,titleRegeneration: mapTitleRegeneration(threadRow.value),deletedAt: null,messages: messageRows.map((row) => {diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.tsindex 3b558d247..ee96e4229 100644--- a/apps/server/src/orchestration/Schemas.ts+++ b/apps/server/src/orchestration/Schemas.ts@@ -13,6 +13,8 @@ import {ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,+ ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,+ ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,@@ -42,6 +44,8 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;+export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;+export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;diff --git a/apps/server/src/orchestration/decider.pinned.test.ts b/apps/server/src/orchestration/decider.pinned.test.tsnew file mode 100644index 000000000..bed41e13a--- /dev/null+++ b/apps/server/src/orchestration/decider.pinned.test.ts@@ -0,0 +1,226 @@+import {+ CommandId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ type OrchestrationReadModel,+} from "@t3tools/contracts";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { decideOrchestrationCommand } from "./decider.ts";++const NOW = "2026-01-01T00:00:00.000Z";+const PINNED_AT = "1969-12-30T00:00:00.000Z";++function makeReadModel(input: {+ readonly pinnedAt?: string | null;+ readonly archivedAt?: string | null;+ readonly settledOverride?: "settled" | "active" | null;+ readonly settledAt?: string | null;+ readonly snoozedUntil?: string | null;+ readonly snoozedAt?: string | null;+}): 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: input.settledOverride ?? null,+ settledAt: input.settledAt ?? (input.settledOverride === "settled" ? NOW : null),+ snoozedUntil: input.snoozedUntil ?? null,+ snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),+ pinnedAt: input.pinnedAt ?? null,+ deletedAt: null,+ messages: [],+ proposedPlans: [],+ activities: [],+ checkpoints: [],+ session: null,+ },+ ],+ updatedAt: NOW,+ };+}++it.layer(NodeServices.layer)("pinned thread decider", (it) => {+ it.effect("pins a thread, stamping pinnedAt and updatedAt together", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({}),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events).toHaveLength(1);+ expect(events[0]?.type).toBe("thread.pinned");+ if (events[0]?.type === "thread.pinned") {+ expect(events[0].payload.pinnedAt).toBe(events[0].payload.updatedAt);+ }+ }),+ );++ it.effect("re-pinning preserves the original pinnedAt and updatedAt", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin-again"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ pinnedAt: PINNED_AT }),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events[0]?.type).toBe("thread.pinned");+ if (events[0]?.type === "thread.pinned") {+ expect(events[0].payload.pinnedAt).toBe(PINNED_AT);+ expect(events[0].payload.updatedAt).toBe(NOW);+ }+ }),+ );++ it.effect("unpins a pinned thread", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.unpin",+ commandId: CommandId.make("cmd-unpin"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ pinnedAt: PINNED_AT }),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events[0]?.type).toBe("thread.unpinned");+ if (events[0]?.type === "thread.unpinned") {+ expect(events[0].payload.updatedAt).not.toBe(NOW);+ }+ }),+ );++ it.effect("unpinning an unpinned thread preserves updatedAt", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.unpin",+ commandId: CommandId.make("cmd-unpin-noop"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({}),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events[0]?.type).toBe("thread.unpinned");+ if (events[0]?.type === "thread.unpinned") {+ expect(events[0].payload.updatedAt).toBe(NOW);+ }+ }),+ );++ it.effect("pinning a settled thread also un-settles it", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin-settled"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ settledOverride: "settled" }),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsettled"]);+ const unsettled = events.find((entry) => entry.type === "thread.unsettled");+ if (unsettled?.type === "thread.unsettled") {+ expect(unsettled.payload.reason).toBe("user");+ }+ }),+ );++ it.effect("pinning a snoozed thread also wakes it", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin-snoozed"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ snoozedUntil: "1970-01-02T09:00:00.000Z" }),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsnoozed"]);+ }),+ );++ it.effect("pinning an unparked thread emits only thread.pinned", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin-plain"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({}),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events.map((entry) => entry.type)).toEqual(["thread.pinned"]);+ }),+ );++ it.effect("settling a pinned thread also unpins it", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.settle",+ commandId: CommandId.make("cmd-settle-pinned"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ pinnedAt: PINNED_AT }),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unpinned"]);+ }),+ );++ it.effect("settling an unpinned thread emits no unpin event", () =>+ Effect.gen(function* () {+ const event = yield* decideOrchestrationCommand({+ command: {+ type: "thread.settle",+ commandId: CommandId.make("cmd-settle-unpinned"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({}),+ });+ const events = Array.isArray(event) ? event : [event];+ expect(events.map((entry) => entry.type)).toEqual(["thread.settled"]);+ }),+ );++ it.effect("rejects pinning an archived thread", () =>+ Effect.gen(function* () {+ const error = yield* decideOrchestrationCommand({+ command: {+ type: "thread.pin",+ commandId: CommandId.make("cmd-pin-archived"),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel({ archivedAt: NOW }),+ }).pipe(Effect.flip);+ expect(error._tag).toBe("OrchestrationCommandInvariantError");+ }),+ );+});diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex ae9a06886..5e5579ae9 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -487,14 +487,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"// settledAt: the engine rejects zero-event commands, and bulk-settle /// double-click must stay silent no-ops rather than surface errors.const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;- return {+ const settledEvent = {...(yield* withEventBase({aggregateKind: "thread",aggregateId: command.threadId,occurredAt,commandId: command.commandId,})),- type: "thread.settled",+ type: "thread.settled" as const,payload: {threadId: command.threadId,settledAt: alreadySettled ? thread.settledAt : occurredAt,@@ -504,6 +504,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"updatedAt: alreadySettled ? thread.updatedAt : occurredAt,},};+ // Settling is "I'm done with this": it clears a pin the same way it+ // parks the thread. Without this, settling a pinned thread would only+ // stamp invisible state — the pin would hold the card in place until+ // a separate unpin.+ if (thread.pinnedAt == null) {+ return settledEvent;+ }+ return [+ settledEvent,+ {+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.unpinned" as const,+ payload: {+ threadId: command.threadId,+ updatedAt: occurredAt,+ },+ },+ ];}case "thread.unsettle": {@@ -630,6 +653,98 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}+ case "thread.pin": {+ const thread = yield* requireThreadNotArchived({+ readModel,+ command,+ threadId: command.threadId,+ });+ const occurredAt = yield* nowIso;+ // Re-pinning an already-pinned thread is a duplicate (double-click,+ // raced clients): re-emit with the original timestamps so the+ // projection is a no-op. Pinning has no lifecycle invariants — a pin+ // only ever promotes visibility, so it can never hide pending work.+ const existingPinnedAt = thread.pinnedAt ?? null;+ const pinnedEvent = {+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.pinned" as const,+ payload: {+ threadId: command.threadId,+ pinnedAt: existingPinnedAt ?? occurredAt,+ updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,+ },+ };+ // Pinning is a promotion: it clears the parked states rather than+ // silently outranking them. An explicit settle un-settles (reason+ // "user", same override the un-settle button stamps), and a snooze's+ // return ticket is spent — the thread is on top NOW, not on Tuesday.+ const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];+ if (thread.settledOverride === "settled") {+ promotionEvents.push({+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.unsettled",+ payload: {+ threadId: command.threadId,+ reason: "user",+ updatedAt: occurredAt,+ },+ });+ }+ if (thread.snoozedUntil != null) {+ promotionEvents.push({+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.unsnoozed",+ payload: {+ threadId: command.threadId,+ reason: "user",+ updatedAt: occurredAt,+ },+ });+ }+ return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;+ }++ case "thread.unpin": {+ const thread = yield* requireThreadNotArchived({+ readModel,+ command,+ threadId: command.threadId,+ });+ // Idempotent by re-emission (see thread.settle): unpinning a thread+ // that is not pinned lands on the same null state without churning+ // updatedAt.+ const alreadyUnpinned = thread.pinnedAt == null;+ const occurredAt = yield* nowIso;+ return {+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.unpinned",+ payload: {+ threadId: command.threadId,+ updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,+ },+ };+ }+case "thread.meta.update": {const thread = yield* requireThread({readModel,diff --git a/apps/server/src/orchestration/projector.pinned.test.ts b/apps/server/src/orchestration/projector.pinned.test.tsnew file mode 100644index 000000000..35bd06366--- /dev/null+++ b/apps/server/src/orchestration/projector.pinned.test.ts@@ -0,0 +1,77 @@+import {+ CommandId,+ EventId,+ ProjectId,+ ThreadId,+ type OrchestrationEvent,+} from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { createEmptyReadModel, projectEvent } from "./projector.ts";++function makeEvent(input: {+ readonly sequence: number;+ readonly type: OrchestrationEvent["type"];+ readonly payload: unknown;+}): OrchestrationEvent {+ return {+ sequence: input.sequence,+ eventId: EventId.make(`event-${input.sequence}`),+ type: input.type,+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ occurredAt: "2026-01-01T00:00:00.000Z",+ commandId: CommandId.make(`command-${input.sequence}`),+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: input.payload as never,+ } as OrchestrationEvent;+}++it.effect("projects pin lifecycle events", () =>+ Effect.gen(function* () {+ const now = "2026-01-01T00:00:00.000Z";+ const created = yield* projectEvent(+ createEmptyReadModel(now),+ makeEvent({+ sequence: 1,+ type: "thread.created",+ payload: {+ threadId: ThreadId.make("thread-1"),+ projectId: ProjectId.make("project-1"),+ title: "Thread",+ modelSelection: { provider: "codex", model: "gpt-5.4" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ }),+ );+ expect(created.threads[0]?.pinnedAt ?? null).toBeNull();++ const pinned = yield* projectEvent(+ created,+ makeEvent({+ sequence: 2,+ type: "thread.pinned",+ payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },+ }),+ );+ expect(pinned.threads[0]?.pinnedAt).toBe(now);++ const unpinned = yield* projectEvent(+ pinned,+ makeEvent({+ sequence: 3,+ type: "thread.unpinned",+ payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },+ }),+ );+ expect(unpinned.threads[0]?.pinnedAt).toBeNull();+ }),+);diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex 4be5843c1..ed4b084e4 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -23,7 +23,9 @@ import {ThreadProposedPlanUpsertedPayload,ThreadRuntimeModeSetPayload,ThreadSettledPayload,+ ThreadPinnedPayload,ThreadSnoozedPayload,+ ThreadUnpinnedPayload,ThreadUnarchivedPayload,ThreadUnsettledPayload,ThreadUnsnoozedPayload,@@ -394,6 +396,28 @@ export function projectEvent(})),);+ case "thread.pinned":+ return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(+ Effect.map((payload) => ({+ ...nextBase,+ threads: updateThread(nextBase.threads, payload.threadId, {+ pinnedAt: payload.pinnedAt,+ updatedAt: payload.updatedAt,+ }),+ })),+ );++ case "thread.unpinned":+ return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(+ Effect.map((payload) => ({+ ...nextBase,+ threads: updateThread(nextBase.threads, payload.threadId, {+ pinnedAt: null,+ updatedAt: payload.updatedAt,+ }),+ })),+ );+case "thread.meta-updated":return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(Effect.map((payload) => ({diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.tsindex 4763f5656..71d7df566 100644--- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts+++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts@@ -95,6 +95,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {settledAt: null,snoozedUntil: null,snoozedAt: null,+ pinnedAt: null,latestUserMessageAt: null,pendingApprovalCount: 0,pendingUserInputCount: 0,@@ -157,6 +158,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {settledAt: "2026-03-25T00:00:00.000Z",snoozedUntil: "2026-03-26T09:00:00.000Z",snoozedAt: "2026-03-25T00:00:00.000Z",+ pinnedAt: "2026-03-25T00:00:00.000Z",latestUserMessageAt: null,pendingApprovalCount: 0,pendingUserInputCount: 0,@@ -175,6 +177,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {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");+ assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");// Un-settle to the keep-active pin and wake the snooze; confirm the// flips persist.@@ -184,6 +187,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {settledAt: null,snoozedUntil: null,snoozedAt: null,+ pinnedAt: null,});const repersisted = yield* threads.getById({threadId: ThreadId.make("thread-settled"),@@ -193,6 +197,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {assert.strictEqual(updated?.settledAt, null);assert.strictEqual(updated?.snoozedUntil, null);assert.strictEqual(updated?.snoozedAt, null);+ assert.strictEqual(updated?.pinnedAt, null);}),);});diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.tsindex eb423aef9..0e2adeecf 100644--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts@@ -47,6 +47,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {settled_at,snoozed_until,snoozed_at,+ pinned_at,title_regeneration_request_id,title_regeneration_started_at,latest_user_message_at,@@ -72,6 +73,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {${row.settledAt},${row.snoozedUntil},${row.snoozedAt},+ ${row.pinnedAt},${row.titleRegenerationRequestId ?? null},${row.titleRegenerationStartedAt ?? null},${row.latestUserMessageAt},@@ -97,6 +99,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {settled_at = excluded.settled_at,snoozed_until = excluded.snoozed_until,snoozed_at = excluded.snoozed_at,+ pinned_at = excluded.pinned_at,title_regeneration_request_id = excluded.title_regeneration_request_id,title_regeneration_started_at = excluded.title_regeneration_started_at,latest_user_message_at = excluded.latest_user_message_at,@@ -129,6 +132,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -163,6 +167,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {settled_at AS "settledAt",snoozed_until AS "snoozedUntil",snoozed_at AS "snoozedAt",+ pinned_at AS "pinnedAt",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex b24aeb503..1309cd7ef 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -48,6 +48,7 @@ import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";+import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";/*** Migration loader with all migrations defined inline.@@ -95,6 +96,7 @@ export const migrationEntries = [[33, "ProjectionThreadsSettled", Migration0033],[34, "ProjectionThreadsSnoozed", Migration0034],[35, "ProjectionThreadTitleRegeneration", Migration0035],+ [36, "ProjectionThreadsPinned", Migration0036],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/036_ProjectionThreadsPinned.ts b/apps/server/src/persistence/Migrations/036_ProjectionThreadsPinned.tsnew file mode 100644index 000000000..c96e4693f--- /dev/null+++ b/apps/server/src/persistence/Migrations/036_ProjectionThreadsPinned.ts@@ -0,0 +1,16 @@+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 === "pinned_at")) {+ yield* sql`+ ALTER TABLE projection_threads+ ADD COLUMN pinned_at TEXT+ `;+ }+});diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.tsindex ea1b011be..a0cee8e32 100644--- a/apps/server/src/persistence/Services/ProjectionThreads.ts+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts@@ -41,6 +41,7 @@ export const ProjectionThread = Schema.Struct({settledAt: Schema.NullOr(IsoDateTime),snoozedUntil: Schema.NullOr(IsoDateTime),snoozedAt: Schema.NullOr(IsoDateTime),+ pinnedAt: Schema.NullOr(IsoDateTime),titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),latestUserMessageAt: Schema.NullOr(IsoDateTime),diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsxindex 0fd513d36..e8f7f8bbb 100644--- a/apps/web/src/components/SidebarV2.tsx+++ b/apps/web/src/components/SidebarV2.tsx@@ -28,6 +28,7 @@ import {GitBranchIcon,EllipsisIcon,MessageSquareIcon,+ PinIcon,PlusIcon,SearchIcon,ServerIcon,@@ -394,6 +395,11 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {settlementSupported: boolean;// Same contract for thread.snooze/unsnooze.snoozeSupported: boolean;+ // Renders the pin glyph. Pinned cards keep the full settle/snooze quick+ // actions: settling clears the pin server-side, and snoozing hides the+ // card until wake with the pin intact underneath. Pin/unpin themselves+ // live in the context menu only.+ isPinned: boolean;// Compact wake countdown ("2h") for rows in the snoozed shelf.snoozeWakeLabelText: string | null;// When a snooze ended (timer or early wake); drives the Woke pill until@@ -939,6 +945,13 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {) : (<span className="flex-1" />)}+ {props.isPinned ? (+ <PinIcon+ aria-label="Pinned"+ role="img"+ className="size-3 shrink-0 text-muted-foreground/65"+ />+ ) : null}{/* The visible state owns this slot's width: status at rest,actions on hover/keyboard focus or while the popover is open. Keepingthe hidden state out of flow lets the project label reclaim@@ -1186,8 +1199,15 @@ export default function SidebarV2() {const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);- const { settleThread, unsettleThread, snoozeThread, unsnoozeThread, deleteThread } =- useThreadActions();+ const {+ settleThread,+ unsettleThread,+ snoozeThread,+ unsnoozeThread,+ pinThread,+ unpinThread,+ deleteThread,+ } = useThreadActions();const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {reportFailure: false,});@@ -1564,76 +1584,91 @@ export default function SidebarV2() {// merging, no optimistic holds. Archived threads remain hidden here —// archive keeps its original "remove from sidebar" meaning.const serverConfigs = useAtomValue(environmentServerConfigsAtom);- const { activeThreads, snoozedThreads, settledThreads, snoozeNow } = useMemo(() => {- const now = `${nowMinute}:00.000Z`;- // Snooze classification uses a REAL clock, not the quantized minute:- // wake times are second-precise and a woken thread must not linger on- // the shelf for the rest of the minute. snoozeWakeTick re-runs this- // memo exactly at the next wake boundary.- void snoozeWakeTick;- const preciseNow = new Date().toISOString();- const visible = threads.filter(- (thread) =>- thread.archivedAt === null &&- (scopedProjectKeys === null ||- scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),- );- const active: EnvironmentThreadShell[] = [];- const snoozed: EnvironmentThreadShell[] = [];- const settled: EnvironmentThreadShell[] = [];- for (const thread of visible) {- // Threads on servers without the settlement capability (old server,- // or descriptor not loaded yet) never classify as settled: the user- // could neither un-settle nor pin them, so auto-settling them would- // strand rows in a tail with no working affordances.- const supportsSettlement =- serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;- const supportsSnooze =- serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;- const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));- const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;- // Snooze outranks settled classification: an explicitly snoozed thread- // belongs to the shelf even if it would also auto-settle (the shelf's- // wake time is a stronger statement about when it matters again).- if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {- snoozed.push(thread);- } else if (- supportsSettlement &&- effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })- ) {- settled.push(thread);- } else {- active.push(thread);+ const { pinnedThreads, activeThreads, snoozedThreads, settledThreads, snoozeNow } =+ useMemo(() => {+ const now = `${nowMinute}:00.000Z`;+ // Snooze classification uses a REAL clock, not the quantized minute:+ // wake times are second-precise and a woken thread must not linger on+ // the shelf for the rest of the minute. snoozeWakeTick re-runs this+ // memo exactly at the next wake boundary.+ void snoozeWakeTick;+ const preciseNow = new Date().toISOString();+ const visible = threads.filter(+ (thread) =>+ thread.archivedAt === null &&+ (scopedProjectKeys === null ||+ scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),+ );+ const pinned: EnvironmentThreadShell[] = [];+ const active: EnvironmentThreadShell[] = [];+ const snoozed: EnvironmentThreadShell[] = [];+ const settled: EnvironmentThreadShell[] = [];+ for (const thread of visible) {+ // Threads on servers without the settlement capability (old server,+ // or descriptor not loaded yet) never classify as settled: the user+ // could neither un-settle nor pin them, so auto-settling them would+ // strand rows in a tail with no working affordances.+ const supportsSettlement =+ serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement ===+ true;+ const supportsSnooze =+ serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;+ const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));+ const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;+ // Snooze outranks everything, including a pin: "hide until Tuesday"+ // temporarily suspends "keep on top". The pin survives underneath —+ // pinned cards are creation-ordered, so on wake the thread reappears+ // at its original spot in the pinned block. (For unpinned threads+ // this is also the snooze-beats-auto-settle rule: the wake time is a+ // stronger statement about when the thread matters again.)+ if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {+ snoozed.push(thread);+ // A pin otherwise overrides the lifecycle: pinned threads never+ // auto-settle out of sight. (The decider clears settled state on+ // pin and the pin on settle, so pin-vs-settled conflicts only+ // arise from stale or raced writes.)+ } else if (thread.pinnedAt != null) {+ pinned.push(thread);+ } else if (+ supportsSettlement &&+ effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })+ ) {+ settled.push(thread);+ } else {+ active.push(thread);+ }}- }- return {- activeThreads: sortThreadsForSidebarV2(active),- // Soonest wake first: "what comes back next" is the shelf's question.- snoozedThreads: snoozed.toSorted(- (left, right) =>- firstValidTimestampMs(left.snoozedUntil ?? null) -- firstValidTimestampMs(right.snoozedUntil ?? null),- ),- settledThreads: sortSettledThreadsForSidebarV2(settled),- snoozeNow: preciseNow,- };- }, [- autoSettleAfterDays,- changeRequestStateByKey,- nowMinute,- scopedProjectKeys,- serverConfigs,- snoozeWakeTick,- threads,- ]);+ return {+ // Same static creation order as the inbox: a pin freezes prominence,+ // it does not introduce a new ordering scheme.+ pinnedThreads: sortThreadsForSidebarV2(pinned),+ activeThreads: sortThreadsForSidebarV2(active),+ // Soonest wake first: "what comes back next" is the shelf's question.+ snoozedThreads: snoozed.toSorted(+ (left, right) =>+ firstValidTimestampMs(left.snoozedUntil ?? null) -+ firstValidTimestampMs(right.snoozedUntil ?? null),+ ),+ settledThreads: sortSettledThreadsForSidebarV2(settled),+ snoozeNow: preciseNow,+ };+ }, [+ autoSettleAfterDays,+ changeRequestStateByKey,+ nowMinute,+ scopedProjectKeys,+ serverConfigs,+ snoozeWakeTick,+ threads,+ ]);const threadSearchInputRef = useRef<HTMLInputElement>(null);const [threadSearchQuery, setThreadSearchQuery] = useState("");const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0);const isSearchingThreads = threadSearchQuery.trim().length > 0;const searchableThreads = useMemo(- () => [...activeThreads, ...snoozedThreads, ...settledThreads],- [activeThreads, settledThreads, snoozedThreads],+ () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads],+ [activeThreads, pinnedThreads, settledThreads, snoozedThreads],);const threadSearchResults = useMemo(() => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery),@@ -1737,8 +1772,8 @@ export default function SidebarV2() {}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);const orderedThreads = useMemo(- () => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],- [activeThreads, visibleSnoozedThreads, renderedSettledThreads],+ () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],+ [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads],);const orderedThreadKeys = useMemo(() =>@@ -2040,6 +2075,42 @@ export default function SidebarV2() {},[unsnoozeThread],);+ const attemptPin = useCallback(+ (threadRef: ScopedThreadRef) => {+ void (async () => {+ const result = await pinThread(threadRef);+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Failed to pin thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ })();+ },+ [pinThread],+ );+ const attemptUnpin = useCallback(+ (threadRef: ScopedThreadRef) => {+ void (async () => {+ const result = await unpinThread(threadRef);+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Failed to unpin thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ })();+ },+ [unpinThread],+ );// One snooze per thread at a time — same double-dispatch guard as settle.const snoozingThreadKeysRef = useRef(new Set<string>());const attemptSnooze = useCallback(@@ -2203,7 +2274,8 @@ export default function SidebarV2() {// Post-settle navigation must skip threads settling in this same// batch — they are all leaving the card block together. Rows that// are already explicitly settled are skipped: nothing to do on a- // valid mixed selection.+ // valid mixed selection. Pinned rows ARE included: the decider+ // clears the pin as part of settling, so they park like the rest.const coSettlingKeys = new Set(threadKeys);for (const threadKey of threadKeys) {const thread = threadByKeyRef.current.get(threadKey);@@ -2300,12 +2372,15 @@ export default function SidebarV2() {true;const supportsSnooze =serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;+ const supportsPinning =+ serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinning === true;const supportsTitleRegeneration =serverConfigs.get(thread.environmentId)?.environment.capabilities.threadTitleRegeneration === true;const isRegeneratingTitle = thread.titleRegeneration != null;const isSettled = settledThreadKeysRef.current.has(threadKey);const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);+ const isPinned = thread.pinnedAt != null;// Presets resolve at menu-open time (same as the popover).const snoozePresets = resolveSnoozePresets(new Date());const clicked = await settlePromise(() =>@@ -2319,6 +2394,16 @@ export default function SidebarV2() {},]: []),+ ...(supportsPinning+ ? [+ isPinned+ ? { id: "unpin", label: "Unpin thread" }+ : { id: "pin", label: "Pin thread" },+ ]+ : []),+ // Both lifecycle actions stay available on pinned threads:+ // settling clears the pin ("done" beats "keep on top"), and+ // snoozing hides the card until wake with the pin intact....(supportsSettlement? [isSettled@@ -2400,6 +2485,12 @@ export default function SidebarV2() {case "unsnooze":attemptUnsnooze(threadRef);return;+ case "pin":+ attemptPin(threadRef);+ return;+ case "unpin":+ attemptUnpin(threadRef);+ return;case "rename":startThreadRename(threadRef, thread.title);return;@@ -2474,8 +2565,10 @@ export default function SidebarV2() {})();},[+ attemptPin,attemptSettle,attemptSnooze,+ attemptUnpin,attemptUnsettle,attemptUnsnooze,confirmThreadDelete,@@ -2830,7 +2923,7 @@ export default function SidebarV2() {{(() => {const renderThreadRow = (thread: EnvironmentThreadShell,- section: "active" | "snoozed" | "settled",+ section: "pinned" | "active" | "snoozed" | "settled",) => {const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id),@@ -2839,7 +2932,7 @@ export default function SidebarV2() {// row: every other thread is a full card. Density comes// from users (or the auto rules) actually parking work,// not from the sidebar second-guessing what still matters.- const isCard = section === "active";+ const isCard = section === "active" || section === "pinned";const rowVariant = isCard ? "card" : "slim";return (<SidebarV2Row@@ -2870,6 +2963,7 @@ export default function SidebarV2() {serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true}+ isPinned={section === "pinned"}snoozeWakeLabelText={section === "snoozed" && thread.snoozedUntil != null? snoozeWakeLabel(thread.snoozedUntil, {@@ -2912,9 +3006,25 @@ export default function SidebarV2() {/>);};- const items: ReactNode[] = activeThreads.map((thread) =>- renderThreadRow(thread, "active"),+ // Pinned block: full cards above the inbox, closed by a+ // thin divider (the pin glyphs carry the meaning, so no+ // header text). Vanishes entirely at count 0.+ const items: ReactNode[] = pinnedThreads.map((thread) =>+ renderThreadRow(thread, "pinned"),);+ if (pinnedThreads.length > 0) {+ items.push(+ <li+ key="pinned-divider"+ aria-hidden+ data-testid="sidebar-v2-pinned-divider"+ className="mx-2.5 my-1.5 h-px list-none bg-sidebar-border/60"+ />,+ );+ }+ for (const thread of activeThreads) {+ items.push(renderThreadRow(thread, "active"));+ }// Snoozed shelf: between the inbox and Settled — out of the// way, never gone. The header always renders while anything// is snoozed (the count is the whole footprint when@@ -3006,7 +3116,11 @@ export default function SidebarV2() {</TooltipProvider>) : null}{!isSearchingThreads &&- activeThreads.length + snoozedThreads.length + settledThreads.length === 0 ? (+ pinnedThreads.length ++ activeThreads.length ++ snoozedThreads.length ++ settledThreads.length ===+ 0 ? (<div className="flex flex-col items-center gap-2 px-2 py-6 text-center text-xs text-muted-foreground/60">{projects.length === 0 ? (<>diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.tsindex 91a3779a0..96ec64555 100644--- a/apps/web/src/hooks/useThreadActions.ts+++ b/apps/web/src/hooks/useThreadActions.ts@@ -21,6 +21,7 @@ import { useNewThreadHandler } from "./useHandleNewThread";import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";import { readLocalApi } from "../localApi";import {+ readEnvironmentSupportsPinning,readEnvironmentSupportsSettlement,readEnvironmentSupportsSnooze,readEnvironmentThreadRefs,@@ -94,6 +95,18 @@ export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoo}}+export class ThreadPinningUnsupportedError extends Schema.TaggedErrorClass<ThreadPinningUnsupportedError>()(+ "ThreadPinningUnsupportedError",+ {+ environmentId: EnvironmentId,+ threadId: ThreadId,+ },+) {+ override get message(): string {+ return "This environment's server does not support pinning yet. Update the server to use Pin.";+ }+}+export function useThreadActions() {const closeTerminal = useAtomCommand(terminalEnvironment.close);const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {@@ -111,6 +124,12 @@ export function useThreadActions() {const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {reportFailure: false,});+ const pinThreadMutation = useAtomCommand(threadEnvironment.pin, {+ reportFailure: false,+ });+ const unpinThreadMutation = useAtomCommand(threadEnvironment.unpin, {+ reportFailure: false,+ });const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {reportFailure: false,});@@ -472,6 +491,47 @@ export function useThreadActions() {[unsettleThreadMutation],);+ const pinThread = useCallback(+ async (target: ScopedThreadRef) => {+ // Version skew: never send the command to a server that predates it.+ if (!readEnvironmentSupportsPinning(target.environmentId)) {+ return AsyncResult.failure(+ Cause.fail(+ new ThreadPinningUnsupportedError({+ environmentId: target.environmentId,+ threadId: target.threadId,+ }),+ ),+ );+ }+ return pinThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ });+ },+ [pinThreadMutation],+ );++ const unpinThread = useCallback(+ async (target: ScopedThreadRef) => {+ if (!readEnvironmentSupportsPinning(target.environmentId)) {+ return AsyncResult.failure(+ Cause.fail(+ new ThreadPinningUnsupportedError({+ environmentId: target.environmentId,+ threadId: target.threadId,+ }),+ ),+ );+ }+ return unpinThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ });+ },+ [unpinThreadMutation],+ );+const snoozeThread = useCallback(async (target: ScopedThreadRef, snoozedUntil: string) => {// Version skew: never send the command to a server that predates it.@@ -565,14 +625,18 @@ export function useThreadActions() {unsettleThread,snoozeThread,unsnoozeThread,+ pinThread,+ unpinThread,}),[archiveThread,confirmAndDeleteThread,deleteThread,+ pinThread,settleThread,snoozeThread,unarchiveThread,+ unpinThread,unsettleThread,unsnoozeThread,],diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex 552468e04..3f8297304 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -241,6 +241,15 @@ export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boo);}+/** Whether the environment's server understands thread.pin/unpin.+ Same version-skew contract as settlement. */+export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {+ return (+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities+ .threadPinning === true+ );+}+export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));}diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex ad25d6544..ee200d3a2 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -39,6 +39,8 @@ 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 PinThreadInput = CommandInput<"thread.pin">;+export type UnpinThreadInput = CommandInput<"thread.unpin">;export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;@@ -197,6 +199,26 @@ export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Eff});});+export const pinThread: (input: PinThreadInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.pinThread",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "thread.pin",+ commandId: yield* commandId(input),+ });+});++export const unpinThread: (input: UnpinThreadInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.unpinThread",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "thread.unpin",+ commandId: yield* commandId(input),+ });+});+export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn("EnvironmentCommands.updateThreadMetadata",)(function* (input) {diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex 6c128eb01..2eabc5aec 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -12,11 +12,13 @@ import {type RevertThreadCheckpointInput,type SetThreadInteractionModeInput,type SetThreadRuntimeModeInput,+ type PinThreadInput,type SettleThreadInput,type SnoozeThreadInput,type StartThreadTurnInput,type StopThreadSessionInput,type UnarchiveThreadInput,+ type UnpinThreadInput,type UnsettleThreadInput,type UnsnoozeThreadInput,type UpdateThreadMetadataInput,@@ -29,11 +31,13 @@ import {revertThreadCheckpoint,setThreadInteractionMode,setThreadRuntimeMode,+ pinThread,settleThread,snoozeThread,startThreadTurn,stopThreadSession,unarchiveThread,+ unpinThread,unsettleThread,unsnoozeThread,updateThreadMetadata,@@ -50,11 +54,13 @@ export type {RevertThreadCheckpointInput,SetThreadInteractionModeInput,SetThreadRuntimeModeInput,+ PinThreadInput,SettleThreadInput,SnoozeThreadInput,StartThreadTurnInput,StopThreadSessionInput,UnarchiveThreadInput,+ UnpinThreadInput,UnsettleThreadInput,UnsnoozeThreadInput,UpdateThreadMetadataInput,@@ -118,6 +124,18 @@ export function createThreadEnvironmentAtoms<R, E>(scheduler,concurrency,}),+ pin: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:pin",+ execute: (input: PinThreadInput) => pinThread(input),+ scheduler,+ concurrency,+ }),+ unpin: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:unpin",+ execute: (input: UnpinThreadInput) => unpinThread(input),+ scheduler,+ concurrency,+ }),updateMetadata: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:update-metadata",execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex eac5ab87d..30e8ef582 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -61,6 +61,7 @@ export function mergeEnvironmentThread(settledAt: shell.settledAt,snoozedUntil: shell.snoozedUntil,snoozedAt: shell.snoozedAt,+ pinnedAt: shell.pinnedAt,session: shell.session,};}diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.tsindex dffae6cf6..8b2479c7a 100644--- a/packages/client-runtime/src/state/threadReducer.test.ts+++ b/packages/client-runtime/src/state/threadReducer.test.ts@@ -231,6 +231,55 @@ describe("applyThreadDetailEvent", () => {});});+ describe("thread.pinned / thread.unpinned", () => {+ it("sets pinnedAt", () => {+ const pinnedAt = "2026-04-01T05:00:00.000Z";+ const result = applyThreadDetailEvent(baseThread, {+ ...baseEventFields,+ sequence: 5,+ occurredAt: pinnedAt,+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.pinned",+ payload: {+ threadId: ThreadId.make("thread-1"),+ pinnedAt,+ updatedAt: pinnedAt,+ },+ });++ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.pinnedAt).toBe(pinnedAt);+ }+ });++ it("clears pinnedAt", () => {+ const pinnedThread: OrchestrationThread = {+ ...baseThread,+ pinnedAt: "2026-04-01T05:00:00.000Z",+ };+ const updatedAt = "2026-04-01T06:00:00.000Z";+ const result = applyThreadDetailEvent(pinnedThread, {+ ...baseEventFields,+ sequence: 6,+ occurredAt: updatedAt,+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.unpinned",+ payload: {+ threadId: ThreadId.make("thread-1"),+ updatedAt,+ },+ });++ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.pinnedAt).toBeNull();+ }+ });+ });+describe("thread.meta-updated", () => {it("patches title and branch", () => {const result = applyThreadDetailEvent(baseThread, {diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex 7b484b835..0c6649f38 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -167,6 +167,26 @@ export function applyThreadDetailEvent(},};+ case "thread.pinned":+ return {+ kind: "updated",+ thread: {+ ...thread,+ pinnedAt: event.payload.pinnedAt,+ updatedAt: event.payload.updatedAt,+ },+ };++ case "thread.unpinned":+ return {+ kind: "updated",+ thread: {+ ...thread,+ pinnedAt: null,+ updatedAt: event.payload.updatedAt,+ },+ };+// ── Thread metadata ─────────────────────────────────────────────case "thread.meta-updated":return {diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex b49860c63..4c44a9596 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -47,6 +47,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({/** Server understands thread.snooze / thread.unsnooze commands. Sameversion-skew contract as threadSettlement. */threadSnooze: Schema.optionalKey(Schema.Boolean),+ /** Server understands thread.pin / thread.unpin commands. Same+ version-skew contract as threadSettlement. */+ threadPinning: Schema.optionalKey(Schema.Boolean),/** Server understands regenerateTitle on thread.meta.update. Absent onolder servers, so clients hide the action instead of sending it. */threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex af93a7b8f..d09e63136 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -373,6 +373,10 @@ export const OrchestrationThread = Schema.Struct({// Optional so payloads from pre-snooze servers still decode.snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),+ // A pin overrides the settled/snoozed lifecycle: while pinnedAt is set the+ // thread renders in the pinned block and never classifies into a shelf.+ // Optional so payloads from pre-pinning servers still decode.+ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),// Pending-only state. Optional so older servers remain compatible.titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),deletedAt: Schema.NullOr(IsoDateTime),@@ -427,6 +431,7 @@ export const OrchestrationThreadShell = Schema.Struct({settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),+ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),session: Schema.NullOr(OrchestrationSession),latestUserMessageAt: Schema.NullOr(IsoDateTime),@@ -621,6 +626,18 @@ const ThreadUnsnoozeCommand = Schema.Struct({reason: Schema.Literal("user"),});+const ThreadPinCommand = Schema.Struct({+ type: Schema.Literal("thread.pin"),+ commandId: CommandId,+ threadId: ThreadId,+});++const ThreadUnpinCommand = Schema.Struct({+ type: Schema.Literal("thread.unpin"),+ commandId: CommandId,+ threadId: ThreadId,+});+const ThreadMetaUpdateCommand = Schema.Struct({type: Schema.Literal("thread.meta.update"),commandId: CommandId,@@ -774,6 +791,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([ThreadUnsettleCommand,ThreadSnoozeCommand,ThreadUnsnoozeCommand,+ ThreadPinCommand,+ ThreadUnpinCommand,ThreadMetaUpdateCommand,ThreadRuntimeModeSetCommand,ThreadInteractionModeSetCommand,@@ -799,6 +818,8 @@ export const ClientOrchestrationCommand = Schema.Union([ThreadUnsettleCommand,ThreadSnoozeCommand,ThreadUnsnoozeCommand,+ ThreadPinCommand,+ ThreadUnpinCommand,ThreadMetaUpdateCommand,ThreadRuntimeModeSetCommand,ThreadInteractionModeSetCommand,@@ -914,6 +935,8 @@ export const OrchestrationEventType = Schema.Literals(["thread.unsettled","thread.snoozed","thread.unsnoozed",+ "thread.pinned",+ "thread.unpinned","thread.meta-updated","thread.runtime-mode-set","thread.interaction-mode-set",@@ -1022,6 +1045,17 @@ export const ThreadUnsnoozedPayload = Schema.Struct({updatedAt: IsoDateTime,});+export const ThreadPinnedPayload = Schema.Struct({+ threadId: ThreadId,+ pinnedAt: IsoDateTime,+ updatedAt: IsoDateTime,+});++export const ThreadUnpinnedPayload = Schema.Struct({+ threadId: ThreadId,+ updatedAt: IsoDateTime,+});+export const ThreadMetaUpdatedPayload = Schema.Struct({threadId: ThreadId,title: Schema.optional(TrimmedNonEmptyString),@@ -1216,6 +1250,16 @@ export const OrchestrationEvent = Schema.Union([type: Schema.Literal("thread.unsnoozed"),payload: ThreadUnsnoozedPayload,}),+ Schema.Struct({+ ...EventBaseFields,+ type: Schema.Literal("thread.pinned"),+ payload: ThreadPinnedPayload,+ }),+ Schema.Struct({+ ...EventBaseFields,+ type: Schema.Literal("thread.unpinned"),+ payload: ThreadUnpinnedPayload,+ }),Schema.Struct({...EventBaseFields,type: Schema.Literal("thread.meta-updated"),