Merge pull request #528: feat(tabs): place new, child and web tabs into groups

Conflict resolved in docs/api-reference.md: #607's prompt cache section and
#528's tabGroupId section are both kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-10-13 18:10:37 +02:00
commit a38eab49cd
30 files changed
+1932 -79

No files matched your search

+27 -2
View File
@@ -189,14 +189,39 @@ describe('custom display name and browser localization', () => {
const dom = makeDom('');
const api = dom.window.CodemanI18n;
api.configure({ language: 'zh-CN' });
const labels = ['Move to "New group"', 'Move to new group', 'Move to "ungrouped"', 'Move to Ungrouped'].map((label) =>
api.t(label)
const labels = ['Move to "New group"', 'Move to new group', 'Move to "ungrouped"', 'Move to Ungrouped'].map(
(label) => api.t(label)
);
expect(labels).toEqual(['移到“New group”', '移到新分组', '移到“ungrouped”', '移到未分组']);
expect(new Set(labels).size).toBe(4);
dom.window.close();
});
it('never translates a tab name, even one that reads like a UI string', async () => {
const tab = (name: string) =>
`<div class="session-tab"><span class="tab-info"><span class="tab-name-row">` +
`<span class="tab-name" data-full-name="${name}">${name}</span></span></span></div>`;
const dom = makeDom(
`<div id="sessionTabs">${tab('New session')}${tab('Follows up on bug')}</div><div id="menu"></div>`
);
const { window } = dom;
const api = window.CodemanI18n;
api.start();
api.configure({ language: 'zh-CN' });
const names = () => [...window.document.querySelectorAll('.tab-name')].map((el) => el.textContent);
expect(names()).toEqual(['New session', 'Follows up on bug']);
// A tab drawn after the switch stays untranslated too, while the same
// strings as real UI text still translate.
window.document.getElementById('sessionTabs')!.insertAdjacentHTML('beforeend', tab('New session'));
const menu = window.document.getElementById('menu')!;
menu.innerHTML = '<button>New session</button><div class="tab-rail-action-menu-note">Follows One</div>';
await new Promise((resolve) => setTimeout(resolve, 0));
expect(names()).toEqual(['New session', 'Follows up on bug', 'New session']);
expect(menu.querySelector('button')?.textContent).toBe('新建会话');
expect(menu.querySelector('div')?.textContent).toBe('跟随 One');
dom.window.close();
});
it('renders hostile-looking names as text rather than HTML', () => {
const dom = makeDom('<span class="logo">Codeman</span>');
const api = dom.window.CodemanI18n;
@@ -0,0 +1,226 @@
/**
* @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';
import { TabLayoutService } from '../../src/tab-layout-service.js';
import { ownerLayoutKey } from '../../src/tab-layout-persistence.js';
import type { TabLayout } from '../../src/tab-layout.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();
});
});
describe('create routes: tabGroupId through the real layout service', () => {
let app: FastifyInstance;
let ctx: MockRouteContext;
let workingDir: string;
const layouts: Record<string, TabLayout> = {};
let order: string[] = [];
beforeEach(async () => {
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
workingDir = await mkdtemp(join(tmpdir(), 'codeman-tab-group-real-'));
app = Fastify({ logger: false });
await app.register(fastifyCookie);
ctx = createMockRouteContext();
ctx.sessions.clear(); // only the sessions these requests create
for (const key of Object.keys(layouts)) delete layouts[key];
order = [];
// The real service over an in-memory store, wired the way server.ts wires it.
const service = new TabLayoutService({
store: {
getTabLayout: (owner: string) => layouts[owner] ?? null,
getTabLayouts: () => ({ ...layouts }),
getSessions: () => ({}),
getSessionOrder: () => [...order],
commitTabLayoutProjection: (
updates: Readonly<Record<string, TabLayout>>,
project: (latest: readonly string[]) => readonly string[]
) => {
order = [...project(order)];
Object.assign(layouts, structuredClone(updates));
return { layouts: structuredClone(updates), sessionOrder: [...order] };
},
} as never,
sessions: ctx.sessions as never,
readWebviews: async () => [],
broadcast: () => {},
broadcastSessionOrder: () => {},
});
service.markRestorationSkipped();
ctx.addSession.mockImplementation((session: Session, placement?: { tabGroupId?: string }) =>
service.sessionCreated(ownerLayoutKey(session.owner), session.id, placement, () => {
ctx.sessions.set(session.id, session as never);
return () => ctx.sessions.delete(session.id);
})
);
registerSessionRoutes(app, ctx);
installRouteErrorHandler(app);
await app.ready();
});
afterEach(async () => {
await app.close();
await rm(workingDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
const unwrap = (raw: string) => {
const parsed = JSON.parse(raw);
return parsed.data ?? parsed;
};
it('places the created session at the end of an existing group and returns the stored layout', async () => {
const first = await app.inject({
method: 'POST',
url: '/api/sessions',
payload: { name: 'w1-x', mode: 'shell', workingDir },
});
const firstId = unwrap(first.body).session.id as string;
const owner = Object.keys(layouts)[0];
layouts[owner] = {
...layouts[owner],
groups: [{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: firstId }] }],
ungrouped: [],
};
const res = await app.inject({
method: 'POST',
url: '/api/sessions',
payload: { name: 'w2-x', mode: 'shell', workingDir, tabGroupId: 'g1' },
});
expect(res.statusCode).toBe(200);
const data = unwrap(res.body);
expect(data.tabLayout).toEqual(layouts[owner]);
expect(data.tabLayout.version).toBe(layouts[owner].version);
expect(data.tabLayout.groups[0].refs).toEqual([
{ kind: 'session', id: firstId },
{ kind: 'session', id: data.session.id },
]);
expect(data.tabLayout.ungrouped).toEqual([]);
expect(order).toEqual([firstId, data.session.id]);
});
});
+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);
+13 -4
View File
@@ -6,9 +6,17 @@ describe('scheduled session layout registration', () => {
it('registers the layout before lifecycle work and rolls back a rejected tentative session', async () => {
const sessions = new Map<string, { id: string; owner?: string }>();
const session = { id: 'scheduled-session', owner: 'alice' };
const sessionCreated = vi.fn(async () => {
throw new Error('layout unavailable');
});
let registeredBeforeFailure = false;
// The layout service registers the session inside its owner lock, then the
// write fails and it calls the undo it was handed.
const sessionCreated = vi.fn(
async (_owner: string, _id: string, _placement: unknown, register: () => void | (() => void)) => {
const undo = register();
registeredBeforeFailure = sessions.get(session.id) === session;
if (typeof undo === 'function') undo();
throw new Error('layout unavailable');
}
);
const server = Object.create(WebServer.prototype) as {
sessions: typeof sessions;
tabLayouts: { sessionCreated: typeof sessionCreated };
@@ -19,7 +27,8 @@ describe('scheduled session layout registration', () => {
await expect(server.registerSessionWithLayout(session)).rejects.toThrow('layout unavailable');
expect(sessionCreated).toHaveBeenCalledWith('alice');
expect(sessionCreated).toHaveBeenCalledWith('alice', 'scheduled-session', undefined, expect.any(Function));
expect(registeredBeforeFailure).toBe(true);
expect(sessions.has(session.id)).toBe(false);
});
+68
View File
@@ -0,0 +1,68 @@
/**
* The "Spawned tabs follow their parent" setting (`spawnedTabsFollowParent`).
*
* SYNCED and OFF by default: the server does the placement, so the value must
* reach it (in SettingsUpdateSchema, never a per-device display key), and the
* layout service reads it at every session creation. These tests read the real
* schema, settings-ui.js, index.html, i18n.js, server.ts and the wiki.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { SettingsUpdateSchema } from '../src/web/schemas.js';
const root = resolve(import.meta.dirname, '..');
const read = (path: string) => readFileSync(resolve(root, path), 'utf8');
const html = read('src/web/public/index.html');
const settingsUi = read('src/web/public/settings-ui.js');
const i18n = read('src/web/public/i18n.js');
const server = read('src/web/server.ts');
const wiki = read('docs/wiki/Settings-Reference.md');
const LABEL = 'Spawned Tabs Follow Their Parent';
describe('spawnedTabsFollowParent setting', () => {
it('is a synced boolean in the settings schema', () => {
expect(SettingsUpdateSchema.safeParse({ spawnedTabsFollowParent: true }).success).toBe(true);
expect(SettingsUpdateSchema.safeParse({ spawnedTabsFollowParent: 'yes' }).success).toBe(false);
});
it('is not a per-device display key', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const block = settingsUi.slice(start, settingsUi.indexOf(']);', start));
expect(start).toBeGreaterThan(-1);
expect(block).not.toContain('spawnedTabsFollowParent');
});
it('has an unchecked switch in App Settings > Appearance > Tabs, marked synced', () => {
const tabs = html.slice(html.indexOf('<h4>Tabs</h4><span class="set-scope">device</span>'));
const group = tabs.slice(0, tabs.indexOf('</section>'));
const row = group.match(
/<div class="set-row"[^>]*id="appSettingsSpawnedTabsFollowParentItem"[\s\S]*?<\/label>/
)?.[0];
expect(row).toBeTruthy();
expect(row).toContain(LABEL);
expect(row).toContain('<span class="set-tag">synced</span>');
expect(row).toMatch(/<input type="checkbox" id="appSettingsSpawnedTabsFollowParent">/);
});
it('loads as off unless explicitly true, and saves from the switch', () => {
expect(settingsUi).toContain(
"document.getElementById('appSettingsSpawnedTabsFollowParent').checked = settings.spawnedTabsFollowParent === true;"
);
expect(settingsUi).toContain(
"spawnedTabsFollowParent: document.getElementById('appSettingsSpawnedTabsFollowParent').checked,"
);
});
it('is read fresh by the layout service at creation time', () => {
expect(server).toMatch(
/childrenFollowParent: async \(\) => \(await this\.readSettings\(true\)\)\.spawnedTabsFollowParent === true/
);
});
it('has a zh-CN label and a wiki row', () => {
expect(i18n).toMatch(new RegExp(`'${LABEL}': '[^']+'`));
expect(wiki).toMatch(new RegExp(`\\| ${LABEL}\\s+\\|[^\\n]*Synced, off by default`));
});
});
+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();
+347 -8
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();
@@ -144,7 +190,10 @@ describe('drop -> operation', () => {
const onUngrouped = h.dropOperation(base(), { type: 'ref', ref: s('a') }, { type: 'ungrouped' }, {});
expect(onUngrouped).toMatchObject({ groupId: null });
expect(onUngrouped).not.toHaveProperty('index');
const crowded = { ...base(), groups: [{ ...base().groups[0], refs: [...base().groups[0].refs, s('late')] }, base().groups[1]] };
const crowded = {
...base(),
groups: [{ ...base().groups[0], refs: [...base().groups[0].refs, s('late')] }, base().groups[1]],
};
const replayed = h.applyOperation(crowded, onHeader);
expect(replayed.groups[0].refs.at(-1)).toEqual(w('web'));
});
@@ -729,7 +778,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 +791,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();
@@ -772,7 +822,7 @@ describe('group menu', () => {
expect(app.tabLayout.groups).toHaveLength(2);
});
it("closing the row menu (as session:deleted does) leaves an open group menu and its listeners alone", () => {
it('closing the row menu (as session:deleted does) leaves an open group menu and its listeners alone', () => {
installFetch();
const app = makeApp();
header('gx').focus();
@@ -889,6 +939,293 @@ 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);
/** The synced "Spawned tabs follow their parent" setting, ON. */
const following = (app: Record<string, any>) => {
app.loadAppSettingsFromStorage = () => ({ spawnedTabsFollowParent: true });
return app;
};
const note = () => document.querySelector<HTMLElement>('.tab-rail-action-menu .tab-rail-action-menu-note');
it('shows where a child sits and offers Follow parent again only to a hand-placed child', async () => {
const puts = installFetch();
const app = following(makeApp(lineageLayout()));
app.sessions.get('s2').parentSessionId = 's1';
app.sessions.get('s3').parentSessionId = 's1';
openMenu(app, 's2');
expect(note()!.textContent).toBe('Follows One');
expect(menuLabels()).not.toContain('Follows One');
expect(menuLabels()).not.toContain('Follow parent again');
// Information, not an action: never focusable, never a menu item, and the
// menu opens on its first real action.
expect(note()!.tagName).not.toBe('BUTTON');
expect(note()!.getAttribute('role')).toBe('none');
expect(note()!.hasAttribute('tabindex')).toBe(false);
expect(document.activeElement?.textContent).toBe('Session options');
expect(document.querySelector('.tab-rail-action-menu')!.getAttribute('aria-describedby')).toBe(note()!.id);
note()!.click();
expect(document.querySelector('.tab-rail-action-menu')).not.toBeNull();
app.closeTabRailActionMenu();
openMenu(app, 's3');
expect(note()!.textContent).toBe('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')],
});
following(app);
app.sessions.delete('s1');
app.sessions.get('s2').parentSessionId = 's1';
openMenu(app, 's2');
expect(note()!.textContent).toBe('Parent closed; placed on its own');
expect(menuLabels()).not.toContain('Follow parent again');
});
it('with the follow setting off (the default) shows no follow note and no Follow parent again', () => {
installFetch();
const app = makeApp(lineageLayout());
app.sessions.get('s2').parentSessionId = 's1';
app.sessions.get('s3').parentSessionId = 's1';
for (const id of ['s2', 's3']) {
openMenu(app, id);
expect(note()).toBeNull();
expect(menuLabels()).not.toContain('Follow parent again');
expect(menuLabels()[0]).toBe('Session options');
app.closeTabRailActionMenu();
}
});
it('a hand move makes a following child manual, so it stays when its parent moves', async () => {
const puts = installFetch();
const app = following(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 = following(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; the browser never echoes them', () => {
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 = () => {};
};
/** Create then delete `kid`, with the server's order broadcast landing first. */
const createAndClose = async (app: Record<string, any>, serverOrder: string[]) => {
app._onSessionOrderChanged({ order: serverOrder });
app._onSessionCreated({ id: 'kid', name: 'Kid', status: 'idle', parentSessionId: 's2' });
const created = [...app.sessionOrder];
const drawn = [...tabs().querySelectorAll<HTMLElement>('.session-tab[data-id]')].map((el) => el.dataset.id);
await new Promise((resolve) => setTimeout(resolve, 450));
const putsAfterCreate = orderPuts();
// 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 {}
const closed = [...app.sessionOrder];
await new Promise((resolve) => setTimeout(resolve, 450));
return { created, drawn, closed, putsAfterCreate, putsAfterClose: orderPuts() };
};
it('with groups: a spawned child is drawn after its parent and NOT echoed back as a hand order', async () => {
installFetch();
const app = makeApp();
stub(app);
const result = await createAndClose(app, ['s1', 's2', 'kid', 's3']);
expect(result).toMatchObject({
created: ['s1', 's2', 'kid', 's3'],
// Drawn inside the parent's group, right after it (the rail draws groups first).
drawn: ['s2', 'kid', 's1', 's3'],
closed: ['s1', 's2', 's3'],
putsAfterCreate: 0,
putsAfterClose: 0,
});
});
it('with no groups (the flat rail): the server broadcast decides the order, and nothing is echoed', async () => {
installFetch();
const app = makeApp({ ...serverLayout(), groups: [], ungrouped: [s('s1'), s('s2'), s('s3')] });
stub(app);
const result = await createAndClose(app, ['s1', 's2', 'kid', 's3']);
expect(result).toMatchObject({
created: ['s1', 's2', 'kid', 's3'],
closed: ['s1', 's2', 's3'],
putsAfterCreate: 0,
putsAfterClose: 0,
});
// The header strip and phones read the same sessionOrder the flat rail drew.
expect(result.drawn).toEqual(['s1', 's2', 'kid', 's3']);
});
it('with no layout read at all (the header strip): a session arriving before its order is appended, not saved', async () => {
installFetch();
const app = makeApp(null);
stub(app);
app._onSessionCreated({ id: 'late', name: 'Late', status: 'idle' });
expect(app.sessionOrder).toEqual(['s1', 's2', 's3', 'late']);
await new Promise((resolve) => setTimeout(resolve, 450));
expect(orderPuts()).toBe(0);
// The server's broadcast then wins.
app._onSessionOrderChanged({ order: ['late', 's1', 's2', 's3'] });
expect(app.sessionOrder).toEqual(['late', 's1', 's2', 's3']);
});
});
describe('a session arriving inside a collapsed group', () => {
it('briefly marks the group header instead of arriving silently', async () => {
installFetch();
const app = makeApp();
app.toggleTabGroupCollapsed('gx', true);
// Collapsing alone hides rows that were already there: no mark.
expect(header('gx').classList.contains('tab-layout-group-arrived')).toBe(false);
app.sessions.set('kid', { id: 'kid', name: 'Kid', status: 'idle', parentSessionId: 's2' });
app.sessionOrder.push('kid');
app._fullRenderSessionTabs();
expect(row('kid')).toBeNull();
expect(header('gx').classList.contains('tab-layout-group-arrived')).toBe(true);
expect(header('gy').classList.contains('tab-layout-group-arrived')).toBe(false);
// It survives a re-render while it lasts, then goes.
app._fullRenderSessionTabs();
expect(header('gx').classList.contains('tab-layout-group-arrived')).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 2100));
expect(header('gx').classList.contains('tab-layout-group-arrived')).toBe(false);
app._fullRenderSessionTabs();
expect(header('gx').classList.contains('tab-layout-group-arrived')).toBe(false);
});
});
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;
@@ -969,7 +1306,7 @@ describe('server echoes and reloads', () => {
expect(gets).toHaveLength(1);
});
it('replays only its own owner\'s recent copy of unsaved edits', async () => {
it("replays only its own owner's recent copy of unsaved edits", async () => {
const copy = (extra: Record<string, unknown>) =>
win.sessionStorage.setItem(
'codeman:tab-layout-pending',
@@ -1076,7 +1413,9 @@ describe('server echoes and reloads', () => {
it('keeps the group menu glyph visible where there is no hover (touch tablets)', () => {
const css = read('styles.css');
const block = css.match(/@media \(hover: none\) \{\s*html\[data-tab-orientation='vertical'\] \.tab-rail \.tab-layout-group-menu \{([^}]*)\}/);
const block = css.match(
/@media \(hover: none\) \{\s*html\[data-tab-orientation='vertical'\] \.tab-rail \.tab-layout-group-menu \{([^}]*)\}/
);
expect(block?.[1]).toMatch(/opacity:\s*1/);
});
+175
View File
@@ -0,0 +1,175 @@
/**
* @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) lands after its parent in
* the parent's group: hand-placed from then on by default, or following its
* parent until moved by hand with the synced `spawnedTabsFollowParent` setting.
*
* 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';
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;
let base = '';
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(0, false, true);
await server.start();
base = `http://localhost:${server.boundPort}`;
});
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('by default a spawned child lands after its parent once and is hand-placed', async () => {
const start = await layout();
const parentId = start.groups[0].refs[0].id;
const child = await create({ name: 'pinned-child' }, { 'X-Codeman-Parent-Session': parentId });
const after = await layout();
expect(after.groups[0].refs.slice(0, 2)).toEqual([
{ kind: 'session', id: parentId },
{ kind: 'session', id: child.session.id, placement: 'manual' },
]);
});
it('with the follow setting on, a spawned child follows its parent until moved by hand', async () => {
const saved = await api('/api/settings', { method: 'PUT', body: { spawnedTabsFollowParent: true } });
expect(saved.status).toBe(200);
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(followed.groups[0].refs.slice(0, 2)).toEqual([
{ kind: 'session', id: parentId },
{ kind: 'session', id: child.session.id },
]);
// A legacy order PUT of the current order (what any device may send) keeps it following.
const order = [...followed.groups.flatMap((group) => group.refs), ...followed.ungrouped]
.filter((ref) => ref.kind === 'session')
.map((ref) => ref.id);
const echoed = await api('/api/session-order', { method: 'PUT', body: { order } });
expect(echoed.status).toBe(200);
expect(echoed.json.data.order).toEqual(order);
expect((await layout()).groups[0].refs.find((ref) => ref.id === child.session.id)).toEqual({
kind: 'session',
id: child.session.id,
});
// Hand-move the child to Ungrouped (what the browser sends for a moveRef).
const before = await layout();
const moved = await api('/api/tab-layout', {
method: 'PUT',
body: {
baseVersion: before.version,
layout: {
...before,
groups: [{ ...before.groups[0], refs: before.groups[0].refs.filter((ref) => ref.id !== child.session.id) }],
ungrouped: [...before.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);
});
});
+80
View File
@@ -83,6 +83,86 @@ describe('applyLegacySessionRank', () => {
expect(normalizeTabLayout(result, facts)).toEqual(result);
});
it('leaves every placement alone when the requested order is the current order', () => {
const input = layout({
groups: [
{
id: 'family',
name: 'Family',
refs: [session('parent'), session('child'), session('grandchild'), session('other')],
},
],
ungrouped: [session('loose', 'manual')],
});
const facts = [
metadata('parent', { order: 0 }),
metadata('child', { order: 1, parentSessionId: 'parent' }),
metadata('grandchild', { order: 2, parentSessionId: 'child' }),
metadata('other', { order: 3 }),
metadata('loose', { order: 4, parentSessionId: 'parent' }),
];
const result = applyLegacySessionRank(input, ['parent', 'child', 'grandchild', 'other', 'loose'], facts);
expect(result.groups[0].refs).toEqual(input.groups[0].refs);
expect(result.ungrouped).toEqual([session('loose', 'manual')]);
});
it('keeps a child following when the reorder keeps it in its parent block', () => {
const input = layout({
ungrouped: [session('x'), session('parent'), session('c1'), session('c2'), webview('w'), session('y')],
});
const facts = [
metadata('x', { order: 0 }),
metadata('parent', { order: 1 }),
metadata('c1', { order: 2, parentSessionId: 'parent' }),
metadata('c2', { order: 3, parentSessionId: 'parent' }),
metadata('y', { order: 4 }),
];
// The whole family moves ahead of x, and its two children swap places.
const result = applyLegacySessionRank(input, ['parent', 'c2', 'c1', 'x', 'y'], facts);
expect(result.ungrouped).toEqual([
session('parent'),
session('c2'),
session('c1'),
session('x'),
webview('w'),
session('y'),
]);
});
it('does not read a web tab left between a parent and its child as a split', () => {
const input = layout({ ungrouped: [session('x'), webview('w'), session('parent'), session('child')] });
const facts = [
metadata('x', { order: 0 }),
metadata('parent', { order: 1 }),
metadata('child', { order: 2, parentSessionId: 'parent' }),
];
const result = applyLegacySessionRank(input, ['parent', 'child', 'x'], facts);
expect(result.ungrouped).toEqual([session('parent'), session('child'), webview('w'), session('x')]);
});
it('pins only the child the requested order splits from its parent block', () => {
const input = layout({
ungrouped: [session('parent'), session('c1'), session('c2'), session('x')],
});
const facts = [
metadata('parent', { order: 0 }),
metadata('c1', { order: 1, parentSessionId: 'parent' }),
metadata('c2', { order: 2, parentSessionId: 'parent' }),
metadata('x', { order: 3 }),
];
const result = applyLegacySessionRank(input, ['parent', 'c1', 'x', 'c2'], facts);
expect(result.ungrouped).toEqual([session('parent'), session('c1'), session('x'), session('c2', 'manual')]);
expect(normalizeTabLayout(result, facts)).toEqual(result);
});
it('keeps a ranked child manual in its group when normalization materializes its missing parent', () => {
const input = layout({
groups: [{ id: 'child-group', name: 'Child', refs: [session('child')] }],
+287
View File
@@ -16,6 +16,8 @@ function createHarness(
live?: SessionFact[];
webviews?: Array<{ id: string; owner?: string }>;
now?: () => string;
/** The synced spawnedTabsFollowParent setting (absent = off, the default). */
follow?: boolean;
} = {}
) {
const layouts = { ...(options.layouts ?? {}) };
@@ -45,6 +47,7 @@ function createHarness(
readWebviews,
broadcast,
broadcastSessionOrder,
childrenFollowParent: vi.fn(() => options.follow === true),
now: options.now ?? (() => '2026-08-16T12:00:00.000Z'),
});
return { service, store, broadcast, broadcastSessionOrder, layouts, order, live, persisted, readWebviews };
@@ -1273,3 +1276,287 @@ 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('with the follow setting on, a child follows its parent; an explicit group pins it manual', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts(), follow: true });
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' }]);
// Move ONLY the parent: the following child goes with it, the hand-placed one stays.
const moved = await h.service.put(
'alice',
{
...pinned,
groups: [{ ...pinned.groups[0], refs: [{ kind: 'session', id: 'child' }] }, pinned.groups[1]],
ungrouped: [...pinned.ungrouped, { kind: 'session', id: 'a' }],
},
pinned.version
);
expect(moved.layout.groups[0].refs).toEqual([]);
expect(moved.layout.groups[1].refs).toEqual([{ kind: 'session', id: 'child-2', placement: 'manual' }]);
expect(moved.layout.ungrouped).toEqual([
{ kind: 'session', id: 'b' },
{ kind: 'session', id: 'a' },
{ kind: 'session', id: 'child' },
]);
});
it('with the follow setting off (the default), a child lands after its parent once and is hand-placed', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const created = await h.service.sessionCreated(
'alice',
'child',
{},
register(h, { id: 'child', owner: 'alice', createdAt: 3, parentSessionId: 'a' })
);
// Same place as a following child, in ONE write, but pinned there.
expect(created.version).toBe(8);
expect(h.store.commitTabLayoutProjection).toHaveBeenCalledTimes(1);
expect(created.groups[0].refs).toEqual([
{ kind: 'session', id: 'a' },
{ kind: 'session', id: 'child', placement: 'manual' },
]);
const moved = await h.service.put(
'alice',
{
...created,
groups: [{ ...created.groups[0], refs: [created.groups[0].refs[1]] }, created.groups[1]],
ungrouped: [...created.ungrouped, { kind: 'session', id: 'a' }],
},
created.version
);
expect(moved.layout.groups[0].refs).toEqual([{ kind: 'session', id: 'child', placement: 'manual' }]);
expect(moved.layout.ungrouped.map((ref) => ref.id)).toEqual(['b', 'a']);
});
it('reads the follow setting fresh at every creation', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const setting = vi.fn<() => boolean>().mockReturnValueOnce(true).mockReturnValueOnce(false);
(h.service as unknown as { deps: { childrenFollowParent: typeof setting } }).deps.childrenFollowParent = setting;
await h.service.sessionCreated(
'alice',
'c1',
{},
register(h, { id: 'c1', owner: 'alice', createdAt: 3, parentSessionId: 'a' })
);
const layout = await h.service.sessionCreated(
'alice',
'c2',
{},
register(h, { id: 'c2', owner: 'alice', createdAt: 4, parentSessionId: 'a' })
);
expect(setting).toHaveBeenCalledTimes(2);
expect(layout.groups[0].refs).toEqual([
{ kind: 'session', id: 'a' },
{ kind: 'session', id: 'c1' },
{ kind: 'session', id: 'c2', placement: 'manual' },
]);
});
it('a session without a parent is never pinned, whatever the setting', async () => {
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
const layout = await h.service.sessionCreated(
'alice',
'plain',
{},
register(h, { id: 'plain', owner: 'alice', createdAt: 3 })
);
expect(layout.ungrouped).toEqual([
{ kind: 'session', id: 'b' },
{ kind: 'session', id: 'plain' },
]);
});
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());
});
});
describe('TabLayoutService legacy order PUTs keep a following child following', () => {
const family = (): TabLayout => ({
version: 4,
groups: [
{
id: 'g1',
name: 'Core',
refs: [
{ kind: 'session', id: 'x' },
{ kind: 'session', id: 'p' },
{ kind: 'session', id: 'kid' },
],
},
],
ungrouped: [{ kind: 'session', id: 'y' }],
updatedAt: '2026-08-15T00:00:00.000Z',
});
const live = [
{ id: 'x', owner: 'alice', createdAt: 1 },
{ id: 'p', owner: 'alice', createdAt: 2 },
{ id: 'kid', owner: 'alice', createdAt: 3, parentSessionId: 'p' },
{ id: 'y', owner: 'alice', createdAt: 4 },
];
for (const actor of [
{ owner: 'alice', isAdmin: false },
{ owner: 'admin', isAdmin: true },
]) {
it(`a PUT of the current order leaves placement alone (${actor.isAdmin ? 'admin' : 'owner'})`, async () => {
const h = createHarness({ layouts: { alice: family() }, live, order: ['x', 'p', 'kid', 'y'] });
await h.service.putLegacyOrder(actor, ['x', 'p', 'kid', 'y']);
expect(h.layouts.alice).toEqual(family());
expect(h.store.commitTabLayoutProjection.mock.calls.every(([updates]) => !Object.hasOwn(updates, 'alice'))).toBe(
true
);
});
}
it('a reorder that keeps the child after its parent keeps it following, so it moves with its parent', async () => {
const h = createHarness({ layouts: { alice: family() }, live, order: ['x', 'p', 'kid', 'y'] });
await h.service.putLegacyOrder({ owner: 'alice', isAdmin: false }, ['p', 'kid', 'x', 'y']);
expect(h.layouts.alice.groups[0].refs).toEqual([
{ kind: 'session', id: 'p' },
{ kind: 'session', id: 'kid' },
{ kind: 'session', id: 'x' },
]);
// Still following: moving only the parent takes the child along.
const current = h.layouts.alice;
const moved = await h.service.put(
'alice',
{
...current,
groups: [{ ...current.groups[0], refs: [current.groups[0].refs[1], current.groups[0].refs[2]] }],
ungrouped: [...current.ungrouped, { kind: 'session', id: 'p' }],
},
current.version
);
expect(moved.layout.ungrouped.map((ref) => ref.id)).toEqual(['y', 'p', 'kid']);
expect(moved.layout.groups[0].refs).toEqual([{ kind: 'session', id: 'x' }]);
});
it('a reorder that splits the child from its parent pins it', async () => {
const h = createHarness({ layouts: { alice: family() }, live, order: ['x', 'p', 'kid', 'y'] });
await h.service.putLegacyOrder({ owner: 'alice', isAdmin: false }, ['kid', 'x', 'p', 'y']);
expect(h.layouts.alice.groups[0].refs).toEqual([
{ kind: 'session', id: 'kid', placement: 'manual' },
{ kind: 'session', id: 'x' },
{ kind: 'session', id: 'p' },
]);
});
});