diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 233957ad056c2..14e6f619d7cb5 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -38,6 +38,8 @@ import { groupSidebarThreadsByProject, resolveSidebarFolderDot, sidebarFolderExpansionKeys, + freshSessionThreadKeys, + placeSystemScheduledThreads, } from "./Sidebar.logic"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { @@ -46,7 +48,14 @@ import { } from "@t3tools/client-runtime/state/thread-sort"; import { resolveProjectExpanded } from "../uiStateStore"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; -import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + RunId, + SYS_DAEMON_STANDING_ROLE, + ThreadId, +} from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, @@ -1739,3 +1748,65 @@ describe("shouldCreateNewThreadInCurrentProject", () => { expect(shouldCreateNewThreadInCurrentProject(true, 2, 2)).toBe(true); }); }); + +describe("placeSystemScheduledThreads", () => { + const chatId = ThreadId.make("chat"); + const scheduledId = ThreadId.make("scheduled"); + const failedScheduledId = ThreadId.make("scheduled-failed"); + const daemonId = ThreadId.make("sys-daemon"); + const liveDaemonId = ThreadId.make("live-daemon"); + const keyOf = (id: ThreadId) => scopedThreadKey(scopeThreadRef(localEnvironmentId, id)); + const threads = [ + { id: chatId, title: "Ordinary chat", standingRole: null, failed: false }, + { id: scheduledId, title: "Nightly digest", standingRole: null, failed: false }, + { id: failedScheduledId, title: "Failed digest", standingRole: null, failed: true }, + { + id: daemonId, + title: "Headless daemon", + standingRole: SYS_DAEMON_STANDING_ROLE, + failed: false, + }, + { id: liveDaemonId, title: "Daemon", standingRole: "Keeps watches", failed: false }, + ]; + const scheduledThreadKeys = freshSessionThreadKeys([ + { + environmentId: localEnvironmentId, + tasks: [ + { threadId: scheduledId, threadMode: "fresh_session" as const }, + { threadId: failedScheduledId, threadMode: "fresh_session" as const }, + { threadId: chatId, threadMode: "continue" as const }, + { threadId: null, threadMode: "new_thread" as const }, + { threadId: liveDaemonId }, + ], + }, + ]); + const place = (revealed: boolean) => + placeSystemScheduledThreads({ + threads, + revealed, + scheduledThreadKeys, + keyOf: (thread) => keyOf(thread.id), + standingRoleOf: (thread) => thread.standingRole, + }); + + it("keeps the section absent until one toggle, then hides it again", () => { + expect(SYS_DAEMON_STANDING_ROLE).toBe("sys:daemon"); + expect([...scheduledThreadKeys]).toEqual([keyOf(scheduledId), keyOf(failedScheduledId)]); + + const hidden = place(false); + expect(hidden.section).toBeNull(); + expect(hidden.rest.map((thread) => thread.id)).toEqual([chatId, liveDaemonId]); + + const revealed = place(true); + expect(revealed.section?.map((thread) => thread.id)).toEqual([ + scheduledId, + failedScheduledId, + daemonId, + ]); + expect(revealed.section?.some((thread) => thread.id === chatId)).toBe(false); + expect(revealed.section?.some((thread) => thread.id === liveDaemonId)).toBe(false); + expect(revealed.section?.some((thread) => thread.failed)).toBe(true); + + expect(place(false).section).toBeNull(); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 7645e67651c6d..79263ffcbcd1c 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -17,6 +17,8 @@ import { } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; import { + scheduledTaskThreadMode, + SYS_DAEMON_STANDING_ROLE, type ContextMenuItem, type EnvironmentId, type ResolvedKeybindingsConfig, @@ -1481,3 +1483,72 @@ export function sortScopedProjectsForSidebar< left.id.localeCompare(right.id), ); } + +/** + * A thread belongs on the System shelf when its standing role is the daemon + * marker, or when a fresh-session scheduled task keeps it as its thread. + * Continue-mode tasks stay in the conversation they were bound to. + */ +export function isSystemScheduledThread(input: { + readonly key: string; + readonly standingRole: string | null; + readonly scheduledThreadKeys: ReadonlySet; +}): boolean { + return ( + input.standingRole === SYS_DAEMON_STANDING_ROLE || input.scheduledThreadKeys.has(input.key) + ); +} + +/** Scoped keys of fresh-session scheduled tasks. Unbound and continue-mode tasks are left out. */ +export function freshSessionThreadKeys( + entries: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly tasks: ReadonlyArray<{ + readonly threadId: ThreadId | null; + readonly threadMode?: "new_thread" | "continue" | "fresh_session" | undefined; + }>; + }>, +): ReadonlySet { + const keys = new Set(); + for (const entry of entries) { + for (const task of entry.tasks) { + if (task.threadId === null) continue; + if (scheduledTaskThreadMode(task) !== "fresh_session") continue; + keys.add(scopedThreadKey(scopeThreadRef(entry.environmentId, task.threadId))); + } + } + return keys; +} + +/** + * Pulls system threads out of the founder list. `section` is null until the + * shelf is opened, and then it keeps every match, including a failed run. + */ +export function placeSystemScheduledThreads(input: { + readonly threads: readonly T[]; + readonly revealed: boolean; + readonly scheduledThreadKeys: ReadonlySet; + readonly keyOf: (thread: T) => string; + readonly standingRoleOf: (thread: T) => string | null; +}): { + readonly rest: T[]; + readonly system: T[]; + readonly section: T[] | null; +} { + const rest: T[] = []; + const system: T[] = []; + for (const thread of input.threads) { + if ( + isSystemScheduledThread({ + key: input.keyOf(thread), + standingRole: input.standingRoleOf(thread), + scheduledThreadKeys: input.scheduledThreadKeys, + }) + ) { + system.push(thread); + } else { + rest.push(thread); + } + } + return { rest, system, section: input.revealed ? system : null }; +} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 28325237e0e5d..239e8c3e40ee8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -34,7 +34,7 @@ import { discardComposerDraft } from "../lib/discardComposerDraft"; import { requestCustomSnooze } from "./CustomSnoozeDialog"; import { useAtomValue } from "@effect/atom-react"; import * as Option from "effect/Option"; -import { Atom } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; import * as Schema from "effect/Schema"; import { DndContext, @@ -179,7 +179,7 @@ import { useSidebarThreadShells, } from "../state/linkedSidebar"; import { environmentPresentations } from "../state/presentation"; -import { primaryServerKeybindingsAtom } from "../state/server"; +import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server"; import { environmentProjects } from "../state/projects"; import { threadEnvironment } from "../state/threads"; import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf"; @@ -199,6 +199,7 @@ import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { runBotMenuAction } from "./bots/botMenuActions"; import { partitionBotGroups, sortBotThreads, splitStandingThreads } from "./bots/botPresence"; import { SidebarBotsGroup } from "./sidebar/SidebarBotsGroup"; +import { SystemScheduledShelf } from "./sidebar/SystemScheduledShelf"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -210,7 +211,9 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + freshSessionThreadKeys, groupSidebarThreadsByProject, + isSystemScheduledThread, sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, @@ -359,6 +362,33 @@ const sidebarProviderEntriesAtom = Atom.make((get) => { return !changed && previous !== null ? previous : next; }).pipe(Atom.withLabel("sidebar-provider-entries")); +const EMPTY_SCHEDULED_THREAD_KEYS: ReadonlySet = new Set(); + +function sameStringSet(left: ReadonlySet, right: ReadonlySet): boolean { + if (left.size !== right.size) return false; + for (const value of left) { + if (!right.has(value)) return false; + } + return true; +} + +// Fresh-session scheduled threads, keyed so a task tick with the same bindings does not rerender. +const scheduledThreadKeysAtom = Atom.make((get) => { + const keys = freshSessionThreadKeys( + [...get(environmentPresentations.serverConfigsAtom).keys()].map((environmentId) => ({ + environmentId, + tasks: + AsyncResult.getOrElse( + get(serverEnvironment.scheduledTasksLive({ environmentId, input: {} })), + () => null, + )?.tasks ?? [], + })), + ); + const previous = Option.getOrNull(get.self>()); + if (previous !== null && sameStringSet(previous, keys)) return previous; + return keys.size === 0 ? EMPTY_SCHEDULED_THREAD_KEYS : keys; +}).pipe(Atom.withLabel("sidebar-scheduled-thread-keys")); + const EMPTY_PROVIDER_ENTRIES: ReadonlyMap = new Map(); const EMPTY_THREADS: readonly EnvironmentThreadShell[] = []; @@ -368,6 +398,7 @@ const SETTLED_TAIL_PAGE_COUNT = 25; const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar:settled-expanded"; const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar:snoozed-expanded"; const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded"; +const SYSTEM_SHELF_REVEALED_KEY = "t3code:sidebar:system-scheduled"; const inboxReturns = createInboxReturnTracker(); @@ -989,6 +1020,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const scheduledThreadKeys = useAtomValue(scheduledThreadKeysAtom); + const [systemShelfRevealed, setSystemShelfRevealed] = useLocalStorage( + SYSTEM_SHELF_REVEALED_KEY, + false, + Schema.Boolean, + ); const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); const timestampFormat = useClientSettings((s) => s.timestampFormat); @@ -1206,10 +1243,19 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve coverage: (environmentId) => threadListFilterCoverage(environmentId, threadListFilter), } : null; + // Fresh-session scheduled threads and the sys:daemon standing role leave the + // founder list. The System shelf is the only place they are drawn. + const isSystemThread = (thread: EnvironmentThreadShell) => + isSystemScheduledThread({ + key: threadShellKey(thread), + standingRole: thread.standing?.role ?? null, + scheduledThreadKeys, + }); + const conversationThreads = inboxThreads.filter((thread) => !isSystemThread(thread)); const listedThreads = promotingDraftThreadKeys.length === 0 - ? inboxThreads - : inboxThreads.map((thread) => + ? conversationThreads + : conversationThreads.map((thread) => promotingDraftThreadKeys.includes(threadShellKey(thread)) ? asLaunchingThread(thread) : thread, @@ -1289,6 +1335,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const scopedProjectGroups = revealWidensScope ? [] : chosenProjectGroups; const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs); const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys; + // The shelf ignores the inbox filter, so one click still shows an Agents-filed + // run. A hidden machine stays hidden while the list filter applies. + const systemThreads = filterSidebarV2VisibleThreads( + (listFilterApplies + ? threads.filter( + (thread) => !threadListFilter.hiddenEnvironmentIds.includes(thread.environmentId), + ) + : threads + ).filter(isSystemThread), + scopedProjectKeys, + delegatedUnderParent, + ); const threadSearch = useThreadSearch( connectedEnvironmentIds, threadSearchQuery, @@ -1466,11 +1524,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // Ranked across environments as the palette ranks them, so one // environment's list does not sit above another's better matches; rows // already shown keep their places while slower environments answer. + const searchCorpus = isSearchingThreads + ? [...searchableThreads, ...systemThreads] + : searchableThreads; const threadByMatchKey = threadSearch.matches.length === 0 ? null : new Map( - searchableThreads.map((thread) => [ + searchCorpus.map((thread) => [ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }), thread, ]), @@ -1502,7 +1563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); if (messageOrder !== shownMessageOrder) setShownMessageOrder(messageOrder); const { titleMatches: threadTitleResults, contentMatches: threadContentResults } = - searchSidebarThreads(searchableThreads, threadSearchQuery, new Set(messageOrder.keys)); + searchSidebarThreads(searchCorpus, threadSearchQuery, new Set(messageOrder.keys)); const threadSearchResults = [...threadTitleResults, ...threadContentResults]; // Only rows listed for their messages show one, and open find on it. const threadSearchMatchByKey = new Map( @@ -3449,6 +3510,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve {!isSearchingThreads && !hasProjectFolders && visibleDraftSessionCount === 0 && + systemThreads.length === 0 && botThreads.length + pinnedThreads.length + activeThreads.length + @@ -3854,6 +3916,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve + setSystemShelfRevealed((value) => !value)} + onOpen={navigateToThread} + /> ) : null} diff --git a/apps/web/src/components/sidebar/SystemScheduledShelf.tsx b/apps/web/src/components/sidebar/SystemScheduledShelf.tsx new file mode 100644 index 0000000000000..514513cb6802e --- /dev/null +++ b/apps/web/src/components/sidebar/SystemScheduledShelf.tsx @@ -0,0 +1,83 @@ +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { CircleAlertIcon } from "lucide-react"; + +import { cn } from "~/lib/utils"; +import { CollapsibleSectionHeader } from "../ui/collapsible-section-header"; + +/** + * System and scheduled runs sit under the founder shelves. The header is the + * toggle; the rows stay absent until it is opened. + */ +export function SystemScheduledShelf(props: { + readonly threads: readonly EnvironmentThreadShell[]; + readonly revealed: boolean; + readonly activeThreadKey: string | null; + readonly onToggle: () => void; + readonly onOpen: (threadRef: ScopedThreadRef) => void; +}) { + if (props.threads.length === 0 && !props.revealed) return null; + const rows = props.revealed + ? [...props.threads].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)) + : []; + return ( +
+ {props.threads.length}} + > + System / Scheduled + + {props.revealed ? ( +
    + {rows.map((thread) => { + const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const failed = thread.runtime?.status === "failed"; + const error = failed ? thread.runtime?.lastError : null; + return ( +
  • + +
  • + ); + })} +
+ ) : null} +
+ ); +} diff --git a/packages/contracts/src/threadStanding.ts b/packages/contracts/src/threadStanding.ts index 042c7b08e1ecd..0da430f97fdf1 100644 --- a/packages/contracts/src/threadStanding.ts +++ b/packages/contracts/src/threadStanding.ts @@ -9,6 +9,12 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts"; * watch list, standing is what the thread is. */ +/** + * Exact standing role the sidebar System shelf matches. + * Nothing assigns this role, so a live Daemon thread stays where it is. + */ +export const SYS_DAEMON_STANDING_ROLE = "sys:daemon"; + /** Built-in avatars clients ship. Unknown ids from a newer peer fall back to the first one. */ export const THREAD_STANDING_AVATAR_IDS = [ "bolt",