feat(tabs): place new, child and web tabs into groups

New sessions, spawned child sessions and saved web tabs now land in tab
groups instead of always starting in Ungrouped.

New session in a group:
- The group menu gains "New session" (first item). It expands a collapsed
  group and runs ONE launch with the current case and run mode; a launch
  already in flight is reported, not queued.
- run({ count, tabGroupId }) threads the group through every launch path
  (local POST /api/sessions, remote/docker and external-CLI
  /api/quick-start). The count overrides the steppers for that launch only.
- Server: POST /api/sessions and /api/quick-start accept an optional
  tabGroupId (Zod, 1-100 chars; null/empty is a 400). The routes pass it to
  addSession(), and TabLayoutService.sessionCreated() places the session at
  the end of that group in the SAME versioned write that first records it.
  The session is added to the live map inside the owner lock (with a
  rollback when the write fails), so no queued layout edit can commit it
  first. The group is looked up in the creating owner's own layout, so an
  unknown, deleted or foreign id is ignored instead of failing the spawn. An
  explicit group is a hand placement: a child placed this way is manual.
- The create response carries the committed tabLayout (only when tabGroupId
  was sent), adopted before the new tab is drawn. Responses without the
  field are unchanged.

Child sessions (parentSessionId / X-Codeman-Parent-Session):
- A child nobody placed follows its parent: the server's existing
  normalization already puts it after the parent's rows; the browser now
  draws a not-yet-stored child there too (project({ parents })) and, while
  groups exist, adopts the server's order instead of echoing its own append
  back through PUT /api/session-order (which pinned every child manual).
- The row menu says where a child sits (follows, placed by hand, parent
  closed, parent loop) and offers "Follow parent again" only to a hand-placed
  child. A child whose parent is gone stands on its own and is never
  re-adopted.

Saved web tabs:
- Web tabs are layout refs like sessions; openness stays per device. A
  grouped web tab shows (and takes an Alt+N slot) only while open here and
  reopens where the layout keeps it. Pinned by tests; no behaviour change.

Unchanged: the flat rail and header strip (markup, HTML5 drag, append and
save on create), the tree semantics and single tab stop, sessionOrder and
Alt+N, and every request that does not send tabGroupId.
This commit is contained in:
Aamer Akhter committed 2026-10-09 20:16:45 -04:00
1 parent b59145effd
commit b8ccfc33d1
22 files changed
+1227 -57

No files matched your search

@@ -0,0 +1,131 @@
/**
* @fileoverview `tabGroupId` on the create routes: a session created from a
* group's "New session" action asks to be placed in that group.
*
* The routes only validate the field and hand it to `ctx.addSession()`; the
* placement itself (and the rule that an unknown or foreign group is ignored)
* lives in TabLayoutService, covered by test/tab-layout-service.test.ts. What is
* pinned here is the wire contract: the field is validated (a null or an empty
* string is a 400, never a silent drop), it reaches addSession with the new
* session, and the committed layout comes back on the response so the browser
* can draw the tab in its group without waiting for a re-read. Requests without
* the field keep their exact response shape.
*
* Uses app.inject(), so no real HTTP port is needed.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { mkdtemp, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
import { Session } from '../../src/session.js';
const LAYOUT = {
version: 4,
updatedAt: '2026-10-01T00:00:00.000Z',
groups: [{ id: 'g1', name: 'Core', refs: [] as Array<{ kind: 'session'; id: string }> }],
ungrouped: [] as Array<{ kind: 'session'; id: string }>,
};
describe('create routes: tabGroupId', () => {
let app: FastifyInstance;
let ctx: MockRouteContext;
let workingDir: string;
beforeEach(async () => {
vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
workingDir = await mkdtemp(join(tmpdir(), 'codeman-tab-group-'));
app = Fastify({ logger: false });
await app.register(fastifyCookie);
ctx = createMockRouteContext();
ctx.addSession.mockImplementation(async (session: { id: string }, placement?: { tabGroupId?: string }) => {
ctx.sessions.set(session.id, session as never);
const refs = [{ kind: 'session' as const, id: session.id }];
return placement?.tabGroupId === 'g1'
? { ...LAYOUT, version: 5, groups: [{ ...LAYOUT.groups[0], refs }] }
: { ...LAYOUT, version: 5, ungrouped: refs };
});
registerSessionRoutes(app, ctx);
installRouteErrorHandler(app);
await app.ready();
});
afterEach(async () => {
await app.close();
await rm(workingDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
const body = (raw: string) => {
const parsed = JSON.parse(raw);
return parsed.data ?? parsed;
};
it('POST /api/sessions hands the group to addSession and returns the committed layout', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/sessions',
payload: { name: 'w1-x', mode: 'shell', workingDir, tabGroupId: 'g1' },
});
expect(res.statusCode).toBe(200);
const data = body(res.body);
expect(ctx.addSession).toHaveBeenCalledTimes(1);
expect(ctx.addSession.mock.calls[0][0].id).toBe(data.session.id);
expect(ctx.addSession.mock.calls[0][1]).toEqual({ tabGroupId: 'g1' });
expect(data.tabLayout.version).toBe(5);
expect(data.tabLayout.groups[0].refs).toEqual([{ kind: 'session', id: data.session.id }]);
});
it('POST /api/sessions without a group keeps its response shape', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/sessions',
payload: { name: 'w1-x', mode: 'shell', workingDir },
});
expect(res.statusCode).toBe(200);
expect(Object.keys(body(res.body))).toEqual(['session']);
expect(ctx.addSession.mock.calls[0][1]).toBeUndefined();
});
it('POST /api/quick-start carries the group the same way', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/quick-start',
payload: { caseName: 'tabgroupcase', mode: 'shell', tabGroupId: 'g1' },
});
expect(res.statusCode).toBe(200);
const data = body(res.body);
expect(ctx.addSession.mock.calls[0][1]).toEqual({ tabGroupId: 'g1' });
expect(data.tabLayout.groups[0].refs).toEqual([{ kind: 'session', id: data.sessionId }]);
const plain = await app.inject({
method: 'POST',
url: '/api/quick-start',
payload: { caseName: 'tabgroupcase', mode: 'shell' },
});
expect(body(plain.body).tabLayout).toBeUndefined();
});
it.each([
['null', null],
['an empty string', ''],
['a number', 7],
['an over-long id', 'g'.repeat(101)],
])('rejects %s as a tabGroupId with a 400 and creates nothing', async (_label, tabGroupId) => {
for (const [url, payload] of [
['/api/sessions', { name: 'w1-x', mode: 'shell', workingDir, tabGroupId }],
['/api/quick-start', { caseName: 'tabgroupcase', mode: 'shell', tabGroupId }],
] as const) {
const res = await app.inject({ method: 'POST', url, payload });
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).errorCode).toBe('INVALID_INPUT');
}
expect(ctx.addSession).not.toHaveBeenCalled();
});
});
+2 -2
View File
@@ -102,7 +102,7 @@ describe('run() dispatch (session-ui.js)', () => {
app._runMode = id;
await expect(app.run()).resolves.toBe(`cli:${id}`);
expect(app._runCliMode).toHaveBeenCalledTimes(1);
expect(app._runCliMode).toHaveBeenCalledWith(id);
expect(app._runCliMode).toHaveBeenCalledWith(id, {});
expect(app.runClaude).not.toHaveBeenCalled();
expect(app.runShell).not.toHaveBeenCalled();
});
@@ -113,7 +113,7 @@ describe('run() dispatch (session-ui.js)', () => {
app._runMode = 'custom-agent';
await expect(app.run()).resolves.toBe('cli:custom-agent');
expect(app._runCliMode).toHaveBeenCalledTimes(1);
expect(app._runCliMode).toHaveBeenCalledWith('custom-agent');
expect(app._runCliMode).toHaveBeenCalledWith('custom-agent', {});
expect(app.runClaude).not.toHaveBeenCalled();
});
+3 -1
View File
@@ -178,7 +178,9 @@ describe('Run launch synchronization', () => {
// once. Confirmed live: adding `this.terminal.clear()` to `_runCliMode`
// left this test 32/32 green under the old pattern.
const bodies = new Map<string, string>();
const header = /^ {2}async (_?run[A-Za-z]*)\(\w*\) \{$/gm;
// Any parameter list (`(mode, options = {})` included), never `\(\w*\)`
// alone, or a launcher that grew a second parameter silently drops out.
const header = /^ {2}async (_?run[A-Za-z]*)\([^)\n]*\) \{$/gm;
for (let m = header.exec(src); m; m = header.exec(src)) {
const start = m.index + m[0].length;
const end = src.indexOf('\n },', start);
+135
View File
@@ -0,0 +1,135 @@
/**
* @fileoverview Launching a session INTO a tab group (the group menu's "New
* session"): session-ui.js run paths with `{ count, tabGroupId }`.
*
* Pins that the group id rides the create request of every launch path (local
* /api/sessions, remote/docker and external-CLI /api/quick-start), that the
* one-session count overrides the toolbar steppers without touching them, that
* the layout returned by the create response is adopted BEFORE the new tab is
* drawn (so it is drawn inside its group), and that an ordinary Run sends no
* group at all.
*
* Port: none (vm sandbox, stubbed fetch).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
const LAYOUT = { version: 9, updatedAt: '', groups: [{ id: 'g1', name: 'Core', refs: [] }], ungrouped: [] };
function harness(caseData: Record<string, unknown>, extra: { mode?: string } = {}) {
const elements: Record<string, any> = {
quickStartCase: { value: 'proj' },
tabCount: { value: '4' },
shellCount: { value: '3' },
};
const requests: Array<{ url: string; body?: any }> = [];
const events: string[] = [];
let counter = 0;
const CodemanApp = function CodemanApp(this: any) {};
const context = vm.createContext({
CodemanApp,
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: (id: string) => elements[id] ?? null },
fetch: async (url: string, init?: { body?: string }) => {
const body = init?.body ? JSON.parse(init.body) : undefined;
requests.push({ url, body });
const json = (value: unknown) => ({ json: async () => value });
if (url === '/api/cases/proj') return json({ success: true, data: caseData });
if (url.endsWith('/status')) return json({ success: true, data: { available: true, runnable: true } });
if (url === '/api/sessions') {
const id = `sess-${++counter}`;
return json({
success: true,
data: { session: { id, name: body.name }, ...(body.tabGroupId ? { tabLayout: LAYOUT } : {}) },
});
}
if (url === '/api/quick-start') {
const id = `sess-${++counter}`;
return json({
success: true,
data: { sessionId: id, session: { id }, ...(body.tabGroupId ? { tabLayout: LAYOUT } : {}) },
});
}
return json({ success: true, data: {} });
},
console,
});
for (const file of ['settings-ui.js', 'session-ui.js']) {
vm.runInContext(readFileSync(resolve(import.meta.dirname, '../src/web/public', file), 'utf8'), context, {
filename: file,
});
}
const app = new (CodemanApp as any)();
app._runMinLockMs = 0;
app._runMode = extra.mode ?? 'claude';
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {}, cols: 80, rows: 24 };
app.sessions = new Map();
app.cases = [{ name: 'proj', location: caseData.location }];
app.loadAppSettingsFromStorage = () => ({});
app.getCaseSettings = () => ({});
app.buildEnvOverrides = () => ({});
app.getEffortSetting = () => undefined;
app.isRalphTrackerEnabledByDefault = () => false;
app.getTerminalDimensions = () => null;
app.isCliAvailable = () => true;
app.loadQuickStartCases = () => {};
app.selectSession = vi.fn(async () => {});
app._applyTabLayout = vi.fn(() => events.push('layout'));
app._onSessionCreated = (session: any) => {
events.push(`created:${session.id}`);
app.sessions.set(session.id, session);
};
app._renderSessionTabsImmediate = () => events.push('render');
return { app, elements, requests, events };
}
const creates = (requests: Array<{ url: string; body?: any }>) =>
requests.filter((req) => req.url === '/api/sessions' || req.url === '/api/quick-start');
describe('launching into a tab group', () => {
it('local Claude: one session with the group id, and the returned layout adopted before the tab renders', async () => {
const { app, elements, requests, events } = harness({ name: 'proj', path: '/tmp/proj' });
await app.run({ count: 1, tabGroupId: 'g1' });
const made = creates(requests);
expect(made).toHaveLength(1);
expect(made[0].url).toBe('/api/sessions');
expect(made[0].body.tabGroupId).toBe('g1');
expect(elements.tabCount.value).toBe('4');
expect(app._applyTabLayout).toHaveBeenCalledWith(LAYOUT);
expect(events.slice(0, 3)).toEqual(['layout', 'created:sess-1', 'render']);
});
it('local Shell honours the same one-session override', async () => {
const { app, elements, requests } = harness({ name: 'proj', path: '/tmp/proj' }, { mode: 'shell' });
await app.run({ count: 1, tabGroupId: 'g1' });
const made = creates(requests);
expect(made).toHaveLength(1);
expect(made[0].body).toMatchObject({ mode: 'shell', tabGroupId: 'g1' });
expect(elements.shellCount.value).toBe('3');
});
it.each([
['remote Claude', { name: 'proj', path: 'u@h:/w', location: 'remote' }, 'claude'],
['remote Shell', { name: 'proj', path: 'u@h:/w', location: 'remote' }, 'shell'],
['an external CLI', { name: 'proj', path: '/tmp/proj' }, 'gemini'],
])('%s carries the group on its quick-start request', async (_label, caseData, mode) => {
const { app, requests } = harness(caseData, { mode });
await app.run({ count: 1, tabGroupId: 'g1' });
const made = creates(requests);
expect(made).toHaveLength(1);
expect(made[0].url).toBe('/api/quick-start');
expect(made[0].body.tabGroupId).toBe('g1');
expect(app._applyTabLayout).toHaveBeenCalledWith(LAYOUT);
});
it('an ordinary Run sends no group and keeps the stepper count', async () => {
const { app, requests } = harness({ name: 'proj', path: '/tmp/proj' });
await app.run();
const made = creates(requests);
expect(made).toHaveLength(4);
expect(made.every((req) => !('tabGroupId' in req.body))).toBe(true);
expect(app._applyTabLayout).not.toHaveBeenCalled();
});
});
+33
View File
@@ -121,6 +121,39 @@ describe('projection', () => {
});
});
describe('projection: sessions spawned by another session', () => {
const grouped = () => ({
version: 3,
updatedAt: '',
groups: [{ id: 'g1', name: 'Core', refs: [s('p'), s('p-kid'), s('x')] }],
ungrouped: [s('u')],
});
const s = (id: string) => ({ kind: 'session', id });
it("draws a child the layout has not stored yet inside its parent's group, after the parent's rows", () => {
const h = loadHelper();
const result = h.project(grouped(), {
liveSessionIds: ['p', 'p-kid', 'x', 'u', 'new', 'grandkid', 'orphan'],
parents: { 'p-kid': 'p', new: 'p', grandkid: 'new', orphan: 'gone' },
});
expect(result.sections.map((section: any) => [section.id, ids(section.refs)])).toEqual([
['g1', ['session:p', 'session:p-kid', 'session:new', 'session:grandkid', 'session:x']],
// A child whose parent is not in the layout has nothing to follow.
[null, ['session:u', 'session:orphan']],
]);
});
it('leaves a stored child where the layout put it, and changes nothing without lineage', () => {
const h = loadHelper();
const layout = { ...grouped(), ungrouped: [s('u'), s('manual-kid')] };
const live = ['p', 'p-kid', 'x', 'u', 'manual-kid'];
const withParents = h.project(layout, { liveSessionIds: live, parents: { 'manual-kid': 'p' } });
expect(ids(withParents.sections[1].refs)).toEqual(['session:u', 'session:manual-kid']);
const without = h.project(layout, { liveSessionIds: [...live, 'new'] });
expect(ids(without.sections[1].refs)).toEqual(['session:u', 'session:manual-kid', 'session:new']);
});
});
describe('structure key', () => {
it('changes with every structural input and ignores everything else', () => {
const h = loadHelper();
+262 -4
View File
@@ -98,6 +98,52 @@ describe('operations', () => {
});
});
describe('child sessions: follow and hand placement', () => {
const h = loadHelper();
const lineage = (): Layout => ({
version: 5,
updatedAt: '',
groups: [
{ id: 'g1', name: 'Core', refs: [s('p'), s('kid'), s('x')] },
{ id: 'g2', name: 'Ops', refs: [{ kind: 'session', id: 'moved', placement: 'manual' }, s('moved-kid')] },
],
ungrouped: [s('u'), { kind: 'session', id: 'orphan', placement: 'manual' }],
});
const parents = { kid: 'p', moved: 'p', 'moved-kid': 'moved', orphan: 'gone' };
it('describes each child: following, placed by hand, or with no parent to follow', () => {
const state = (id: string, extra = {}) => plain(h.placementState(lineage(), s(id), { ...parents, ...extra }));
expect(state('kid')).toEqual({ state: 'inherited', parentId: 'p', canFollow: false });
expect(state('moved')).toEqual({ state: 'manual', parentId: 'p', canFollow: true });
expect(state('orphan')).toEqual({ state: 'dangling', parentId: 'gone', canFollow: false });
expect(state('p')).toBeNull();
expect(state('x', { x: 'u', u: 'x' })).toMatchObject({ state: 'cycle', canFollow: false });
});
it('Follow parent again clears the hand placement and puts the child (and its followers) after its parent', () => {
const next = h.applyOperation(lineage(), { type: 'followParent', ref: s('moved'), parents });
expect(keys(next.groups[0].refs)).toEqual([
'session:p',
'session:kid',
'session:moved',
'session:moved-kid',
'session:x',
]);
expect(next.groups[0].refs.find((ref: Ref) => ref.id === 'moved').placement).toBeUndefined();
expect(next.groups[1].refs).toEqual([]);
});
it('refuses to follow a parent that is gone or loops, and leaves a following child as it is', () => {
expect(() => h.applyOperation(lineage(), { type: 'followParent', ref: s('orphan'), parents })).toThrow();
expect(() =>
h.applyOperation(lineage(), { type: 'followParent', ref: s('x'), parents: { x: 'u', u: 'x' } })
).toThrow();
expect(plain(h.applyOperation(lineage(), { type: 'followParent', ref: s('kid'), parents }))).toEqual(
plain(h.normalizeLayout(lineage()))
);
});
});
describe('drop -> operation', () => {
const h = loadHelper();
@@ -729,7 +775,8 @@ describe('group cap', () => {
app.closeTabRailActionMenu();
header('g0').focus();
key(header('g0'), 'F10', { shiftKey: true });
expect(menuLabels()).toEqual(['Rename group', 'Move group down', 'Delete group']);
// "New session" adds a tab, not a group, so it stays offered at the cap.
expect(menuLabels()).toEqual(['New session', 'Rename group', 'Move group down', 'Delete group']);
app.closeTabGroupMenu();
});
});
@@ -741,15 +788,15 @@ describe('group menu', () => {
win.confirm = vi.fn(() => true);
header('gx').focus();
key(header('gx'), 'F10', { shiftKey: true });
expect(menuLabels()).toEqual(['Rename group', 'New group', 'Move group down', 'Delete group']);
expect(document.activeElement?.textContent).toBe('Rename group');
expect(menuLabels()).toEqual(['New session', 'Rename group', 'New group', 'Move group down', 'Delete group']);
expect(document.activeElement?.textContent).toBe('New session');
clickMenu('Move group down');
await flush();
expect(puts.at(-1).layout.groups.map((g: any) => g.id)).toEqual(['gy', 'gx']);
expect(document.activeElement).toBe(header('gx'));
key(header('gx'), 'ContextMenu');
expect(menuLabels()).toEqual(['Rename group', 'New group', 'Move group up', 'Delete group']);
expect(menuLabels()).toEqual(['New session', 'Rename group', 'New group', 'Move group up', 'Delete group']);
clickMenu('Delete group');
expect(win.confirm).toHaveBeenCalledWith('Delete group "<Core & Ops>"? Its tabs move to Ungrouped.');
await flush();
@@ -889,6 +936,217 @@ describe('group menu', () => {
});
});
describe('new session in a group', () => {
it('expands a collapsed group and launches ONE session targeted at it', async () => {
installFetch();
const app = makeApp();
app.toggleTabGroupCollapsed('gx', true);
app.run = vi.fn(async () => {});
header('gx').focus();
key(header('gx'), 'F10', { shiftKey: true });
clickMenu('New session');
await flush();
expect(app.run).toHaveBeenCalledTimes(1);
expect(app.run).toHaveBeenCalledWith({ count: 1, tabGroupId: 'gx' });
expect(app.collapsedTabGroupIds.has('gx')).toBe(false);
expect(JSON.parse(win.localStorage.getItem('codeman:tab-groups-collapsed'))).toEqual([]);
expect(document.querySelector('.tab-layout-group-action-menu')).toBeNull();
});
it('says so, and starts nothing, while another launch is in flight', async () => {
installFetch();
const app = makeApp();
app.toggleTabGroupCollapsed('gx', true);
app.run = vi.fn(async () => {});
app._runInFlight = true;
await app.createSessionInTabGroup('gx');
expect(app.run).not.toHaveBeenCalled();
expect(app.collapsedTabGroupIds.has('gx')).toBe(true);
expect(app.showToast).toHaveBeenCalledWith('A session is already starting.', 'info');
// A group that no longer exists starts nothing either.
app._runInFlight = false;
expect(await app.createSessionInTabGroup('deleted')).toBe(false);
expect(app.run).not.toHaveBeenCalled();
});
});
describe('child session placement in the row menu', () => {
const lineageLayout = (): Layout => ({
version: 8,
updatedAt: '2026-10-01T00:00:00.000Z',
groups: [
{ id: 'gx', name: 'Core', refs: [s('s1'), s('s2')] },
{ id: 'gy', name: 'Later', refs: [{ kind: 'session', id: 's3', placement: 'manual' }] },
],
ungrouped: [],
});
const openMenu = (app: Record<string, any>, id: string) =>
app.openTabRailActionMenu({ preventDefault() {}, stopPropagation() {}, currentTarget: row(id) }, id);
it('shows where a child sits and offers Follow parent again only to a hand-placed child', async () => {
const puts = installFetch();
const app = makeApp(lineageLayout());
app.sessions.get('s2').parentSessionId = 's1';
app.sessions.get('s3').parentSessionId = 's1';
openMenu(app, 's2');
expect(menuLabels()).toContain('Follows One');
expect(menuLabels()).not.toContain('Follow parent again');
const summary = [...document.querySelectorAll<HTMLElement>('.tab-rail-action-menu button')].find(
(button) => button.textContent === 'Follows One'
)!;
expect(summary.getAttribute('aria-disabled')).toBe('true');
summary.click(); // informational: does nothing, keeps the menu open
expect(document.querySelector('.tab-rail-action-menu')).not.toBeNull();
app.closeTabRailActionMenu();
openMenu(app, 's3');
expect(menuLabels()).toContain('Placed by hand (parent: One)');
clickMenu('Follow parent again');
// Optimistic: the child is back under its parent at once.
expect(row('s3').closest('.tab-layout-group')!.getAttribute('data-tab-group-id')).toBe('gx');
await flush();
expect(puts).toHaveLength(1);
expect(puts[0].layout.groups[0].refs).toEqual([s('s1'), s('s2'), s('s3')]);
expect(puts[0].layout.groups[1].refs).toEqual([]);
});
it('a child whose parent is gone says so and cannot follow', () => {
installFetch();
const app = makeApp({
...lineageLayout(),
groups: [{ id: 'gx', name: 'Core', refs: [{ kind: 'session', id: 's2', placement: 'manual' }] }],
ungrouped: [s('s3')],
});
app.sessions.delete('s1');
app.sessions.get('s2').parentSessionId = 's1';
openMenu(app, 's2');
expect(menuLabels()).toContain('Parent closed; placed on its own');
expect(menuLabels()).not.toContain('Follow parent again');
});
it('a hand move makes a following child manual, so it stays when its parent moves', async () => {
const puts = installFetch();
const app = makeApp(lineageLayout());
app.sessions.get('s2').parentSessionId = 's1';
openMenu(app, 's2');
clickMenu('Move to "Later"');
await flush();
expect(puts[0].layout.groups[1].refs).toEqual([
{ kind: 'session', id: 's3', placement: 'manual' },
{ kind: 'session', id: 's2', placement: 'manual' },
]);
openMenu(app, 's1');
clickMenu('Move to Ungrouped');
await flush();
expect(puts[1].layout.ungrouped).toEqual([s('s1')]);
expect(keys(puts[1].layout.groups[1].refs)).toEqual(['session:s3', 'session:s2']);
});
it('adds nothing to the menu for a session without a parent, or outside a grouped rail', () => {
installFetch();
const app = makeApp(lineageLayout());
openMenu(app, 's1');
expect(menuLabels()).toEqual([
'Session options',
'Move down',
'Move to "Later"',
'Move to Ungrouped',
'Move to new group',
'Close session',
]);
});
});
describe('the server places created and closed sessions while groups exist', () => {
const orderPuts = () =>
(win.fetch as any).mock.calls.filter(([url]: [string]) => url === '/api/session-order').length;
const stub = (app: Record<string, any>) => {
app._debounceTimers = {};
app.markSessionTabEntering = () => {};
app.markTerminalEntering = () => {};
app.markConnectionLineEntering = () => {};
app.renderSessionTabs = () => app._fullRenderSessionTabs();
app.updateCost = () => {};
app.startSystemStatsPolling = () => {};
};
it('a spawned child is drawn after its parent and NOT echoed back as a hand order (which would pin it)', async () => {
installFetch();
const app = makeApp();
stub(app);
// The server already broadcast its order with the child after its parent.
win.localStorage.setItem('codeman-session-order', JSON.stringify(['s1', 's2', 'kid', 's3']));
app._onSessionCreated({ id: 'kid', name: 'Kid', status: 'idle', parentSessionId: 's2' });
expect(row('kid').closest('.tab-layout-group')!.getAttribute('data-tab-group-id')).toBe('gx');
expect(app.sessionOrder).toEqual(['s1', 's2', 'kid', 's3']);
await new Promise((resolve) => setTimeout(resolve, 450));
expect(orderPuts()).toBe(0);
// The order bookkeeping runs first in _cleanupSessionData; the buffer and
// timer maps it clears afterwards are not part of this harness.
try {
app._cleanupSessionData('kid');
} catch {}
expect(app.sessionOrder).toEqual(['s1', 's2', 's3']);
await new Promise((resolve) => setTimeout(resolve, 450));
expect(orderPuts()).toBe(0);
});
it('keeps the flat rail exactly as before: a new session is appended and its order saved', async () => {
installFetch();
const app = makeApp({ ...serverLayout(), groups: [], ungrouped: [s('s1'), s('s2'), s('s3')] });
stub(app);
app._onSessionCreated({ id: 'kid', name: 'Kid', status: 'idle', parentSessionId: 's2' });
expect(app.sessionOrder).toEqual(['s1', 's2', 's3', 'kid']);
await new Promise((resolve) => setTimeout(resolve, 450));
expect(orderPuts()).toBe(1);
});
});
describe('saved web tabs in groups (openness is per device)', () => {
const webLayout = (): Layout => ({
version: 8,
updatedAt: '2026-10-01T00:00:00.000Z',
groups: [{ id: 'gx', name: 'Dash', refs: [s('s1'), w('w1'), s('s2')] }],
ungrouped: [s('s3'), w('w2')],
});
const webRows = () =>
[...document.querySelectorAll<HTMLElement>('.session-tab[data-webview-id]')].map((el) => [
el.closest('.tab-layout-group')!.getAttribute('data-tab-group-id'),
el.dataset.webviewId,
el.querySelector('.tab-number')?.textContent ?? null,
]);
it('shows a grouped web tab only while it is open here, and reopens it where the layout keeps it', () => {
installFetch();
const app = makeApp(null);
app.webviews = new Map([
['w1', { id: 'w1', name: 'One', url: 'https://one.test' }],
['w2', { id: 'w2', name: 'Two', url: 'https://two.test' }],
]);
app.webviewOrder = ['w1'];
app._applyTabLayout(webLayout());
// w2 is saved and placed, but not open on this device: no row, no number.
expect(webRows()).toEqual([['gx', 'w1', '4']]);
expect(header('gx').querySelector('.tab-layout-group-count')!.textContent).toBe('3');
app.webviewOrder = [];
app._fullRenderSessionTabs();
expect(webRows()).toEqual([]);
// The group survives with its sessions; the layout still holds the web tab.
expect(header('gx').querySelector('.tab-layout-group-count')!.textContent).toBe('2');
expect(keys(app.tabLayout.groups[0].refs)).toEqual(['session:s1', 'webview:w1', 'session:s2']);
app.webviewOrder = ['w2', 'w1'];
app._fullRenderSessionTabs();
const order = [...tabs().querySelectorAll<HTMLElement>('.session-tab')].map(
(el) => el.dataset.webviewId || el.dataset.id
);
expect(order).toEqual(['s1', 'w1', 's2', 's3', 'w2']);
});
});
describe('server echoes and reloads', () => {
it('defers an SSE-triggered read while its own write is in flight, then re-reads once', async () => {
let releasePut: (() => void) | null = null;
+148
View File
@@ -0,0 +1,148 @@
/**
* @fileoverview End to end through the real WebServer: a session created with a
* `tabGroupId` lands in that group in ONE layout version, and a session spawned
* by another one (the X-Codeman-Parent-Session header) follows its parent into
* the parent's group until it is moved by hand.
*
* The service and route halves have their own unit tests; this pins the wiring
* in server.ts (the session joins the live map inside the layout owner lock and
* the placement commits with it) against the real routes and StateStore.
*/
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { WebServer } from '../src/web/server.js';
const TEST_PORT = 3301;
type Ref = { kind: string; id: string; placement?: string };
type Layout = {
version: number;
updatedAt: string;
groups: Array<{ id: string; name: string; refs: Ref[] }>;
ungrouped: Ref[];
};
describe('grouped session creation through the server', () => {
let server: WebServer;
const base = `http://localhost:${TEST_PORT}`;
const workingDir = mkdtempSync(join(tmpdir(), 'codeman-grouped-create-'));
const api = async (
path: string,
init: { method?: string; body?: unknown; headers?: Record<string, string> } = {}
) => {
const res = await fetch(`${base}${path}`, {
method: init.method ?? 'GET',
headers: { 'Content-Type': 'application/json', ...(init.headers ?? {}) },
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
});
return { status: res.status, json: (await res.json()) as any };
};
const layout = async (): Promise<Layout> => (await api('/api/tab-layout')).json.data.layout;
const create = async (body: Record<string, unknown>, headers?: Record<string, string>) => {
const res = await api('/api/sessions', { method: 'POST', body: { workingDir, mode: 'shell', ...body }, headers });
expect(res.status).toBe(200);
return res.json.data as { session: { id: string }; tabLayout?: Layout };
};
const ids = (refs: Ref[]) => refs.map((ref) => ref.id);
beforeAll(async () => {
server = new WebServer(TEST_PORT, false, true);
await server.start();
});
afterAll(async () => {
await server.stop();
}, 60000);
it('places the new session at the end of the group in the same write that records it', async () => {
const first = await create({ name: 'first' });
const current = await layout();
const put = await api('/api/tab-layout', {
method: 'PUT',
body: {
baseVersion: current.version,
layout: {
...current,
groups: [{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: first.session.id }] }],
ungrouped: [],
},
},
});
expect(put.status).toBe(200);
const before = put.json.data.layout as Layout;
const made = await create({ name: 'grouped', tabGroupId: 'g1' });
const after = await layout();
expect(after.version).toBe(before.version + 1);
expect(ids(after.groups[0].refs)).toEqual([first.session.id, made.session.id]);
expect(made.tabLayout).toEqual(after);
// An unknown group is a hint that does not apply: the session is still created.
const loose = await create({ name: 'loose', tabGroupId: 'no-such-group' });
expect(ids((await layout()).ungrouped)).toContain(loose.session.id);
});
it('a spawned child follows its parent into the group, and stays put once moved by hand', async () => {
const start = await layout();
const parentId = start.groups[0].refs[0].id;
const child = await create({ name: 'child' }, { 'X-Codeman-Parent-Session': parentId });
const followed = await layout();
expect(ids(followed.groups[0].refs).slice(0, 2)).toEqual([parentId, child.session.id]);
// Hand-move the child to Ungrouped (what the browser sends for a moveRef).
const moved = await api('/api/tab-layout', {
method: 'PUT',
body: {
baseVersion: followed.version,
layout: {
...followed,
groups: [
{ ...followed.groups[0], refs: followed.groups[0].refs.filter((ref) => ref.id !== child.session.id) },
],
ungrouped: [...followed.ungrouped, { kind: 'session', id: child.session.id, placement: 'manual' }],
},
},
});
expect(moved.status).toBe(200);
const after = await layout();
expect(after.ungrouped.find((ref) => ref.id === child.session.id)).toEqual({
kind: 'session',
id: child.session.id,
placement: 'manual',
});
expect(ids(after.groups[0].refs)).not.toContain(child.session.id);
});
});
describe('server.ts addSession wiring', () => {
it("keys the placement on the SESSION's owner and registers it only inside the layout call", async () => {
const sessions = new Map<string, unknown>();
let registered: (() => void | (() => void)) | undefined;
const sessionCreated = vi.fn(async (_owner: string, _id: string, _placement: unknown, register: () => unknown) => {
expect(sessions.has('bob-new')).toBe(false);
registered = register as never;
const rollback = register() as () => void;
expect(sessions.get('bob-new')).toBe(session);
rollback();
return { version: 1 };
});
const server = Object.create(WebServer.prototype) as any;
server.sessions = sessions;
server.tabLayouts = { sessionCreated };
const session = { id: 'bob-new', owner: 'bob' };
await server.registerSessionWithLayout(session, { tabGroupId: 'g1' });
expect(sessionCreated).toHaveBeenCalledWith('bob', 'bob-new', { tabGroupId: 'g1' }, expect.any(Function));
// The rollback removed it; a rollback never removes a DIFFERENT session under that id.
expect(sessions.has('bob-new')).toBe(false);
const rollback = registered!() as () => void;
const replacement = { id: 'bob-new', owner: 'bob' };
sessions.set('bob-new', replacement);
rollback();
expect(sessions.get('bob-new')).toBe(replacement);
});
});
+141
View File
@@ -1273,3 +1273,144 @@ describe('TabLayoutService', () => {
expect(Object.hasOwn(h.store.commitTabLayoutProjection.mock.calls.at(-1)![0], 'bob')).toBe(true);
});
});
describe('TabLayoutService grouped session creation', () => {
const grouped = (version = 7): TabLayout => ({
version,
groups: [
{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: 'a' }] },
{ id: 'g2', name: 'Ops', refs: [] },
],
ungrouped: [{ kind: 'session', id: 'b' }],
updatedAt: '2026-08-15T00:00:00.000Z',
});
const facts = (owner = 'alice') => [
{ id: 'a', owner, createdAt: 1 },
{ id: 'b', owner, createdAt: 2 },
];
/** Registers `id` the way server.ts does: inside the owner lock, with a rollback. */
const register = (h: ReturnType<typeof createHarness>, fact: SessionFact) =>
vi.fn(() => {
h.live.set(fact.id, fact as never);
return () => h.live.delete(fact.id);
});
it('places a new session at the end of the requested group in ONE versioned write', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const added = register(h, { id: 'new', owner: 'alice', createdAt: 3 });
const layout = await h.service.sessionCreated('alice', 'new', { tabGroupId: 'g1' }, added);
expect(added).toHaveBeenCalledOnce();
expect(layout.version).toBe(8);
expect(layout.groups[0].refs).toEqual([
{ kind: 'session', id: 'a' },
{ kind: 'session', id: 'new' },
]);
expect(layout.ungrouped).toEqual([{ kind: 'session', id: 'b' }]);
expect(h.layouts.alice).toEqual(layout);
expect(h.store.commitTabLayoutProjection).toHaveBeenCalledTimes(1);
expect(h.broadcast.mock.calls.filter(([event]) => event === SseEvent.TabLayoutChanged)).toEqual([
[SseEvent.TabLayoutChanged, { owner: 'alice', version: 8 }],
]);
});
it('registers the session INSIDE the owner lock, so a queued edit cannot commit it first', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts(), order: ['a', 'b'] });
let release!: () => void;
const blocked = new Promise<void>((resolve) => (release = resolve));
h.readWebviews.mockImplementationOnce(async () => {
await blocked;
return [];
});
const occupied = h.service.get('alice');
await vi.waitFor(() => expect(h.readWebviews).toHaveBeenCalledOnce());
const added = register(h, { id: 'new', owner: 'alice', createdAt: 3 });
const created = h.service.sessionCreated('alice', 'new', { tabGroupId: 'g2' }, added);
await Promise.resolve();
expect(added).not.toHaveBeenCalled();
release();
await occupied;
const layout = await created;
expect(layout.groups[1].refs).toEqual([{ kind: 'session', id: 'new' }]);
// The queued read committed nothing; the creation is the only write.
expect(h.store.commitTabLayoutProjection).toHaveBeenCalledTimes(1);
expect(layout.version).toBe(8);
});
it('treats an unknown group as a hint, not an error: the session lands where it normally would', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const layout = await h.service.sessionCreated(
'alice',
'new',
{ tabGroupId: 'gone' },
register(h, { id: 'new', owner: 'alice', createdAt: 3 })
);
expect(layout.ungrouped.map((ref) => ref.id)).toEqual(['b', 'new']);
expect(layout.groups.flatMap((group) => group.refs.map((ref) => ref.id))).toEqual(['a']);
});
it("never places a session into another owner's group", async () => {
const h = createHarness({
layouts: { alice: grouped(), bob: existing([{ kind: 'session', id: 'bob-1' }], 3) },
live: [...facts(), { id: 'bob-1', owner: 'bob', createdAt: 4 }],
});
const layout = await h.service.sessionCreated(
'bob',
'bob-new',
{ tabGroupId: 'g1' },
register(h, { id: 'bob-new', owner: 'bob', createdAt: 5 })
);
expect(layout.groups).toEqual([]);
expect(layout.ungrouped.map((ref) => ref.id)).toEqual(['bob-1', 'bob-new']);
expect(h.layouts.alice).toEqual(grouped());
});
it("a child follows its parent into the parent's group; an explicit group pins it manual", async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const followed = await h.service.sessionCreated(
'alice',
'child',
{},
register(h, { id: 'child', owner: 'alice', createdAt: 3, parentSessionId: 'a' })
);
expect(followed.groups[0].refs).toEqual([
{ kind: 'session', id: 'a' },
{ kind: 'session', id: 'child' },
]);
const pinned = await h.service.sessionCreated(
'alice',
'child-2',
{ tabGroupId: 'g2' },
register(h, { id: 'child-2', owner: 'alice', createdAt: 4, parentSessionId: 'a' })
);
expect(pinned.groups[1].refs).toEqual([{ kind: 'session', id: 'child-2', placement: 'manual' }]);
// Moving the parent later leaves the hand-placed child where it was.
const moved = await h.service.put(
'alice',
{
...pinned,
groups: [{ ...pinned.groups[0], refs: [] }, pinned.groups[1]],
ungrouped: [...pinned.ungrouped, ...pinned.groups[0].refs],
},
pinned.version
);
expect(moved.layout.groups[1].refs).toEqual([{ kind: 'session', id: 'child-2', placement: 'manual' }]);
expect(moved.layout.ungrouped.map((ref) => ref.id)).toEqual(['b', 'a', 'child']);
});
it('rolls the registration back when the layout write fails', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
h.store.commitTabLayoutProjection.mockImplementationOnce(() => {
throw new Error('disk full');
});
const added = register(h, { id: 'new', owner: 'alice', createdAt: 3 });
await expect(h.service.sessionCreated('alice', 'new', { tabGroupId: 'g1' }, added)).rejects.toThrow('disk full');
expect(added).toHaveBeenCalledOnce();
expect(h.live.has('new')).toBe(false);
expect(h.layouts.alice).toEqual(grouped());
});
});