diff --git a/README.md b/README.md index da9c31fab7486..14a37ca74579a 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,6 @@ This is a personal fork of [pingdotgg/t3code](https://github.com/pingdotgg/t3cod - **Switch back to the previous thread.** In the desktop app, Ctrl+Tab toggles between the current and previously viewed thread or unsent draft, including across projects and environments. It works while typing in the composer or terminal and follows the focused pane in split view. The pair lasts for the current app session. On web and desktop, snoozing or archiving the open thread yourself returns you to that previous thread, unless **Return to previous thread** is off in Settings → Extras; an agent's or scheduled archive leaves it on screen. -- **Move a thread to the top.** The command palette moves the current thread to the top of Pinned, Active, or its custom group, counting members hidden by filters or folded groups, and keeps its group. Pinned always accepts it. Active and custom groups accept it only while the Working shelf is off outside folder mode; otherwise they sort by activity and the action is not offered there. Drafts, subagents, side chats, and archived, snoozed, or settled threads can't be moved this way. - - **Custom thread groups.** Organize threads from any project or environment into named groups. Pick a group on the new-thread view or with **New thread in group** in the command palette, and move threads (several at once with Cmd/Ctrl-click) by dragging, from their menu, or from the palette. The Thread groups dialog places each group above or below Active; mobile shows the same groups and order, and **Arrange threads** moves threads between them. Forks join their source's group, and pinned, snoozed, settled, and archived threads return to their group. Settings → Extras can add a Thread groups toolbar button. - **Rename and snooze from the command palette.** Rename current thread edits the title inside the palette input. Snooze current thread lists your configured snooze options with their wake times, including Until it's done, and also parses a typed time such as `45m`, `2pm`, or `fri 9am`; a snoozed thread offers Wake current thread instead. Both are available as unbound keybinding commands (Thread: Rename, Thread: Snooze) that open the palette straight into that step. Thread: Snooze Until Done snoozes a working thread until it's done in one keystroke and opens the snooze step otherwise; Settings → Extras can make it always open the snooze step. @@ -41,7 +39,7 @@ This is a personal fork of [pingdotgg/t3code](https://github.com/pingdotgg/t3cod - **Hideable panel toggles** — Settings → Extras → Panels can hide the terminal drawer and right panel toggles from the thread header, in single and split view, for keyboard-driven use; the header then stops reserving room for them and the shortcuts keep working. They show by default. - **Mobile swipe-right actions** — swiping a thread row right reveals Pin (Unpin on a pinned row), Fork, and Archive, in that order. Pin needs a server that supports pinning and Fork a conversation that can be forked; each has a twin in the row's long-press menu. Pin and Archive keep you on the list; Fork opens the new copy. Archive stays innermost, so a full swipe right still archives, or asks first when the thread has queued messages. - **Session import** — import an external Claude Code or Codex CLI session as a native thread from Project Settings, into the project checkout or one of its existing worktrees; the native session continues in T3. Sessions already owned by a T3 thread show as linked; importing one again forks it into a fresh thread, so the original keeps its session. -- **Recent archived threads and archive browser** — the thread list ends with a folded **Archived** shelf of your most recently archived threads on web, desktop, and mobile; set its size in Settings → Extras (Settings → General on mobile). Opening one shows it as archived, and Unarchive or a new message restores it. On web and desktop the shelf follows the sidebar's project and environment filters, and the full archive in Settings groups threads by repository across environments, follows the Settings scope, and is searchable by title, project, path, environment, or model. Archived subagent threads stay out of both the shelf and the archive on every client. The command palette adds **Open archived threads**, also scoped to the current project. Tag hiding also applies to the shelf; while enabled, archived threads outside the live list cannot be opened. +- **Recent archived threads and archive browser** — the thread list ends with a folded **Archived** shelf of your most recently archived threads on web, desktop, and mobile; set its size in Settings → Extras (Settings → General on mobile). Opening one shows it as archived, and Unarchive or a new message restores it. On web and desktop the shelf follows the sidebar's project and environment filters, and the full archive in Settings groups threads by repository across environments, follows the Settings scope, and is searchable by title, project, path, environment, or model. Archived subagent threads stay out of both the shelf and the archive on every client. Tag hiding also applies to the shelf; while enabled, archived threads outside the live list cannot be opened. - **Offline mobile archive queue** — archiving or unarchiving on mobile while an environment is disconnected takes effect immediately on the phone: an archived thread moves to the Archived shelf marked Pending, with an Undo action, and the change syncs on reconnect. Archiving a thread that is still working queues an archive-when-done, and cancelling a pending archive works offline too. Discarding queued messages asks first, from the phone's last known state; a confirmed discard archives right away on reconnect, and an archive the server refuses shows why. A later choice for the same thread replaces the pending one. - **Thread-list filters** — on web and desktop, the thread sidebar narrows the list along independent axes: - **Project** — show any combination of projects, or hide individual projects; both choices persist across relaunches. diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index def1434174045..f5a04bde09cee 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -8,7 +8,6 @@ import type { Thread } from "../types"; import { makeThreadFixture } from "../test-fixtures"; import { buildArchiveCurrentThreadAction, - buildArchivedThreadsActionItems, buildCurrentThreadActionItems, newThreadNoProjectIndex, buildNestedSearchItems, @@ -433,40 +432,6 @@ describe("buildSnoozeThreadViewItems", () => { }); }); -describe("buildArchivedThreadsActionItems", () => { - it("offers only the unfiltered entry without a resolvable project", () => { - expect( - buildArchivedThreadsActionItems({ - projectFilterKey: null, - projectTitle: "Ignored", - icon: null, - openArchived: vi.fn(), - }).map((item) => item.value), - ).toEqual(["action:archived-threads"]); - }); - - it("adds a project-scoped entry naming the current project", async () => { - const openArchived = vi.fn(async () => undefined); - const items = buildArchivedThreadsActionItems({ - projectFilterKey: "github.com/t3tools/t3code", - projectTitle: "T3 Code", - icon: null, - openArchived, - }); - - expect(items.map((item) => item.value)).toEqual([ - "action:archived-threads", - "action:archived-threads-in-project", - ]); - expect(items[1]).toMatchObject({ title: "Open archived threads in T3 Code" }); - - await items[0]?.run(); - expect(openArchived).toHaveBeenCalledWith(null); - await items[1]?.run(); - expect(openArchived).toHaveBeenCalledWith("github.com/t3tools/t3code"); - }); -}); - describe("linked pull request thread navigation", () => { it("keeps archived relations searchable and routes them through the PR environment", async () => { const environmentId = EnvironmentId.make("remote"); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 7a8c05f9bb670..d391083624fd5 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -866,50 +866,6 @@ export function buildSnoozeThreadViewItems(input: { return items; } -export function buildArchivedThreadsActionItems(input: { - /** Logical group key of the open thread's project, when there is one. */ - readonly projectFilterKey: string | null; - readonly projectTitle: string | null; - readonly icon: ReactNode; - readonly openArchived: (projectFilterKey: string | null) => Promise; -}): CommandPaletteActionItem[] { - const items: CommandPaletteActionItem[] = [ - { - kind: "action", - value: "action:archived-threads", - searchTerms: ["open archived threads", "archived", "archive", "history", "settings"], - title: "Open archived threads", - icon: input.icon, - run: async () => { - await input.openArchived(null); - }, - }, - ]; - - if (input.projectFilterKey !== null && input.projectTitle !== null) { - const projectFilterKey = input.projectFilterKey; - items.push({ - kind: "action", - value: "action:archived-threads-in-project", - searchTerms: [ - "open archived threads", - "archived", - "archive", - "project", - "current project", - input.projectTitle, - ], - title: `Open archived threads in ${input.projectTitle}`, - icon: input.icon, - run: async () => { - await input.openArchived(projectFilterKey); - }, - }); - } - - return items; -} - export type BuildThreadActionItemsThread = Pick< SidebarThreadSummary, | "archivedAt" diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 173f17c80e790..2f33063dc55ce 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -92,7 +92,6 @@ import { GitForkIcon, MessageSquareDashedIcon, GroupIcon, - ArrowUpToLineIcon, LinkIcon, MessageSquareIcon, NotebookPenIcon, @@ -184,9 +183,7 @@ import { usePrimaryEnvironmentId, } from "../state/environments"; import { - readEnvironmentServerConfigLoaded, readEnvironmentSupportsSnoozeUntilDone, - readThreadShells, useProjects, useServerConfigs, useThreadShell, @@ -195,7 +192,6 @@ import { useHiddenThreadKeys, useEnvironmentThreadRefs, useVisibleThreadShells, - useThreadShells, waitForProject, } from "../state/entities"; import { useIsLabsPanelProject } from "../state/labs"; @@ -297,7 +293,6 @@ import { } from "./CommandPalette.logic"; import { useThreadGroupCatalog } from "../hooks/useThreadGroups"; import { groupMovableThreads, moveThreadsToGroup } from "../lib/threadGroupMove"; -import { planThreadMoveToTop } from "../lib/threadMoveToTop"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { openThreadGroupsDialog } from "./sidebar/threadGroupsDialogStore"; import { threadGroupId } from "@t3tools/shared/threadGroups"; @@ -436,10 +431,6 @@ function threadActionIcon(id: CommandPaletteThreadActionId): ReactNode { } } -// Fork: the dialog unmounts between invocations; keep an unfinished reorder -// across openings. -const pendingMovesToTop = new Set(); - async function reportThreadActionFailure( title: string, run: () => Promise>, @@ -457,22 +448,6 @@ async function reportThreadActionFailure( return result._tag === "Success"; } -// Stops on failure; each successful key write remains a valid placement. -async function writeMoveToTopKeys( - assignments: ReadonlyArray<{ readonly threadRef: ScopedThreadRef; readonly orderKey: string }>, - reorder: ( - threadRef: ScopedThreadRef, - orderKey: string, - ) => Promise>, -): Promise { - for (const assignment of assignments) { - const moved = await reportThreadActionFailure("Failed to move thread to top", () => - reorder(assignment.threadRef, assignment.orderKey), - ); - if (!moved) return; - } -} - export function CommandPalette({ children }: { children: ReactNode }) { useCommandPaletteMount(); const state = useCommandPaletteStore(); @@ -679,8 +654,6 @@ function OpenCommandPaletteDialog(props: { unsnoozeThread, forkThread, setThreadCustomGroup, - reorderActiveThread, - reorderPinnedThread, } = useThreadActions(); // Fork: custom thread groups. const customGroupCatalog = useThreadGroupCatalog(); @@ -692,14 +665,10 @@ function OpenCommandPaletteDialog(props: { reportFailure: false, }); const timestampFormat = useClientSettings((s) => s.timestampFormat); - // Snooze state, presets and move-to-top plans read the clock at minute precision. + // Snooze state and presets read the clock at minute precision. const nowMinute = useNowMinute(); const renderNow = new Date(`${nowMinute}:00.000Z`); const snoozeShortcutUntilDone = useClientSettings((s) => s.snoozeShortcutUntilDone); - // The sidebar's Working shelf and folder mode sort Active by activity, not order keys. - const activeKeyOrdered = useClientSettings( - (s) => !s.sidebarWorkingShelfEnabled && !s.boringSidebarEnabled, - ); const paletteRouteTarget = useThreadRouteTarget(); const projects = useProjects(); const accentTint = useAccentTintSettings(); @@ -773,7 +742,6 @@ function OpenCommandPaletteDialog(props: { delegatedUnderParent, ), ); - const allThreads = useThreadShells(); const serverConfigs = useServerConfigs(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const providersByEnvironment = useEnvironmentProviders(); @@ -1972,52 +1940,6 @@ function OpenCommandPaletteDialog(props: { } } - // Fork: group-aware "Move to top", planned against the full group or pinned - // shelf so search, filters and folded groups cannot change what "top" is. - const canReorderSection = (environmentId: EnvironmentId) => serverConfigs.has(environmentId); - const moveToTopPlan = planThreadMoveToTop({ - threads: allThreads, - threadRef: currentThreadRef, - groups: customGroupCatalog.groups, - now: renderNow.toISOString(), - activeKeyOrdered, - canReorder: canReorderSection, - }); - if (moveToTopPlan !== null && currentThreadRef !== null) { - const threadRef = currentThreadRef; - actionItems.push({ - kind: "action", - value: "action:thread:move-to-top", - title: "Move current thread to top", - searchTerms: ["move", "top", "reorder", "group", "current thread"], - icon: , - ...(moveToTopPlan.disabledReason - ? { disabled: true, description: moveToTopPlan.disabledReason } - : {}), - run: async () => { - if (pendingMovesToTop.size > 0) return; - // Re-read shells at execution: a snooze or another client's reorder - // may have landed while the palette was open. - const plan = planThreadMoveToTop({ - threads: readThreadShells(), - threadRef, - groups: customGroupCatalog.groups, - // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) - now: new Date().toISOString(), - activeKeyOrdered, - canReorder: readEnvironmentServerConfigLoaded, - }); - if (plan === null || plan.disabledReason) return; - const moveKey = `${threadRef.environmentId}:${threadRef.threadId}`; - pendingMovesToTop.add(moveKey); - await writeMoveToTopKeys( - plan.assignments, - plan.section === "pinned" ? reorderPinnedThread : reorderActiveThread, - ).finally(() => pendingMovesToTop.delete(moveKey)); - }, - }); - } - // Fork: a sidebar multi-selection takes over the group move; rows on // servers without group support are left out of the count and the move. const selectedThreads = diff --git a/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx index b2355901ed952..1f57b26202c86 100644 --- a/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx +++ b/apps/web/src/components/desktop/DesktopThreadLinkCoordinator.tsx @@ -11,7 +11,7 @@ import { } from "../../desktopThreadLink"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { readThreadShell } from "../../state/entities"; -import { orchestrationEnvironment } from "../../state/orchestration"; +import { archivedSnapshotAtom } from "../../lib/archivedThreadsState"; import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment"; import { environmentShell } from "../../state/shell"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../../threadRoutes"; @@ -44,10 +44,7 @@ function waitForThreadList(environmentId: EnvironmentId): Promise { async function hasArchivedThread(threadRef: ScopedThreadRef): Promise { const result = await executeAtomQuery( appAtomRegistry, - orchestrationEnvironment.archivedShellSnapshot({ - environmentId: threadRef.environmentId, - input: {}, - }), + archivedSnapshotAtom(threadRef.environmentId), { label: "thread link archived lookup", reportFailure: false, diff --git a/apps/web/src/components/labs/LabParts.tsx b/apps/web/src/components/labs/LabParts.tsx index bb24ba57ddae0..855a4f001bc3a 100644 --- a/apps/web/src/components/labs/LabParts.tsx +++ b/apps/web/src/components/labs/LabParts.tsx @@ -7,7 +7,7 @@ import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect, useState } from "react"; -import { liveArchivedShellSnapshotAtom } from "../../lib/archivedThreadsState"; +import { archivedSnapshotAtom } from "../../lib/archivedThreadsState"; import { cn } from "~/lib/utils"; import { useThreadShell } from "../../state/entities"; import { appAtomRegistry } from "../../rpc/atomRegistry"; @@ -117,9 +117,7 @@ function archivedOwnerShell( environmentId: EnvironmentId, threadId: string, ): EnvironmentThreadShell | null { - const snapshot = Option.getOrNull( - AsyncResult.value(get(liveArchivedShellSnapshotAtom(environmentId))), - ); + const snapshot = Option.getOrNull(AsyncResult.value(get(archivedSnapshotAtom(environmentId)))); const thread = snapshot?.threads.find((candidate) => candidate.id === threadId); return thread ? presentThreadShell(environmentId, thread) : null; } diff --git a/apps/web/src/components/sidebar/sidebarActiveWork.test.ts b/apps/web/src/components/sidebar/sidebarActiveWork.test.ts index fa2c2a4c828df..4333b3658f269 100644 --- a/apps/web/src/components/sidebar/sidebarActiveWork.test.ts +++ b/apps/web/src/components/sidebar/sidebarActiveWork.test.ts @@ -1,48 +1,10 @@ import { EnvironmentId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { - isSidebarActiveWorkThread, - matchesSidebarActiveWorkFilter, - nextActiveWorkThreadKeys, -} from "./sidebarActiveWork"; +import { matchesSidebarActiveWorkFilter, nextActiveWorkThreadKeys } from "./sidebarActiveWork"; import { makeThreadFixture } from "../../test-fixtures"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; -describe("isSidebarActiveWorkThread", () => { - const runtime = { - status: "running" as const, - activeRunId: null, - providerInstanceId: ProviderInstanceId.make("codex"), - providerName: "Codex", - lastError: null, - updatedAt: "2026-03-09T10:00:00.000Z", - }; - const ready = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null }; - - it("keeps marked threads even when nothing runs", () => { - expect(isSidebarActiveWorkThread(ready)).toBe(false); - expect( - isSidebarActiveWorkThread({ ...ready, activeMarkedAt: "2026-03-09T10:00:00.000Z" }), - ).toBe(true); - }); - - it("keeps running threads and threads that need the user", () => { - expect(isSidebarActiveWorkThread({ ...ready, runtime })).toBe(true); - expect(isSidebarActiveWorkThread({ ...ready, hasPendingApprovals: true })).toBe(true); - expect(isSidebarActiveWorkThread({ ...ready, hasPendingUserInput: true })).toBe(true); - }); - - it("drops finished and failed threads", () => { - expect( - isSidebarActiveWorkThread({ ...ready, runtime: { ...runtime, status: "completed" } }), - ).toBe(false); - expect(isSidebarActiveWorkThread({ ...ready, runtime: { ...runtime, status: "failed" } })).toBe( - false, - ); - }); -}); - describe("active work filter session", () => { const now = "2026-10-30T12:00:00.000Z"; const key = (thread: ReturnType) => @@ -51,6 +13,14 @@ describe("active work filter session", () => { const liveEnvironmentIds = new Set([thread.environmentId]); const finished = { ...thread, activeMarkedAt: null }; const other = { ...thread, environmentId: EnvironmentId.make("other") }; + const runtime = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: now, + }; const options = { retainedKeys: new Set(), includeDone: false, @@ -58,6 +28,18 @@ describe("active work filter session", () => { now, }; + it.each([ + { change: { runtime: { ...runtime, status: "running" as const } }, admitted: true }, + { change: { hasPendingApprovals: true }, admitted: true }, + { change: { hasPendingUserInput: true }, admitted: true }, + { change: { runtime: { ...runtime, status: "failed" as const } }, admitted: false }, + ])("admits unmarked threads that run or need the user: %o", ({ change, admitted }) => { + const candidate = { ...finished, ...change }; + expect(nextActiveWorkThreadKeys([], true, [candidate], now, liveEnvironmentIds)).toEqual( + admitted ? [key(candidate)] : [], + ); + }); + it("retains activity, admits later activity, and resets on disable", () => { const bothLive = new Set([thread.environmentId, other.environmentId]); const first = nextActiveWorkThreadKeys([], true, [thread], now, bothLive); diff --git a/apps/web/src/components/sidebar/sidebarActiveWork.ts b/apps/web/src/components/sidebar/sidebarActiveWork.ts index 1ff2e763b06e8..56d5ec71efe96 100644 --- a/apps/web/src/components/sidebar/sidebarActiveWork.ts +++ b/apps/web/src/components/sidebar/sidebarActiveWork.ts @@ -2,7 +2,6 @@ import { useEffect, useState } from "react"; import * as Schema from "effect/Schema"; import type { EnvironmentId } from "@t3tools/contracts"; import { - isActiveWorkThread, matchesActiveWorkFilter, nextActiveWorkThreadKeys as nextSharedActiveWorkThreadKeys, } from "@t3tools/client-runtime/state/thread-active-work"; @@ -15,13 +14,6 @@ import { resolveThreadLastVisitedAt, } from "../Sidebar.logic"; -export function isSidebarActiveWorkThread( - thread: Parameters[0] & - Pick, -): boolean { - return isActiveWorkThread(thread, resolveSidebarThreadStatus); -} - export function nextActiveWorkThreadKeys( previous: readonly string[], enabled: boolean, diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts index ecbbeadca5132..9d81d930db976 100644 --- a/apps/web/src/lib/archivedThreadsState.ts +++ b/apps/web/src/lib/archivedThreadsState.ts @@ -16,15 +16,30 @@ import { import { Atom } from "effect/reactivity"; import { connectionAtomRuntime } from "../connection/runtime"; -import { orchestrationEnvironment } from "../state/orchestration"; import { serverEnvironment } from "../state/server"; import { environmentThreadShells } from "../state/threads"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; import { environmentShell } from "../state/shell"; -function archivedSnapshotAtom(environmentId: EnvironmentId) { - return orchestrationEnvironment.archivedShellSnapshot({ +// Fork: Settings, SP Labs, desktop links, and the recent-shelf fallback share this archive +// query. It refetches on archive changes, unarchives included, and on snapshots that may hide +// changes made meanwhile. +const archiveRefreshAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const state = get(environmentShell.stateValueAtom(environmentId)); + return `${state.archiveInvalidationSequence ?? 0}:${state.generation}`; + }), +); + +const archivedShellSnapshot = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, { + label: "web:archived-shell-snapshot", + tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, + refreshTrigger: ({ environmentId }) => archiveRefreshAtom(environmentId), +}); + +export function archivedSnapshotAtom(environmentId: EnvironmentId) { + return archivedShellSnapshot({ environmentId, input: {}, }); @@ -43,24 +58,6 @@ export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentI appAtomRegistry.refresh(archivedSnapshotAtom(environmentId)); } -// Fork (SP Labs): the full archive for owner lookups, refetched after an archive change even one -// that happened while nothing read it, so a lab owner archived by an agent or another client -// resolves without a manual refresh. -const archiveInvalidationAtom = Atom.family((environmentId: EnvironmentId) => - Atom.make( - (get) => get(environmentShell.stateValueAtom(environmentId)).archiveInvalidationSequence ?? 0, - ), -); - -const liveArchivedShellSnapshot = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, { - label: "web:live-archived-shell-snapshot", - tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, - refreshTrigger: ({ environmentId }) => archiveInvalidationAtom(environmentId), -}); - -export const liveArchivedShellSnapshotAtom = (environmentId: EnvironmentId) => - liveArchivedShellSnapshot({ environmentId, input: {} }); - export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray): { readonly snapshots: ReadonlyArray; readonly error: string | null; diff --git a/apps/web/src/lib/threadMoveToTop.test.ts b/apps/web/src/lib/threadMoveToTop.test.ts deleted file mode 100644 index c0339c8b5b008..0000000000000 --- a/apps/web/src/lib/threadMoveToTop.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; -import { - sortActiveThreadsByOrderKey, - sortPinnedThreadsByOrderKey, -} from "@t3tools/client-runtime/state/thread-sort"; -import { EnvironmentId, ThreadId, type ThreadGroup } from "@t3tools/contracts"; -import { planThreadMoveToTop } from "./threadMoveToTop"; - -type Input = Parameters[0]; -type Row = Input["threads"][number]; -const local = EnvironmentId.make("local"); -const remote = EnvironmentId.make("remote"); -const now = "2026-09-16T12:00:00.000Z"; -const groups: ThreadGroup[] = [ - { id: "research", name: "Research", orderKey: "m", revision: "1", deleted: false }, -]; - -function row(id: string, overrides: Partial = {}): Row { - return { - id: ThreadId.make(id), - environmentId: local, - createdAt: now, - archivedAt: null, - settledOverride: null, - unsettledAt: null, - pinnedAt: null, - pinOrderKey: null, - activeOrderKey: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null }, - ...overrides, - }; -} - -function key(thread: Row) { - return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); -} - -function plan(threads: readonly Row[], moved: Row, overrides: Partial = {}) { - return planThreadMoveToTop({ - threads, - threadRef: scopeThreadRef(moved.environmentId, moved.id), - groups, - now, - activeKeyOrdered: true, - canReorder: () => true, - ...overrides, - }); -} - -function apply(threads: readonly Row[], result: NonNullable>) { - const assignments = new Map( - result.assignments.map(({ threadRef, orderKey }) => [scopedThreadKey(threadRef), orderKey]), - ); - return threads.map((thread) => { - const orderKey = assignments.get(key(thread)); - return orderKey === undefined - ? thread - : { ...thread, [result.section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: orderKey }; - }); -} - -describe("planThreadMoveToTop", () => { - it("reorders Pinned with one write, regardless of retained custom-group membership", () => { - const first = row("first", { pinnedAt: now, pinOrderKey: "f" }); - const moved = row("moved", { - pinnedAt: now, - pinOrderKey: "t", - customGroupId: "research", - }); - const active = row("active", { customGroupId: "research", activeOrderKey: "m" }); - const result = plan([first, moved, active], moved)!; - expect(result.section).toBe("pinned"); - expect(result.assignments).toHaveLength(1); - expect(sortPinnedThreadsByOrderKey(apply([first, moved], result)).map(key)).toEqual([ - key(moved), - key(first), - ]); - expect(apply([active], result)).toEqual([active]); - }); - - it("moves above new and reopened Active threads across environments, preserving the rest", () => { - const newest = row("same-id", { environmentId: remote }); - const reopened = row("reopened", { - createdAt: "2026-09-15T12:00:00.000Z", - unsettledAt: "2026-09-16T11:00:00.000Z", - }); - const moved = row("same-id", { activeOrderKey: "t" }); - const arranged = row("arranged", { activeOrderKey: "m" }); - const rows = [arranged, moved, reopened, newest]; - const result = plan(rows, moved)!; - expect(result.assignments).toHaveLength(4); - expect(sortActiveThreadsByOrderKey(apply(rows, result)).map(key)).toEqual([ - key(moved), - key(newest), - key(reopened), - key(arranged), - ]); - }); - - it("orders the full custom group while leaving other groups and shelves untouched", () => { - const first = row("first", { customGroupId: "research" }); - const moved = row("moved", { customGroupId: "research", activeOrderKey: "t" }); - const untouched = [ - row("active", { activeOrderKey: "m" }), - row("archived", { customGroupId: "research", archivedAt: now }), - row("settled", { customGroupId: "research", settledOverride: "settled" }), - row("snoozed", { - customGroupId: "research", - snoozedAt: now, - snoozedUntil: "2026-09-17T12:00:00.000Z", - }), - row("pinned", { customGroupId: "research", pinnedAt: now }), - ]; - const rows = [first, moved, ...untouched]; - const result = plan(rows, moved)!; - expect(result.assignments.map(({ threadRef }) => scopedThreadKey(threadRef))).toEqual([ - key(moved), - key(first), - ]); - expect(sortActiveThreadsByOrderKey(apply([first, moved], result)).map(key)).toEqual([ - key(moved), - key(first), - ]); - expect(apply(untouched, result)).toEqual(untouched); - expect(result.assignments.every(({ orderKey }) => orderKey !== "m")).toBe(true); - }); - - it("treats deleted group membership as Active, like the sidebar", () => { - const first = row("first", { activeOrderKey: "f" }); - const moved = row("moved", { customGroupId: "research", activeOrderKey: "t" }); - const result = plan([first, moved], moved, { - groups: groups.map((group) => ({ ...group, deleted: true })), - })!; - expect(sortActiveThreadsByOrderKey(apply([first, moved], result)).map(key)).toEqual([ - key(moved), - key(first), - ]); - }); - - it.each([ - { archivedAt: now }, - { settledOverride: "settled" as const }, - { snoozedAt: now, snoozedUntil: "2026-09-17T12:00:00.000Z", pinnedAt: now }, - { snoozedUntil: "2026-09-17T12:00:00.000Z" }, - ])("excludes unavailable lifecycle states: %j", (overrides) => { - const moved = row("moved", overrides); - expect(plan([row("first"), moved], moved)).toBeNull(); - }); - - it("allows an expired snooze and excludes drafts or missing threads", () => { - const moved = row("moved", { - snoozedUntil: "2026-09-16T11:00:00.000Z", - activeOrderKey: "t", - }); - const rows = [row("first", { activeOrderKey: "f" }), moved]; - expect(plan(rows, moved)?.assignments).toHaveLength(1); - expect(plan(rows, moved, { threadRef: null })).toBeNull(); - expect(plan(rows, row("draft"))).toBeNull(); - }); - - it("offers no Active or group move where the sidebar sorts them by activity", () => { - const pinned = row("pinned", { pinnedAt: now, pinOrderKey: "t" }); - const active = row("active", { activeOrderKey: "t" }); - const grouped = row("grouped", { customGroupId: "research", activeOrderKey: "t" }); - const rows = [row("first", { pinnedAt: now, pinOrderKey: "f" }), pinned, active, grouped]; - expect(plan(rows, active, { activeKeyOrdered: false })).toBeNull(); - expect(plan(rows, grouped, { activeKeyOrdered: false })).toBeNull(); - expect(plan(rows, pinned, { activeKeyOrdered: false })?.assignments).toHaveLength(1); - }); - - it("ignores subagents and side chats for rank and rewrites, but reserves their keys", () => { - const parent = ThreadId.make("parent"); - const subagent = row("subagent", { - activeOrderKey: "a", - lineage: { rootThreadId: parent, parentThreadId: parent, relationshipToParent: "subagent" }, - }); - const sideChat = row("side", { - lineage: { - rootThreadId: parent, - parentThreadId: parent, - relationshipToParent: null, - sideChat: true, - }, - }); - const moved = row("moved", { activeOrderKey: "f" }); - const rows = [subagent, sideChat, moved, row("last", { activeOrderKey: "t" })]; - expect(plan(rows, moved)).toMatchObject({ disabledReason: "Already at top" }); - expect(plan(rows, subagent)).toBeNull(); - const first = row("first"); - const result = plan([...rows, first], moved)!; - expect(result.assignments.map(({ threadRef }) => scopedThreadKey(threadRef))).not.toContain( - key(subagent), - ); - expect(result.assignments.every(({ orderKey }) => orderKey !== "a")).toBe(true); - }); - - it("does not write for an already-first or only thread", () => { - const moved = row("moved", { activeOrderKey: "f" }); - for (const rows of [[moved], [moved, row("last", { activeOrderKey: "t" })]]) { - expect(plan(rows, moved)).toMatchObject({ - assignments: [], - disabledReason: "Already at top", - }); - } - }); - - it("requires server support for every needed write, but allows read-only ordering anchors", () => { - const moved = row("moved", { activeOrderKey: "t" }); - const oldServer = row("first", { environmentId: remote }); - const canReorder: Input["canReorder"] = (environmentId) => environmentId === local; - expect(plan([oldServer, moved], moved, { canReorder })).toMatchObject({ - assignments: [], - disabledReason: expect.stringContaining("Update the servers"), - }); - expect( - plan([{ ...oldServer, activeOrderKey: "f" }, moved], moved, { canReorder })?.assignments, - ).toHaveLength(1); - expect(plan([oldServer, moved], oldServer, { canReorder })).toBeNull(); - }); -}); diff --git a/apps/web/src/lib/threadMoveToTop.ts b/apps/web/src/lib/threadMoveToTop.ts deleted file mode 100644 index 456f8e1c4a77b..0000000000000 --- a/apps/web/src/lib/threadMoveToTop.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { - effectiveSnoozed, - type ThreadSnoozeShell, -} from "@t3tools/client-runtime/state/thread-settled"; -import { - planPinnedReorder, - sortActiveThreadsByOrderKey, - sortPinnedThreadsByOrderKey, -} from "@t3tools/client-runtime/state/thread-sort"; -import { - isListedThreadLineage, - type EnvironmentId, - type ScopedThreadRef, - type ThreadGroup, -} from "@t3tools/contracts"; -import { threadGroupId } from "@t3tools/shared/threadGroups"; - -type OrderThread = ThreadSnoozeShell & - Pick< - EnvironmentThreadShell, - | "id" - | "environmentId" - | "createdAt" - | "unsettledAt" - | "archivedAt" - | "settledOverride" - | "pinnedAt" - | "pinOrderKey" - | "activeOrderKey" - | "customGroupId" - | "lineage" - >; - -interface ThreadMoveToTopPlan { - readonly section: "pinned" | "active"; - readonly assignments: ReadonlyArray<{ - readonly threadRef: ScopedThreadRef; - readonly orderKey: string; - }>; - readonly disabledReason?: string; -} - -function rowKey(thread: OrderThread): string { - return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); -} - -/** - * Plan against the full group so search, filters, and collapsed rows cannot change "top". - * `activeKeyOrdered`: whether Active and custom groups display in `activeOrderKey` order; - * the Working shelf and folder mode sort them by activity, so no Active move applies. - */ -export function planThreadMoveToTop(input: { - readonly threads: readonly OrderThread[]; - readonly threadRef: ScopedThreadRef | null; - readonly groups: readonly ThreadGroup[]; - readonly now: string; - readonly activeKeyOrdered: boolean; - readonly canReorder: (environmentId: EnvironmentId, section: "pinned" | "active") => boolean; -}): ThreadMoveToTopPlan | null { - if (input.threadRef === null) return null; - const movedKey = scopedThreadKey(input.threadRef); - const thread = input.threads.find((row) => rowKey(row) === movedKey); - const isEligible = (row: OrderThread) => - isListedThreadLineage(row.lineage) && - row.archivedAt === null && - row.settledOverride !== "settled" && - !effectiveSnoozed(row, { now: input.now }); - if (!thread || !isEligible(thread)) return null; - const section = thread.pinnedAt != null ? "pinned" : "active"; - if (section === "active" && !input.activeKeyOrdered) return null; - if (!input.canReorder(thread.environmentId, section)) return null; - const groupId = threadGroupId(thread, input.groups); - const members = input.threads.filter( - (row) => - isEligible(row) && - (section === "pinned" - ? row.pinnedAt != null - : row.pinnedAt == null && threadGroupId(row, input.groups) === groupId), - ); - const ordered = - section === "pinned" - ? sortPinnedThreadsByOrderKey(members) - : sortActiveThreadsByOrderKey(members); - if (rowKey(ordered[0]!) === movedKey) { - return { section, assignments: [], disabledReason: "Already at top" }; - } - const byKey = new Map(members.map((row) => [rowKey(row), row])); - const assignments = planPinnedReorder({ - orderedIds: [movedKey, ...ordered.map(rowKey).filter((key) => key !== movedKey)], - // Retained positions in other groups and shelves remain reserved, as in dragging. - keysById: new Map( - input.threads.map((row) => [ - rowKey(row), - section === "pinned" ? row.pinOrderKey : row.activeOrderKey, - ]), - ), - movedId: movedKey, - }).map(({ id, orderKey }) => { - const row = byKey.get(id)!; - return { threadRef: scopeThreadRef(row.environmentId, row.id), orderKey }; - }); - if (assignments.some(({ threadRef }) => !input.canReorder(threadRef.environmentId, section))) { - return { - section, - assignments: [], - disabledReason: "Update the servers for these threads to support ordering", - }; - } - return { section, assignments }; -} diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 948763e8e977c..7872198193879 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -159,11 +159,6 @@ position, so using **Un-settle** returns it to the top. Pinning and snoozing pre position until you move it again. Thread activity does not change the order. The settled shelf continues to use settlement time. -On web and desktop, **Move current thread to top** in the command palette moves the open thread to -the top of Pinned, Active, or its custom group without dragging. It counts group members hidden by -a filter or a collapsed group, so the thread lands above all of them. The action is unavailable for -drafts and for archived, snoozed, or settled threads. - If dragging is unavailable for one environment, update the T3 Code server running in that environment. Pinned and active reordering require server support. Threads from older servers keep their default order until the server is updated. diff --git a/packages/client-runtime/src/state/threadActiveWork.ts b/packages/client-runtime/src/state/threadActiveWork.ts index ac2ea45bf565d..137a253f3ddd1 100644 --- a/packages/client-runtime/src/state/threadActiveWork.ts +++ b/packages/client-runtime/src/state/threadActiveWork.ts @@ -19,7 +19,7 @@ const ACTIVE_WORK_STATUSES: ReadonlySet = new Set([ type ResolveStatus = (thread: T) => string; /** Marked threads plus threads that are running or need the user right now. */ -export function isActiveWorkThread>( +function isActiveWorkThread>( thread: T, status: ResolveStatus, ): boolean {