diff --git a/.github/workflows/box-usage.yml b/.github/workflows/box-usage.yml new file mode 100644 index 000000000..e997d4900 --- /dev/null +++ b/.github/workflows/box-usage.yml @@ -0,0 +1,42 @@ +# What uses the bitbaum box's memory and disk. Read-only. +# +# Same SSH setup as box-doctor.yml and disk-cleanup.yml (repo secret +# HETZNER_SSH_KEY, org variable HETZNER_IP). The script is piped to bash on +# the box as root, measures, prints, and changes nothing. It prints sizes, +# counts and program names only: this repo is public, so its run logs are too. +# +# Run: gh workflow run box-usage.yml +name: Box usage + +on: + workflow_dispatch: + +concurrency: + group: box-usage + cancel-in-progress: false + +permissions: + contents: read + +jobs: + usage: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + HETZNER_IP: ${{ vars.HETZNER_IP }} + steps: + - uses: actions/checkout@v7 + + - name: SSH setup (same key and host as deploy.yml) + run: | + test -n "$HETZNER_IP" || { echo "::error::org variable HETZNER_IP is not set"; exit 1; } + mkdir -p ~/.ssh + printf '%s\n' "${{ secrets.HETZNER_SSH_KEY }}" > ~/.ssh/id_deploy + chmod 600 ~/.ssh/id_deploy + ssh-keyscan -H "$HETZNER_IP" >> ~/.ssh/known_hosts 2>/dev/null + printf 'Host %s\n IdentityFile ~/.ssh/id_deploy\n IdentitiesOnly yes\n' "$HETZNER_IP" >> ~/.ssh/config + + - name: Measure memory and disk (changes nothing) + run: | + ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 \ + "root@$HETZNER_IP" bash -s < scripts/hetzner/box-usage.sh diff --git a/.github/workflows/disk-cleanup.yml b/.github/workflows/disk-cleanup.yml index f92b36035..08707ea67 100644 --- a/.github/workflows/disk-cleanup.yml +++ b/.github/workflows/disk-cleanup.yml @@ -27,7 +27,7 @@ permissions: jobs: cleanup: runs-on: ubuntu-latest - timeout-minutes: 30 + timeout-minutes: 60 env: HETZNER_IP: ${{ vars.HETZNER_IP }} steps: diff --git a/scripts/hetzner/box-usage.sh b/scripts/hetzner/box-usage.sh new file mode 100755 index 000000000..0bfbb614a --- /dev/null +++ b/scripts/hetzner/box-usage.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# What uses this box's memory and disk. READ-ONLY: it measures and prints. +# Piped to `bash -s` as root from .github/workflows/box-usage.yml (same SSH +# setup as box-doctor.yml and disk-cleanup.yml). +# +# Why it exists: on 2026-11-11 the box sat at 91-95% memory and 91-93% disk, +# both sites reset connections, CI could not sign in against production auth, +# and nothing could say WHAT was using either. disk-cleanup.sh reclaims disk; +# nothing measured memory at all. +# +# THE REPO IS PUBLIC and run logs are too. This prints sizes, counts and +# program NAMES only: `comm`, never a command line, because arguments and +# environments carry tokens. No file contents, no env, no keys. +set -uo pipefail + +section() { printf '\n=== %s ===\n' "$1"; } + +section "memory" +free -h +echo +awk '/MemTotal|MemAvailable|SwapTotal|SwapFree/ {printf "%s %.1f GiB\n", $1, $2/1048576}' /proc/meminfo + +section "memory by program (resident, summed over its processes)" +ps -eo rss=,comm= | awk '{rss[$2]+=$1; n[$2]++} END {for (p in rss) printf "%8.0f MiB %4d proc %s\n", rss[p]/1024, n[p], p}' | sort -rn | head -25 + +section "agent CLIs and browsers: how many, how old" +for name in claude gemini grok cursor-agent codex chrome chromium node; do + count="$(pgrep -c -x "$name" 2>/dev/null)" + [ "${count:-0}" = "0" ] && continue + oldest="$(ps -o etimes= -C "$name" 2>/dev/null | sort -rn | head -1 | tr -d ' ')" + mib="$(ps -o rss= -C "$name" 2>/dev/null | awk '{s+=$1} END {printf "%.0f", s/1024}')" + printf '%-14s %4s processes %6s MiB oldest %s h\n' "$name" "$count" "${mib:-0}" "$(( ${oldest:-0} / 3600 ))" +done + +section "out-of-memory kills since boot" +journalctl -k -b --no-pager 2>/dev/null | grep -ci 'out of memory' || true +journalctl -k -b --no-pager 2>/dev/null | grep -i 'out of memory' | sed -E 's/.*Killed process [0-9]+ \(([^)]*)\).*/\1/' | sort | uniq -c | sort -rn | head -10 + +section "containers: memory now" +if command -v docker >/dev/null 2>&1; then + docker stats --no-stream --format '{{.MemUsage}}\t{{.Name}}' 2>/dev/null | sort -rh | head -25 +fi + +section "disk" +df -h / 2>/dev/null +echo +du -xsh /opt /home /var/lib/docker /var/log /root /tmp 2>/dev/null | sort -rh + +section "disk: /home/ubuntu, largest" +du -xh --max-depth=1 /home/ubuntu 2>/dev/null | sort -rh | head -15 + +section "disk: agent workspaces" +for dir in /home/ubuntu/.loki/workspaces /home/ubuntu/dev; do + [ -d "$dir" ] || continue + total="$(du -xsh "$dir" 2>/dev/null | cut -f1)" + count="$(find "$dir" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)" + modules="$(find "$dir" -maxdepth 3 -type d -name node_modules -prune 2>/dev/null | wc -l)" + stale="$(find "$dir" -mindepth 1 -maxdepth 1 -type d -mtime +14 2>/dev/null | wc -l)" + printf '%s: %s in %s directories; %s with node_modules; %s untouched for 14 days\n' "$dir" "${total:-?}" "$count" "$modules" "$stale" +done + +section "disk: /opt, largest" +du -xh --max-depth=1 /opt 2>/dev/null | sort -rh | head -20 + +section "disk: docker" +if command -v docker >/dev/null 2>&1; then + docker system df 2>/dev/null + echo + docker volume ls -q 2>/dev/null | while read -r v; do + path="$(docker volume inspect -f '{{.Mountpoint}}' "$v" 2>/dev/null)" + [ -n "$path" ] && printf '%s\t%s\n' "$(du -xsh "$path" 2>/dev/null | cut -f1)" "$v" + done | sort -rh | head -12 +fi + +section "disk: uploaded files (Supabase Storage)" +find / -xdev -type d -path '*volumes/storage*' -maxdepth 6 2>/dev/null | head -3 | while read -r d; do + printf '%s\t%s\n' "$(du -xsh "$d" 2>/dev/null | cut -f1)" "$d" +done + +echo +echo "box-usage: done, nothing changed" diff --git a/scripts/hetzner/disk-cleanup.sh b/scripts/hetzner/disk-cleanup.sh index aed0e21f6..76b78829e 100755 --- a/scripts/hetzner/disk-cleanup.sh +++ b/scripts/hetzner/disk-cleanup.sh @@ -43,6 +43,20 @@ if [ "$DRY" != "0" ] && [ "$DRY" != "1" ]; then exit 2 fi +# A size, or "over ${DU_BUDGET}s" when counting takes too long to be worth it. +# +# The first run of this script (2026-11-11, dry) was cancelled at the +# workflow's 30 minutes having printed four sizes and planned nothing: `du` +# on /opt alone took 14 minutes on a disk full of node_modules. Sizes here +# are for the reader; what was freed is measured from df, which is instant. +# So a size that cannot be had quickly is skipped rather than waited for. +DU_BUDGET=45 +sz() { + local out + out="$(timeout "$DU_BUDGET" du -sh "$1" 2>/dev/null | awk '{print $1}')" + echo "${out:-over ${DU_BUDGET}s}" +} + pct() { df --output=pcent / 2>/dev/null | tail -1 | tr -dc '0-9'; } used_k() { df --output=used / 2>/dev/null | tail -1 | tr -dc '0-9'; } @@ -71,25 +85,30 @@ journalctl --disk-usage 2>/dev/null || true echo echo "=== hotspot sizes ===" -du -sh /var/lib/docker /var/lib/containerd /var/log /opt /opt/backups /opt/backups/pg \ - /home/ubuntu/dev /var/cache/apt /usr /swapfile 2>/dev/null || true +for hot in /var/lib/docker /var/lib/containerd /var/log /opt /opt/backups /opt/backups/pg \ + /home/ubuntu /home/ubuntu/dev /home/ubuntu/.loki /home/ubuntu/.cache /home/ubuntu/.npm \ + /home/ubuntu/.local /var/cache/apt /usr /swapfile; do + [ -e "$hot" ] && printf '%s\t%s\n' "$(sz "$hot")" "$hot" +done echo echo "=== /opt per entry ===" -du -sh /opt/* 2>/dev/null | sort -h || true +for entry in /opt/*; do + [ -e "$entry" ] && printf '%s\t%s\n' "$(sz "$entry")" "$entry" +done | sort -h echo echo "=== release dirs (newest first; keep ${KEEP_RELEASES}) ===" for reldir in /opt/*/releases; do [ -d "$reldir" ] || continue count="$(ls -1 "$reldir" 2>/dev/null | wc -l | tr -d ' ')" - echo "-- $reldir ($count entries, $(du -sh "$reldir" 2>/dev/null | awk '{print $1}'))" + echo "-- $reldir ($count entries, $(sz "$reldir"))" i=0 ls -1t "$reldir" 2>/dev/null | while read -r name; do [ -n "$name" ] || continue i=$((i + 1)) tag="KEEP" [ "$i" -gt "$KEEP_RELEASES" ] && tag="PRUNE" - printf ' %s %s %s\n' "$tag" "$(du -sh "$reldir/$name" 2>/dev/null | awk '{print $1}')" "$name" + printf ' %s %s %s\n' "$tag" "$(sz "$reldir/$name")" "$name" done done echo @@ -98,7 +117,7 @@ echo "=== app / previous release pointers ===" for d in /opt/*/app /opt/*/app.prev /opt/*/app-old; do [ -e "$d" ] || continue target="$(readlink -f "$d" 2>/dev/null || echo not-a-link)" - size="$(du -sh "$d" 2>/dev/null | awk '{print $1}')" + size="$(sz "$d")" printf ' %s -> %s %s\n' "$d" "$target" "$size" done echo @@ -107,7 +126,7 @@ echo "=== backups in /opt/backups/pg (counts and sizes only) ===" if [ -d /opt/backups/pg ]; then total_n="$(find /opt/backups/pg -maxdepth 1 -type f \( -name '*.dump' -o -name '*.sql.gz' \) | wc -l | tr -d ' ')" old_n="$(find /opt/backups/pg -maxdepth 1 -type f \( -name '*.dump' -o -name '*.sql.gz' \) -mtime +${KEEP_BACKUP_DAYS} | wc -l | tr -d ' ')" - total_sz="$(du -sh /opt/backups/pg 2>/dev/null | awk '{print $1}')" + total_sz="$(sz /opt/backups/pg)" old_sz="$(find /opt/backups/pg -maxdepth 1 -type f \( -name '*.dump' -o -name '*.sql.gz' \) -mtime +${KEEP_BACKUP_DAYS} -printf '%s\n' 2>/dev/null | awk '{s+=$1} END {if(s<1024*1024) printf "%dK\n", s/1024; else printf "%dM\n", s/1024/1024}')" echo " files=$total_n size=$total_sz older_than_${KEEP_BACKUP_DAYS}d=$old_n size=${old_sz:-0}" else @@ -259,7 +278,7 @@ for reldir in /opt/*/releases; do *$'\n'"$resolved"$'\n'*) echo " KEEP (live or previous pointer) $path"; continue ;; esac if [ "$DRY" = "1" ]; then - echo " DRY rm -rf $path ($(du -sh "$path" 2>/dev/null | awk '{print $1}'))" + echo " DRY rm -rf $path ($(sz "$path"))" else echo " rm -rf $path" rm -rf -- "$path" @@ -352,7 +371,7 @@ if [ "${stop:-0}" != 1 ]; then continue fi if [ "$DRY" = "1" ]; then - echo " DRY rm -rf $nm ($(du -sh "$nm" 2>/dev/null | awk '{print $1}'), idle ${idle}d)" + echo " DRY rm -rf $nm ($(sz "$nm"), idle ${idle}d)" else echo " rm -rf $nm (idle ${idle}d)" rm -rf -- "$nm" diff --git a/scripts/test/landing-destination.ts b/scripts/test/landing-destination.ts index e1cebae6d..102fc1dee 100644 --- a/scripts/test/landing-destination.ts +++ b/scripts/test/landing-destination.ts @@ -32,10 +32,22 @@ function runTests(): void { assert(ROUTES.RUNNER_HOME.startsWith("/"), "RUNNER_HOME must be a path"); }); - check("browsers still get the marketing page", () => { + check("a signed-in browser lands in the app, not on the pitch", () => { + const to = landingRedirect({ insideRunner: false, signedIn: true, params: {} }); + assert(to === ROUTES.APP_HOME, `expected ${ROUTES.APP_HOME}, got ${to}`); + }); + + check("a signed-out browser still gets the marketing page", () => { assert( - landingRedirect({ insideRunner: false, signedIn: true, params: {} }) === null, - "browser must not redirect", + landingRedirect({ insideRunner: false, signedIn: false, params: {} }) === null, + "signed-out browser must not redirect", + ); + }); + + check("?site opens the real homepage for a signed-in browser too", () => { + assert( + landingRedirect({ insideRunner: false, signedIn: true, params: { site: "1" } }) === null, + "?site must not redirect", ); }); diff --git a/scripts/test/orangecat-actor-status.ts b/scripts/test/orangecat-actor-status.ts index 5884d0e42..1f21e7329 100644 --- a/scripts/test/orangecat-actor-status.ts +++ b/scripts/test/orangecat-actor-status.ts @@ -147,6 +147,16 @@ async function main(): Promise { assert.ok(!isFreshIssuedAt("not a date", now)); console.log(" ✓ freshness window"); + const { shapeActorModelKeys } = await import("../../src/lib/integrations/orangecat-actor-status"); + const keys = shapeActorModelKeys([ + { vendor: "xai", model: "grok-4.7", keyHint: "…VWhN" }, + { vendor: "xai", model: "grok-4.6", keyHint: "…VWhN" }, + { vendor: "custom", model: "local", keyHint: "no key" }, + ]); + assert.deepEqual(keys, [{ vendor: "xai", model: "grok-4.7", keyHint: "…VWhN" }]); + assert.ok(!JSON.stringify(keys).includes("sealed"), "nothing but the name and the hint"); + console.log(" ✓ model keys cross as a vendor name and a hint, one per vendor, never custom"); + // ── refusals (no database) ───────────────────────────────────────────────── const { POST } = await import("../../src/app/api/orangecat/actor-status/route"); diff --git a/scripts/test/terminal-conversation.ts b/scripts/test/terminal-conversation.ts index 5b785b7ef..4ec67a049 100644 --- a/scripts/test/terminal-conversation.ts +++ b/scripts/test/terminal-conversation.ts @@ -92,6 +92,14 @@ assert(!toolWasInterrupted({ ...tool, status: "error", result: "command exited 1 assert.equal(shown.text, "Make these changes on this page, together:\n1. Add an H1."); assert.equal(shown.details, filed, "the diagnostics stay one tap away"); } +{ + // The packet a retried dispatch sends, as production stored it on 2026-11-11. + const retried = + "## Escalation state (operator dispatch pipeline — rung 3/4: REPLAN)\nTHREE consecutive runs failed — the current approach is not working. Step back and re-plan: state in the session handoff why the previous attempts failed, choose a genuinely different approach or a much smaller verifiable step, and pursue that instead.\nLast recorded failure: Timed out — run exceeded maximum duration and was cleaned up\n\n## Task\nFix the sign-in page.\n\n## Exit contract (operator requirement)\nBefore stopping, create ~/.loki/sessions/orangecat.md."; + const shown = dispatchMessageDisplay(retried); + assert.equal(shown.text, "Fix the sign-in page.", "the person sees what they asked"); + assert.equal(shown.details, retried, "the full packet stays one tap away"); +} console.log( "✓ dispatch presentation preserves requests; interruption, quiet and disconnected sessions report honest state", ); diff --git a/scripts/test/terminal-session-status.ts b/scripts/test/terminal-session-status.ts index f4f5b139b..59fcdeefb 100644 --- a/scripts/test/terminal-session-status.ts +++ b/scripts/test/terminal-session-status.ts @@ -7,7 +7,7 @@ * Run: npx tsx scripts/test/terminal-session-status.ts */ import type { FastProjectState } from "@/lib/control-fast-state"; -import { isNewsworthy, sessionStatusOf } from "@/lib/terminal-session-status"; +import { orderSessions, isNewsworthy, sessionStatusOf } from "@/lib/terminal-session-status"; let failures = 0; function check(name: string, fn: () => void) { @@ -82,6 +82,35 @@ check("the first report of a session is never news", () => { assert(!isNewsworthy(undefined, "needs-you"), "first sight should be quiet"); }); +check("the session list leads with what needs the person and folds the quiet ones", () => { + const tabs = [ + { id: "loki-2", status: "idle" as const }, + { id: "loki-3", status: null }, + { id: "kivvi", status: "needs-you" as const }, + { id: "loki-4", status: "idle" as const }, + { id: "bias", status: "working" as const }, + { id: "loki-5", status: "idle" as const }, + { id: "solon", status: "done" as const }, + { id: "loki-6", status: "idle" as const }, + ]; + const { first, quiet } = orderSessions(tabs, "loki-4"); + assert( + first.map((t) => t.id).join(",") === "kivvi,bias,solon,loki-4", + `needs-you, working, finished, then the one in use: got ${first.map((t) => t.id)}`, + ); + assert(quiet.length === 4 && !quiet.some((t) => t.id === "loki-4"), "the rest wait"); +}); +check("a few quiet sessions are simply listed", () => { + const { first, quiet } = orderSessions( + [ + { id: "a", status: "idle" as const }, + { id: "b", status: "needs-you" as const }, + ], + null, + ); + assert(first.map((t) => t.id).join(",") === "b,a" && quiet.length === 0, "nothing folded"); +}); + if (failures) { console.log(`\n${failures} failing`); process.exit(1); diff --git a/src/app/api/orangecat/actor-status/route.ts b/src/app/api/orangecat/actor-status/route.ts index d8a8824ca..5250a0c0a 100644 --- a/src/app/api/orangecat/actor-status/route.ts +++ b/src/app/api/orangecat/actor-status/route.ts @@ -8,7 +8,12 @@ import { getRecentOutcomesByProjectKeys } from "@/db/queries/orchestration-runs" import { listFeedbackSummary } from "@/db/queries/site-feedback"; import { getOrangeCatLinksForUser } from "@/db/queries/orangecat-links"; import { readSignedOrangeCatBody } from "@/lib/integrations/orangecat-webhook"; -import { isFreshIssuedAt, shapeActorStatus } from "@/lib/integrations/orangecat-actor-status"; +import { + isFreshIssuedAt, + shapeActorModelKeys, + shapeActorStatus, +} from "@/lib/integrations/orangecat-actor-status"; +import { listOwnModels } from "@/db/queries/user-model-keys"; /** * OrangeCat asks what is happening to one person's Loki projects, so its @@ -39,12 +44,13 @@ export async function POST(req: NextRequest) { return NextResponse.json({ ok: true, linked: false, projects: [] }); } - const [own, org, states, feedback, links] = await Promise.all([ + const [own, org, states, feedback, links, models] = await Promise.all([ getUserProjects(user.id).catch(() => []), getOrgProjects(user.id).catch(() => []), getProjectStatesByUserId(user.id).catch(() => []), listFeedbackSummary(user.id).catch(() => []), getOrangeCatLinksForUser(user.id).catch(() => []), + listOwnModels(user.id).catch(() => []), ]); const projects = mergeVisibleProjects(own, org); const outcomes = await getRecentOutcomesByProjectKeys( @@ -57,6 +63,8 @@ export async function POST(req: NextRequest) { linked: true, generatedAt: new Date().toISOString(), projects: shapeActorStatus({ projects, states, outcomes, feedback, links }), + // Names only, never a key (shapeActorModelKeys). + modelKeys: shapeActorModelKeys(models), }); } catch (err) { console.error("[orangecat/actor-status] failed:", (err as Error).message); diff --git a/src/components/terminal/TerminalSessionSheet.tsx b/src/components/terminal/TerminalSessionSheet.tsx index f4d7771a6..3cc5f480e 100644 --- a/src/components/terminal/TerminalSessionSheet.tsx +++ b/src/components/terminal/TerminalSessionSheet.tsx @@ -7,7 +7,11 @@ import { List, ListRow } from "@/components/ui/list-row"; import { Section } from "@/components/ui/section-heading"; import type { AgentEntry } from "@/components/control/agent-switcher-popover"; import { TERMINAL_SOURCES, type TerminalSource } from "@/config/terminal-modes"; -import { SESSION_STATUS_WORDS, type SessionStatus } from "@/lib/terminal-session-status"; +import { + orderSessions, + SESSION_STATUS_WORDS, + type SessionStatus, +} from "@/lib/terminal-session-status"; export type SheetTab = { id: string; @@ -84,6 +88,11 @@ export function TerminalSessionSheet({ const t = setTimeout(() => setArmed(null), 3000); return () => clearTimeout(t); }, [armed]); + // What needs the person first; sessions that are merely open wait behind + // one row (orderSessions). + const [showQuiet, setShowQuiet] = useState(false); + const ordered = orderSessions(tabs ?? [], activeTab); + const listed = showQuiet ? [...ordered.first, ...ordered.quiet] : ordered.first; const sourceOptions = TERMINAL_SOURCES.filter((s) => sources.includes(s.id)); const check = ; @@ -104,7 +113,7 @@ export function TerminalSessionSheet({ {tabs && onSelectTab && (
- {tabs.map((tab) => ( + {listed.map((tab) => ( ))} + {!showQuiet && ordered.quiet.length > 0 && ( + setShowQuiet(true)} + /> + )} {onNewSession && ( , +): ActorModelKey[] { + const seen = new Set(); + const out: ActorModelKey[] = []; + for (const row of rows) { + if (row.vendor === "custom" || seen.has(row.vendor)) continue; + seen.add(row.vendor); + out.push({ vendor: row.vendor, model: row.model, keyHint: row.keyHint }); + } + return out; +} diff --git a/src/lib/landing-destination.ts b/src/lib/landing-destination.ts index 4a1886a16..1a75fb63b 100644 --- a/src/lib/landing-destination.ts +++ b/src/lib/landing-destination.ts @@ -13,18 +13,19 @@ export type LandingContext = { /** * Where a visitor to "/" should actually end up. * - * Fleet Runner starts with the OS and loads APP_URL with no path, so a - * signed-in operator's first sight of the day was the marketing hero — a pitch - * written for a stranger, which suggests nothing to do and costs a click before - * any agent can be launched. Inside the runner, a signed-in operator goes to - * the command deck instead. + * Someone signed in goes to the app. The marketing hero is a pitch written + * for a stranger: it suggests nothing to do and costs a tap ("Open Loki") + * before anything can be said. That was first fixed for Fleet Runner only, + * which loads APP_URL with no path at OS startup; a browser kept the pitch. + * On 2026-11-11 the owner opened loki.orangecat.ch on his phone, signed in, + * and got the marketing page and its marketing menu. * - * Returns null when the marketing page is the correct answer: every browser - * visitor, anyone signed out (they still need the pitch and the sign-in path), - * and a runner operator who asked for the site on purpose with `?site`. + * Returns null when the marketing page is the correct answer: anyone signed + * out (they still need the pitch and the sign-in path), and anyone who asked + * for the site on purpose with `?site`. */ export function landingRedirect(ctx: LandingContext): string | null { - if (!ctx.insideRunner || !ctx.signedIn) return null; + if (!ctx.signedIn) return null; if (ctx.params[SITE_PREVIEW_PARAM] !== undefined) return null; - return ROUTES.RUNNER_HOME; + return ctx.insideRunner ? ROUTES.RUNNER_HOME : ROUTES.APP_HOME; } diff --git a/src/lib/terminal-session-status.ts b/src/lib/terminal-session-status.ts index ba0080232..210edce40 100644 --- a/src/lib/terminal-session-status.ts +++ b/src/lib/terminal-session-status.ts @@ -42,3 +42,32 @@ export function isNewsworthy( if (!after || before === after || !before) return false; return after === "needs-you" || (after === "done" && before === "working"); } + +/** Fewer quiet sessions than this are simply listed; folding three rows is busywork. */ +const QUIET_FOLD_MIN = 4; + +const ATTENTION: Record = { "needs-you": 0, working: 1, done: 2, idle: 3 }; + +/** + * The session list in the order a person needs it, and what can wait. + * + * The phone's picker listed every open session in the order it was opened: 27 + * rows, "Loki 2" to "Loki 15", with the three that needed the owner somewhere + * among them (2026-11-11). `first` is what is worth reading now: sessions + * waiting on the person, then working, then finished, plus the one in use. + * `quiet` is the rest (open, nothing happening), shown on request. + */ +export function orderSessions( + tabs: readonly T[], + activeId: string | null, +): { first: T[]; quiet: T[] } { + const rank = (t: T) => (t.status ? ATTENTION[t.status] : ATTENTION.idle); + const sorted = tabs + .map((tab, index) => ({ tab, index })) + .sort((a, b) => rank(a.tab) - rank(b.tab) || a.index - b.index) + .map(({ tab }) => tab); + const isQuiet = (t: T) => t.id !== activeId && rank(t) === ATTENTION.idle; + const quiet = sorted.filter(isQuiet); + if (quiet.length < QUIET_FOLD_MIN) return { first: sorted, quiet: [] }; + return { first: sorted.filter((t) => !isQuiet(t)), quiet }; +}