Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion apps/web/src/components/Sidebar.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {
groupSidebarThreadsByProject,
resolveSidebarFolderDot,
sidebarFolderExpansionKeys,
freshSessionThreadKeys,
placeSystemScheduledThreads,
} from "./Sidebar.logic";
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
Expand All @@ -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,
Expand Down Expand Up @@ -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();
});
});
71 changes: 71 additions & 0 deletions apps/web/src/components/Sidebar.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string>;
}): 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<string> {
const keys = new Set<string>();
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<T>(input: {
readonly threads: readonly T[];
readonly revealed: boolean;
readonly scheduledThreadKeys: ReadonlySet<string>;
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 };
}
81 changes: 75 additions & 6 deletions apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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";
Expand All @@ -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";
Expand All @@ -210,7 +211,9 @@ import {
import {
applySidebarThreadDrop,
filterSidebarV2VisibleThreads,
freshSessionThreadKeys,
groupSidebarThreadsByProject,
isSystemScheduledThread,
sidebarFolderExpansionKeys,
buildBulkTitleRegenerationContextMenuItem,
buildBulkUnpinContextMenuItem,
Expand Down Expand Up @@ -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<string> = new Set();

function sameStringSet(left: ReadonlySet<string>, right: ReadonlySet<string>): 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<ReadonlySet<string>>());
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<string, SidebarProviderEntry> = new Map();
const EMPTY_THREADS: readonly EnvironmentThreadShell[] = [];

Expand All @@ -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();

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
]),
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -3449,6 +3510,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
{!isSearchingThreads &&
!hasProjectFolders &&
visibleDraftSessionCount === 0 &&
systemThreads.length === 0 &&
botThreads.length +
pinnedThreads.length +
activeThreads.length +
Expand Down Expand Up @@ -3854,6 +3916,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
</ul>
</SortableContext>
</DndContext>
<SystemScheduledShelf
threads={systemThreads}
revealed={systemShelfRevealed}
activeThreadKey={routeRowThreadKey}
onToggle={() => setSystemShelfRevealed((value) => !value)}
onOpen={navigateToThread}
/>
</TooltipProvider>
) : null}
</SidebarGroup>
Expand Down
Loading
Loading