Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .changeset/9008093b.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
---
"aicodeman": minor
---

Add an optional collapsible left session sidebar as an alternative to the header tab strip.

With many concurrent sessions the horizontal strip wraps into several rows and stops being scannable. The new layout puts the session list in a vertical `<aside>` with a filter box and a live session count, collapsible to a 44px rail that keeps the status dots and task badges visible.

Opt-in via Settings → Layout → Tabs → Session List Layout; the default stays the header strip, so nothing changes unless you switch. Both layouts share one `#sessionTabs` element that is re-parented between mount points, so every existing affordance (status, mode badge, alerts, drag-reorder, keyboard navigation, web tabs, subagent windows) behaves identically in both. Below 1024px the sidebar is an off-canvas drawer that overlays the terminal instead of shrinking it. Collapse state persists per device; `Alt+B` toggles it.
1 change: 1 addition & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,7 @@ Single-digit selection (1-9), color-coded status, token counts, auto-refresh. De
| `Ctrl/Cmd+Tab` | Next session |
| `Alt/Option+[` / `Alt/Option+]` | Previous / next session |
| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) |
| `Alt/Option+B` | Collapse / expand the session sidebar (sidebar layout only) |
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right |
| `Ctrl/Cmd+C` | Copy selection, or interrupt when nothing is selected |
| `Ctrl+Shift+C` | Copy selection (never interrupts) |
Expand Down
6 changes: 6 additions & 0 deletions docs/architecture-invariants.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,12 @@ Anatomy: `.set-shell` → `.set-shell-head` (title + `.set-head-actions`) + `.se
⚠️ **Claude transcripts are grouped at real human-turn boundaries, not per JSONL row.** A Claude transcript is an append-only event log, so one logical exchange spans many rows: tool-result rows, meta/image/skill rows, compact summaries, task/team notifications, sidechains, replayed assistant snapshots, and multi-block assistant output. Rendering a card per row was the bug: it produced duplicate and truncated cards that looked like the viewer had lost the response. The grouping walks to the next genuine user turn and dedups replayed assistant snapshots while preserving the tool/task/skill/compact/team metadata filtering. Related: a recovered `restored-<uuid8>` tmux placeholder carries a **stale cwd**, so transcript lookup by working directory finds nothing; it rebinds to the matching top-level Claude transcript UUID instead when that match is unambiguous. Tests: `test/routes/session-routes-claude-last-response.test.ts`. Purely client-side (no `renderIndexHtml` step): the template ships with `btn-response-viewer-header--hidden` and `applyHeaderVisibilitySettings()` (settings-ui.js) toggles it after settings load. Hiding must go through that marker class — the base rule is `display:inline-flex !important`, so an inline style can't override it. `showResponseViewer` is in the `displayKeys` per-device set (settings-ui.js), so it does NOT sync across devices.
**File Viewer button** (header, 1.4.1) is **shown by default on desktop** since `211f3c0` (post-1.8.0): toggle under App Settings → Header & Panels → Header buttons → File Viewer (`showFileViewerButton`, in the per-device `displayKeys` set, fallback default `true`). Purely client-side like the response viewer: the template now ships the button VISIBLE (no `--hidden` class) and `applyHeaderVisibilitySettings()` toggles the `btn-file-viewer--hidden` marker class after settings load; phones still hide it via mobile.css. The button toggles the file-browser panel open/closed without opening the settings modal (`panels-ui.js`). The same commit set the **default desktop header** to WS/CPU/MEM + File Viewer + gear: the token-count chip (`showTokenCount`, no settings-UI toggle) and the lifecycle-log button (`showLifecycleLog`) both default **OFF** now (templates ship them hidden; stored prefs still honored). The plan-usage chip default is unchanged (opt-in, see Plan-usage chip). The **Cron toolbar button** joined the same opt-in pattern in 1.6.0: template ships `btn-cron--hidden`, `applyHeaderVisibilitySettings()` toggles it via the per-device `showCronButton` setting (default OFF, App Settings → Header & Panels → Scheduling); cron jobs themselves are unaffected.

### Session list layout (header strip vs. left sidebar)

**The session list can render as the horizontal header strip (default) or as a collapsible left sidebar** — App Settings → Layout → Tabs → **Session List Layout** (`sessionListLayout: 'header' | 'sidebar'`, in the per-device `displayKeys` set, so it never syncs across devices; also in `SettingsUpdateSchema`, which is `.strict()` — without that entry the server 400s the ENTIRE settings PUT and every unrelated setting silently stops persisting). ⚠️ **There is exactly ONE `#sessionTabs` element and `applySessionListLayout()` RE-PARENTS it** between `#sessionTabsHost` (in `<header>`) and `#sessionSidebarList` (in the `<aside>`, a flex sibling of `.terminal-wrap` so the terminal shrinks and `terminal-ui.js`'s `ResizeObserver` refits xterm on its own). It must never be cloned or rebuilt: `app.$(id)` caches elements by id and NEVER invalidates, and `settings-ui.js` / `webview-tabs.js` resolve the same id independently, so a rebuilt container leaves every consumer writing into a detached orphan — silently, with no error. Everything else is CSS keyed off `html[data-session-list]` / `html[data-sidebar]`, both written by a pre-paint script in `<head>` so the loading skeleton already matches. Consequences: the renderers, drag/keyboard handlers, web tabs (`data-webview-id` rows stay in the same list, keeping the shared Alt+N numbering and the single-active-tab invariant) and the generated gesture bundle (`TAB_SELECTOR`/`DOCK_SELECTOR` match on class names that are unchanged) all need **zero** edits.

⚠️ Collapsed means **different things per viewport**: at 1024px and up the sidebar keeps a 44px icon rail so the ambient signal (status dot, task/subagent/ultracode badges) survives — the Alt+N number, the name/folder and the `sh`/`oc`/`cx`/`gm` mode chip do NOT, because 44px minus paddings and borders is ~34px of content box and the chip lives inside `.tab-info`; below 1024px `mobile.css` turns the sidebar into an off-canvas overlay where collapsed == drawer closed (mirrored into an `.open` class plus `inert`/`aria-hidden`, since `translateX(-100%)` alone leaves every row in the Tab order), it defaults to CLOSED when the user has made no choice, and picking a session or web tab dismisses it. ⚠️ **That 1024px breakpoint is the only handheld test the sidebar may use** (`_isSessionSidebarOverlay()`, mirrored in the pre-paint script): `MobileDetection.getDeviceType()` calls everything from 768px up `'desktop'`, so using it gave 768-1023px the overlay CSS with docked-sidebar logic — drawer opening itself on load, immune to selection and Escape. The toggle chord (default Alt+B) also needs its gate in `terminal-ui.js`'s `attachCustomKeyEventHandler`, or `preventDefault()` in the capture handler still lets xterm write ESC b into the live PTY (same trap as COD-153). The sidebar filter only applies while its input is on screen — `applySidebarFilter()` strips the class in the header strip, the collapsed rail and the closed drawer, because a filter with no reachable control hides sessions permanently. Collapse state lives in its OWN `codeman-sidebar-collapsed` key, **not** in the settings blob — `saveAppSettings()` rebuilds that blob from DOM controls, so a key without a control is wiped on every Save. Solo (`/session/:id`) windows never get a sidebar (three guards: `getSessionListLayout()`, the pre-paint script, and `body.solo-mode`), because `#sessionTabs` parked in a `display:none` subtree measures 0/0 for tab overflow and inline rename. The sidebar CSS block sits at the END of `styles.css`, **after** the `html:not([data-skin="og"])` nesting block, and is layout-only — any colour on `.session-tab` there would render correctly on the `og` skin only. Same for the `mobile.css` block: it must stay at the end of the file or the earlier compact-strip rules clip the list to a 36px sliver. Two surfaces DEFER to the sidebar rather than adapt: **lineage arcs are skipped** in sidebar layout (`_appendLineageConnectionLines` early-returns — `computeLineagePath()`'s whole geometry hangs a U-bridge from the horizontal STRIP's bottom edge, so against a vertical list every arc would loop to the foot of the sidebar; a sideways lineage shape needs its own visual tuning, it is not a by-product of re-parenting), and the **desktop home tab rail** (`shouldShowHomeSessions()`) stays hidden while the sidebar is active, because both dock the session list flush left and the rail would render the same list next to it, z-ordered UNDER it. The subagent/ultracode connectors DO adapt (`_tabAnchor()`/`_tabConnectorPath()` in app.js: right-edge anchor, horizontal bezier), and the lineage strip-scroll listener redraws them on the sidebar's vertical scroll. `_scrollActiveTabIntoView()` owns active-row reveal on BOTH axes: sidebar mode branches to `scrollIntoView({block:'nearest'})` because the horizontal `computeTabScrollLeft` math no-ops against a vertical scroller, and `_fullRenderSessionTabs()` restores `scrollTop` alongside the #257 `scrollLeft` restore or ambient rebuilds yank a mid-scroll sidebar back to the top. Tests: `test/session-list-layout.test.ts`.

### Gesture control: the setting

**Gesture control** (the camera hand-tracking overlay) is **opt-in, default OFF**, under App Settings → Terminal & Input → Scrolling & rendering (`gestureControlEnabled`). `CODEMAN_GESTURE=1` makes the feature _available_ on the instance (CSP widening + `/gesture/` assets) and sets `window.__codemanGestureAvailable` (the Input section only shows when set); the overlay bundle is injected by `renderIndexHtml` **only when the setting is enabled**, so that method is `async` and reads `settings.json` via `readSettings(true)` — the `true` forces a **fresh** read (bypassing the 2s `_settingsCache`), because a post-save reload happens within that TTL and the cached value would otherwise render the pre-toggle state. Toggling the setting reloads the page (the bundle is render-injected).
Expand Down
179 changes: 179 additions & 0 deletions scripts/verify-session-sidebar.mts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
/**
* Manual verification harness for the session-sidebar feature.
*
* Renders the real UI in headless Chromium against a testMode WebServer,
* injects a synthetic 25-session fleet, and screenshots every layout state.
* Not part of the automated suite — run it by hand:
*
* npx tsx scripts/verify-session-sidebar.mts
*
* SAFETY: uses the repo's own test harness (temp HOME, testMode server) on a
* dedicated port. It never touches a real Codeman instance or tmux socket.
*/
import { chromium } from 'playwright';
import { WebServer } from '../src/web/server.js';
import { mkdirSync } from 'node:fs';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

// Mirror test/setup.ts: isolate HOME before the app modules touch state.
process.env.HOME = mkdtempSync(join(tmpdir(), 'codeman-sidebar-verify-'));
process.env.VITEST = 'true';

const PORT = 3299;
const OUT = process.env.SIDEBAR_SHOTS_DIR ?? join(tmpdir(), 'codeman-sidebar-shots');
mkdirSync(OUT, { recursive: true });

// Generic on purpose: these names end up in the harness screenshots, so they
// should not carry one contributor's project list into everyone else's review.
// The mix of CLI modes matters (each renders a different badge); the names do not.
const PROJECTS = [
['api-server', 'claude'],
['web-client', 'claude'],
['mobile-app', 'codex'],
['data-pipeline', 'claude'],
['shared-lib', 'gemini'],
['codeman', 'claude'],
['docs-site', 'claude'],
['batch-jobs', 'opencode'],
['search-index', 'claude'],
];
const STATUSES = ['idle', 'busy', 'idle', 'busy', 'error', 'idle'];

function fleet(n: number) {
const out: any[] = [];
for (let i = 0; i < n; i++) {
const [proj, mode] = PROJECTS[i % PROJECTS.length];
const status = STATUSES[i % STATUSES.length];
out.push({
id: `sess-${String(i).padStart(4, '0')}-aaaa-bbbb-cccc-dddddddddddd`,
pid: 10000 + i,
status,
workingDir: `${tmpdir()}/projects/${proj}`,
name: `${proj}${i > 8 ? '-' + Math.floor(i / 9) : ''}`,
mode,
currentTaskId: null,
createdAt: Date.now() - i * 60000,
lastActivityAt: Date.now() - i * 1000,
isWorking: status === 'busy',
messageCount: i * 3,
totalCost: 0,
inputTokens: 0,
outputTokens: 0,
color: 'default',
taskStats: { total: i % 4, running: i % 3 === 0 ? 2 : 0, completed: 0, failed: 0 },
taskTree: [],
tokens: { input: 0, output: 0, total: 0 },
bufferStats: { terminalBufferSize: 0, textOutputSize: 0, messageCount: 0 },
});
}
return out;
}

const SESSIONS = fleet(25);

async function main() {
const server = new WebServer(PORT, false, true);
await server.start();
const browser = await chromium.launch({ headless: true });
const results: string[] = [];

async function shot(
name: string,
opts: { layout: 'header' | 'sidebar'; collapsed?: boolean; width: number; height: number; touch?: boolean }
) {
const ctx = await browser.newContext({
viewport: { width: opts.width, height: opts.height },
hasTouch: !!opts.touch,
isMobile: !!opts.touch,
deviceScaleFactor: 2,
});
const page = await ctx.newPage();
const settings = JSON.stringify({ sessionListLayout: opts.layout });
const collapsed = opts.collapsed === undefined ? null : opts.collapsed ? '1' : '0';
await page.addInitScript(
([s, c]) => {
localStorage.setItem('codeman-app-settings', s as string);
localStorage.setItem('codeman-app-settings-mobile', s as string);
if (c !== null) localStorage.setItem('codeman-sidebar-collapsed', c as string);
else localStorage.removeItem('codeman-sidebar-collapsed');
},
[settings, collapsed]
);
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(1500);

await page.evaluate((list) => {
const app = (window as any).app;
if (!app) throw new Error('no window.app');
app.sessions.clear();
for (const s of list as any[]) app.sessions.set(s.id, s);
// The renderer iterates sessionOrder, not the map.
app.sessionOrder = (list as any[]).map((s) => s.id);
app.activeSessionId = (list as any[])[3].id;
// renderSessionTabs() is debounced; drive the immediate path directly.
(app._fullRenderSessionTabs ?? app._renderSessionTabsImmediate)?.call(app);
app.applySessionListLayout?.();
}, SESSIONS as any);
await page.waitForTimeout(600);

const info = await page.evaluate(() => {
const root = document.documentElement;
const aside = document.getElementById('sessionSidebar');
const tabsEl = document.getElementById('sessionTabs');
const asideBox = aside?.getBoundingClientRect();
const cs = aside ? getComputedStyle(aside) : null;
return {
dataSessionList: root.dataset.sessionList ?? null,
dataSidebar: root.dataset.sidebar ?? null,
rows: document.querySelectorAll('.session-tab').length,
tabsParent: tabsEl?.parentElement?.id || tabsEl?.parentElement?.className || null,
asideWidth: asideBox ? Math.round(asideBox.width) : null,
asideVisible: cs ? cs.display !== 'none' && cs.visibility !== 'hidden' : null,
asideInert: aside?.hasAttribute('inert') ?? null,
ariaHidden: aside?.getAttribute('aria-hidden') ?? null,
toggleAriaExpanded: document.getElementById('sidebarToggleBtn')?.getAttribute('aria-expanded') ?? null,
firstRowText:
(document.querySelector('.session-tab') as HTMLElement | null)?.innerText
?.trim()
.replace(/\s+/g, ' ')
.slice(0, 40) ?? null,
listScrollable: (() => {
const el = document.getElementById('sessionTabs');
return el ? el.scrollHeight > el.clientHeight + 2 : null;
})(),
};
});

await page.waitForTimeout(400);
const file = join(OUT, `${name}.png`);
await page.screenshot({ path: file });
results.push(`${name.padEnd(28)} ${JSON.stringify(info)}`);
await ctx.close();
return info;
}

await shot('01-header-desktop', { layout: 'header', width: 1600, height: 900 });
await shot('02-sidebar-expanded', { layout: 'sidebar', collapsed: false, width: 1600, height: 900 });
await shot('03-sidebar-collapsed-rail', { layout: 'sidebar', collapsed: true, width: 1600, height: 900 });
await shot('04-sidebar-narrow-1000', { layout: 'sidebar', collapsed: true, width: 1000, height: 800 });
await shot('05-sidebar-drawer-open-1000', { layout: 'sidebar', collapsed: false, width: 1000, height: 800 });
await shot('06-sidebar-phone-closed', { layout: 'sidebar', collapsed: true, width: 393, height: 852, touch: true });
await shot('07-sidebar-phone-open', { layout: 'sidebar', collapsed: false, width: 393, height: 852, touch: true });

console.log('\n=== RESULTS ===');
for (const r of results) console.log(r);
console.log(`\nScreenshots in ${OUT}`);

await browser.close();
await server.stop();
}

main().then(
() => process.exit(0),
(e) => {
console.error(e);
process.exit(1);
}
);
Loading