import { navigationKey, type DraftRow, type FamilyRequest, type NavDraft, type NavigationFilters, type NavigationGroup, type NavigationKey, type NavigationSettings, type NavigationView, type NavSession, type Row, type Section, type SectionHeading, type SectionKind, type SessionRow, type ShowCount, type RowsPerGroup, type Status, type ViewInput, } from "./contract" /** * Where every session appears: drafts first, then Pinned, the grouped list, the Running shelf and Archived. Always last * activity first, except inside Group by Manual, which keeps your order. With Subagents off, children never show and * their root carries their requests; with it on, they nest under it. Show limits the ungrouped list, Rows per group * each headed group; rows that need you, the selected row and the parents they nest under always show. */ export const navigationView: NavigationView = (input, settings) => { const sessions = new Map(input.sessions.map((session) => [session.key, session])) const request = familyRequests(input.sessions, settings.subagents) const parentOf = (session: NavSession) => session.parentID === undefined ? undefined : navigationKey(session.server, session.parentID) const needsYou = (session: NavSession) => request.has(session.key) const hidden = (session: NavSession) => input.hiddenUntilReply?.[session.key] !== undefined const active = (session: NavSession) => needsYou(session) || (!session.archived && !hidden(session)) const status = (session: NavSession): Status => request.get(session.key)?.kind ?? session.status const listed = (session: NavSession) => settings.subagents || parentOf(session) === undefined const shown = input.sessions.filter((session) => { if (!listed(session)) return false if (session.key !== input.selected && !active(session) && !settings.archived) return false return sessionMatches(session, status(session), input.view.filters) }) const pins = new Set(input.pins) const zoneOf = (session: NavSession): Zone => { if (pins.has(session.key) && (active(session) || session.key === input.selected)) return "pinned" if (!active(session) && settings.archived) return "archived" return "active" } const zones = new Map(shown.map((session) => [session.key, zoneOf(session)])) const attached = (session: NavSession) => { const parent = parentOf(session) if (parent === undefined) return false const parentZone = zones.get(parent) const own = zones.get(session.key) if (parentZone === undefined || own === "pinned") return false return (parentZone === "archived") === (own === "archived") } const children = Map.groupBy(shown.filter(attached), (session) => parentOf(session)) const compare = comparator(input, settings) const open = new Set(input.open) const row = (session: NavSession, depth: number): SessionRow => ({ kind: "session", key: session.key, session, status: status(session), request: request.get(session.key), depth, pinned: pins.has(session.key), open: open.has(session.key), selected: input.selected === session.key, group: input.groups.groups.find((group) => group.id === input.groups.membership[session.key]), surfaced: needsYou(session) && (session.archived || hidden(session)), archived: zones.get(session.key) === "archived", }) const flatten = (session: NavSession, depth: number): Entry[] => [ { row: row(session, depth), parent: depth > 0 ? parentOf(session) : undefined }, ...(children.get(session.key) ?? []).toSorted(compare).flatMap((child) => flatten(child, depth + 1)), ] const entries = (list: NavSession[], order = compare) => list.toSorted(order).flatMap((session) => flatten(session, 0)) const tops = shown.filter((session) => !attached(session)) const placed = tops.filter((session) => zones.get(session.key) === "active") const shelf = new Set( settings.runningAtBottom ? placed.filter((session) => status(session) === "working").map((item) => item.key) : [], ) const pinned = input.pins.flatMap((key) => { const session = sessions.get(key) return session !== undefined && zones.get(key) === "pinned" ? [session] : [] }) const archived = tops.filter((session) => zones.get(session.key) === "archived").toSorted(recent) const drafts = input.drafts .toSorted((a, b) => b.updated - a.updated) .flatMap((draft): Entry[] => draft.key === input.selected || draftMatches(draft, input.view.filters) ? [{ row: draftRow(draft, open.has(draft.key), input.selected === draft.key), parent: undefined }] : [], ) const grouped = groupedSpecs( placed.filter((session) => !shelf.has(session.key)), input, settings, request, entries, ) const specs: Spec[] = [ spec("drafts", "drafts", undefined, drafts), spec( "pinned", "pinned", { type: "pinned" }, pinned.flatMap((session) => flatten(session, 0)), ), ...grouped, spec( "working", "working", { type: "running" }, entries( placed.filter((session) => shelf.has(session.key)), started, ), ), spec( "archived", "archived", { type: "archived" }, archived.flatMap((session) => flatten(session, 0)), ), ] const sections = specs.flatMap((item) => item.entries.length > 0 || item.heading?.type === "group" ? [finish(item, input, settings)] : [], ) const base = input.sessions.filter((session) => listed(session) && (active(session) || settings.archived)) return { sections, order: sections.flatMap((section) => section.rows.map((item) => item.key)), empty: base.length === 0 && input.drafts.length === 0, filteredOut: (base.length > 0 || input.drafts.length > 0) && shown.length === 0 && drafts.length === 0, } } /** How many rows Show more adds to a section: Rows per group for a headed group, Show's step for the rest. */ export function moreStep(kind: SectionKind, settings: Pick) { if (kind === "group") return rowsPerGroupLimit(settings.rowsPerGroup) return settings.show === "30" ? 30 : 10 } /** * The request each session's row shows. A session's own request always counts; with Subagents off, a root also takes * the oldest request waiting anywhere below it, as production puts a family's requests on its root. */ export function familyRequests(sessions: NavSession[], subagents: boolean) { const own = (session: NavSession): FamilyRequest[] => (session.status === "approval" || session.status === "question") && session.requestSince !== undefined ? [{ key: session.key, kind: session.status, since: session.requestSince }] : [] const children = Map.groupBy( sessions.filter((session) => session.parentID !== undefined), (session) => navigationKey(session.server, session.parentID ?? ""), ) const below = (session: NavSession, seen: Set): FamilyRequest[] => (children.get(session.key) ?? []) .filter((child) => !seen.has(child.key)) .flatMap((child) => [...own(child), ...below(child, new Set([...seen, child.key]))]) return new Map( sessions.flatMap((session) => { const found = [ ...own(session), ...(subagents || session.parentID !== undefined ? [] : below(session, new Set([session.key]))), ] const oldest = found.toSorted((a, b) => a.since - b.since)[0] return oldest ? [[session.key, oldest] as const] : [] }), ) } const WEEK = 7 * 24 * 60 * 60 * 1000 type Zone = "pinned" | "archived" | "active" type Entry = { row: Row; parent: NavigationKey | undefined } type Spec = { id: string; kind: SectionKind; heading: SectionHeading | undefined; entries: Entry[] } type Bucket = { id: string; heading: SectionHeading; rank: number; name: string } type Order = (a: NavSession, b: NavSession) => number const spec = (id: string, kind: SectionKind, heading: SectionHeading | undefined, entries: Entry[]): Spec => ({ id, kind, heading, entries, }) const draftRow = (draft: NavDraft, open: boolean, selected: boolean): DraftRow => ({ kind: "draft", key: draft.key, draft, open, selected, }) const rowsPerGroupLimit = (value: RowsPerGroup) => (value === "all" ? Infinity : Number(value)) const showLimit = (show: ShowCount) => (show === "10" || show === "30" ? Number(show) : Infinity) const showSince = (show: ShowCount, now: number) => (show === "week" ? now - WEEK : -Infinity) const byKey: Order = (a, b) => { if (a.key === b.key) return 0 return a.key < b.key ? -1 : 1 } const recent: Order = (a, b) => b.activity - a.activity || byKey(a, b) const started: Order = (a, b) => (a.runSince ?? Number.MAX_SAFE_INTEGER) - (b.runSince ?? Number.MAX_SAFE_INTEGER) || byKey(a, b) const compareNames = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }) function groupedSpecs( sessions: NavSession[], input: ViewInput, settings: NavigationSettings, request: Map, entries: (sessions: NavSession[], order?: Order) => Entry[], ): Spec[] { if (settings.groupBy === "none") return [spec("main", "main", undefined, entries(sessions))] if (settings.groupBy === "status") { const sectionOf = (session: NavSession) => { if (request.has(session.key)) return "attention" if (session.status === "working") return "running" return "recent" } const waiting: Order = (a, b) => (request.get(a.key)?.since ?? 0) - (request.get(b.key)?.since ?? 0) || byKey(a, b) const orders = { attention: waiting, running: started, recent: undefined } return (["attention", "running", "recent"] as const).map((status) => spec( `status:${status}`, "group", { type: "status", status }, entries( sessions.filter((session) => sectionOf(session) === status), orders[status], ), ), ) } if (settings.groupBy === "manual") { const ids = new Set(input.groups.groups.map((group) => group.id)) return [ ...input.groups.groups.map((group: NavigationGroup) => spec( `group:${group.id}`, "group", { type: "group", group }, entries(sessions.filter((session) => input.groups.membership[session.key] === group.id)), ), ), spec( "main", "main", undefined, entries(sessions.filter((session) => !ids.has(input.groups.membership[session.key] ?? ""))), ), ] } const bucketOf = bucketer(input, settings.groupBy) const tagged = sessions.map((session) => ({ session, bucket: bucketOf(session) })) const buckets = [...new Map(tagged.map((item) => [item.bucket.id, item.bucket])).values()].toSorted( (a, b) => a.rank - b.rank || compareNames(a.name, b.name), ) return buckets.map((bucket) => spec( bucket.id, "group", bucket.heading, entries(tagged.flatMap((item) => (item.bucket.id === bucket.id ? [item.session] : []))), ), ) } function bucketer(input: ViewInput, groupBy: "project" | "server"): (session: NavSession) => Bucket { if (groupBy === "server") return (session) => { const index = input.servers.findIndex((server) => server.key === session.server) const name = input.servers[index]?.name ?? session.server return { id: `server:${session.server}`, heading: { type: "server", server: session.server, name }, rank: index === -1 ? input.servers.length : index, name, } } return (session) => { if (session.projectID === undefined) return { id: "project:none", heading: { type: "project", server: session.server, projectID: undefined, name: "" }, rank: 1, name: "", } const name = input.projects.find((project) => project.server === session.server && project.id === session.projectID)?.name ?? session.projectID return { id: `project:${navigationKey(session.server, session.projectID)}`, heading: { type: "project", server: session.server, projectID: session.projectID, name }, rank: 0, name, } } } /** Last activity first, always. Group by Manual keeps your order instead: sessions not yet ordered first, then yours. */ function comparator(input: ViewInput, settings: NavigationSettings): Order { if (settings.groupBy !== "manual") return recent const manual = new Map(input.groups.order.map((key, index) => [key, index])) return (a, b) => (manual.get(a.key) ?? -1) - (manual.get(b.key) ?? -1) || recent(a, b) } function projectFilterKey(server: string, projectID: string | undefined) { return projectID === undefined ? "none" : navigationKey(server, projectID) } function sessionMatches(session: NavSession, status: Status, filters: NavigationFilters) { const query = filters.query.trim().toLowerCase() if (query !== "" && !session.title.toLowerCase().includes(query)) return false if (filters.status.length > 0 && !filters.status.includes(status)) return false if (filters.server.length > 0 && !filters.server.includes(session.server)) return false return filters.project.length === 0 || filters.project.includes(projectFilterKey(session.server, session.projectID)) } function draftMatches(draft: NavDraft, filters: NavigationFilters) { const query = filters.query.trim().toLowerCase() if (filters.status.length > 0) return false if (query !== "" && !draft.preview.toLowerCase().includes(query)) return false if (filters.server.length > 0 && !filters.server.includes(draft.server)) return false return filters.project.length === 0 || filters.project.includes(projectFilterKey(draft.server, draft.projectID)) } function finish(item: Spec, input: ViewInput, settings: NavigationSettings): Section { const collapsible = item.heading !== undefined const collapsed = collapsible && input.view.collapsed[item.id] === true const rows = collapsed ? item.entries.filter((entry) => entry.row.selected).map((entry) => entry.row) : limited(item, input, settings) const rendered = new Set(rows.map((row) => row.key)) const hidden = item.entries.map((entry) => entry.row).filter((row) => !rendered.has(row.key)) return { id: item.id, kind: item.kind, heading: item.heading, collapsible, collapsed, rows, total: item.entries.length, more: collapsed ? 0 : hidden.length, hiddenMark: collapsed ? hiddenMark(hidden) : undefined, } } /** The rows the limit allows, plus every row that needs you or is selected, each with the parents it nests under. */ function limited(item: Spec, input: ViewInput, settings: NavigationSettings) { const limit = sectionLimit(item, input, settings) if (limit === undefined) return item.entries.map((entry) => entry.row) const fresh = (row: Row) => row.kind === "draft" || row.session.activity >= limit.since const parents = new Map(item.entries.map((entry) => [entry.row.key, entry.parent])) const lineage = (key: string): string[] => { const parent = parents.get(key) return parent === undefined || !parents.has(parent) ? [key] : [key, ...lineage(parent)] } const keep = new Set( item.entries.flatMap((entry, index) => (index < limit.count && fresh(entry.row)) || forced(entry.row) ? lineage(entry.row.key) : [], ), ) return item.entries.filter((entry) => keep.has(entry.row.key)).map((entry) => entry.row) } function sectionLimit(item: Spec, input: ViewInput, settings: NavigationSettings) { const extra = input.view.expanded[item.id] ?? 0 if (item.kind === "group") return { count: rowsPerGroupLimit(settings.rowsPerGroup) + extra, since: -Infinity } if (item.kind === "main") return { count: showLimit(settings.show) + extra, since: extra > 0 ? -Infinity : showSince(settings.show, input.now), } return undefined } function forced(row: Row) { return row.selected || (row.kind === "session" && row.request !== undefined) } function hiddenMark(rows: Row[]): Section["hiddenMark"] { const sessions = rows.flatMap((row) => (row.kind === "session" ? [row] : [])) if (sessions.some((row) => row.request !== undefined)) return "attention" if (sessions.some((row) => row.status === "unread" || row.status === "failed")) return "unread" return undefined }