mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-21 13:39:32 +01:00
feat: per-case default session group
Case settings gains a "Default session group" selector (Ungrouped plus every named tab group of the owner). A new session of the case lands in that group in the same versioned layout write that registers it, so it is drawn in place with no Ungrouped-to-group jump. - Stored per owner and case in state.json (caseDefaultGroups), as the group's stable id or null for Ungrouped; read and written only through TabLayoutService under the owner lock. - Precedence in sessionCreated: explicit tabGroupId, then the parent placement, then the case default, else Ungrouped. A deleted or foreign id never fails a spawn and is forgotten only after the creating write lands. - POST /api/quick-start (local, linked, remote, Docker) and /api/ralph-loop/start pass their case; POST /api/sessions infers it lexically from workingDir. The create response carries tabLayout when a case default placed the session. - GET/PUT /api/cases/:name/default-group; deleting a case (or an admin deleting a user's case folder) forgets the value. - The selector mirrors desktop and phone, reverts on a refused save, and is redrawn from every adopted tab layout; zh-CN strings added.
This commit is contained in:
1 parent
39077281d1
commit
74c980413a
24 files changed
+1362
-26
No files matched your search
@@ -778,6 +778,26 @@ deleted group, another user's group) is ignored and the session lands where it
|
||||
otherwise would, never a `400`. A malformed value (`null`, an empty string, a
|
||||
non-string) is a `400 INVALID_INPUT`. Requests without the field are unchanged.
|
||||
|
||||
### A case's default session group
|
||||
|
||||
- `GET /api/v1/cases/:name/default-group` → `{ caseName, groupId, groups }`: `groupId` is a
|
||||
group id from the caller's own tab layout or `null` (Ungrouped), `groups` the caller's
|
||||
current named groups (`{ id, name }`, in layout order). A stored id whose group was
|
||||
deleted reads back as `null` and is forgotten.
|
||||
- `PUT /api/v1/cases/:name/default-group` with `{ "groupId": string | null }` saves it. An
|
||||
id not in the caller's layout is a `400 INVALID_INPUT` that leaves the old value in place.
|
||||
|
||||
Both answer `404 NOT_FOUND` for a case the caller cannot see (the same rules as
|
||||
`GET /api/v1/cases`). The value is stored per owner and case, so in multi-user mode it is
|
||||
never shared and needs no admin role. A new session of the case is placed in that group in
|
||||
its creating write when nothing stronger applies; the order is: an explicit `tabGroupId`,
|
||||
then the session it was spawned from (`parentSessionId`), then the case default, else
|
||||
Ungrouped. `POST /api/v1/quick-start` uses its `caseName` (local, linked, remote and Docker
|
||||
cases); `POST /api/v1/sessions` uses the case whose folder `workingDir` is (a direct child of
|
||||
the caller's case space, or a linked case's exact path). When a case default places the
|
||||
session, the create response carries `tabLayout` as it does for `tabGroupId`. Deleting the
|
||||
case forgets the value; existing sessions never move.
|
||||
|
||||
## Approvals Inbox
|
||||
|
||||
Cross-session queue of prompts waiting on a human (permission dialogs,
|
||||
|
||||
@@ -331,6 +331,7 @@ So: `_confirmIdle()` (session.ts) requires the pane to go quiet, and then asks t
|
||||
- **Edits are named operations, saved serially.** `createEditCoordinator` applies `createGroup` / `renameGroup` / `deleteGroup` / `reorderGroup` / `moveRef` to the rail at once, then sends ONE `PUT /api/tab-layout {baseVersion, layout}` at a time; edits made meanwhile wait and go out on the version that write returns. A 409 carries the server's layout: the in-flight operations are replayed onto it (an operation that no longer applies is dropped and reported) and re-sent, at most `maxAttempts` times; a 400 re-reads once (a second 400 is reported as a failed save, not as a race); anything else reports and re-reads. A `moveRef` moves the session together with the sessions that still follow it and marks a hand-moved child `placement: 'manual'`, mirroring the server's `moveRef`, and `normalizeLayout` keeps `placement` because whole layouts are written back. `_onTabLayoutChanged` / `_applyTabLayout` defer a read while a write is in flight and rebase unsaved edits onto a read otherwise. ⚠️ A FAILED read (`_applyTabLayout(null)`) while edits are pending keeps the held layout and the editor and re-reads after the write settles: disposing there would orphan the in-flight write, whose 409 then never gets its rebase. Any path that does drop unsaved work says so in a toast. On `pagehide`, unconfirmed operations go out in a `keepalive` PUT AND into sessionStorage as `{ owner, baseVersion, savedAt, operations }`; after reload they replay onto the fresh layout (a no-op when the keepalive landed), but only for the same owner, within `TAB_LAYOUT_PENDING_MAX_AGE_MS` (60 s), and never onto a layout older than the copy's base. A "Move to <group>" with no anchor carries no `index`, so a replay still puts the row last.
|
||||
- **Every way in has a keyboard path.** The session row menu (Shift+F10 in the tree, the rail's overflow button) gains Move up/down, Move to <group>, Move to Ungrouped and Move to new group in the vertical rail (only "new group" before the first group exists; nothing on the strip). A group header opens its menu with Shift+F10 / ContextMenu, right-click or its hover glyph (a non-focusable, `aria-hidden` span: a treeitem holds no interactive children), and F2 renames it inline (Enter commits and refocuses the header; a commit by BLUR leaves focus where it went, since refocusing from inside the blur handler overrides the user's click). The glyph stays visible under `@media (hover: none)`: a touch tablet has no hover and no long-press `contextmenu`. Group names in "Move to" labels are quoted, so a group named "New group" or "ungrouped" cannot read (or translate, case-insensitively) like the fixed entries. The menu closes on Escape (which it consumes before the global Escape handler), a pointer outside, Tab, focus leaving it, a resize, a second open and any full re-render. It borrows the `.tab-rail-action-menu` class for its look only: `closeTabRailActionMenu()` excludes `.tab-layout-group-action-menu`, so closing the row menu (every `session:deleted` does) cannot strand the group menu's listeners. The inline group editor shares `_activeRename` with the session rename, so only the CURRENT editor may release `_inlineRenameActive`.
|
||||
- **New, child and web tabs land in groups.** A group menu's "New session" (`createSessionInTabGroup`) runs ONE launch with `run({ count: 1, tabGroupId })`; every launch path puts `tabGroupId` on its create request (`POST /api/sessions` or `/api/quick-start`), and `TabLayoutService.sessionCreated(owner, id, { tabGroupId }, register)` places the session at the end of that group in the SAME versioned write that first records it. The session enters the live map inside the owner lock (`register`, rolled back if 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 rather than failing the spawn, and an explicit group is a hand placement (a child placed this way is `manual`). The create response carries the committed `tabLayout`, adopted before the tab is drawn. A session spawned by another one (`parentSessionId`) and placed by nobody lands after its parent: the server's normalization puts it after the parent's rows in the parent's container, and `project({ parents })` draws a not-yet-stored child there at once. Whether it then FOLLOWS its parent is the synced `spawnedTabsFollowParent` setting (default OFF), which `sessionCreated()` reads fresh through the `childrenFollowParent` dep: off, the child is marked `manual` in that same creating write; on, it follows until moved by hand. Deciding at creation is enough, so flipping the setting leaves existing tabs alone. A hand move makes a following child `manual`; with the setting on, the row menu notes where a child sits (following, placed by hand, parent closed, parent loop; plain text, never a focusable menu item) and offers "Follow parent again" only to a `manual` child, which clears `placement` and is re-derived by the server on save. With the setting off the row menu says nothing about placement. A legacy `PUT /api/session-order` (strip or phone drag, a same-section Ctrl+Shift+{/}, a device without a layout, an admin's cross-owner order) marks a child `manual` ONLY when the requested order splits it from its parent's block (`applyLegacySessionRank`, `childrenSplitFromParent`); a PUT of the current order, or one that moves a family together, leaves every stored placement alone. The browser never echoes a create or delete through that PUT, with or without groups: the service already re-projects the order and broadcasts it (`session:orderChanged`), and `syncSessionOrder` adopts it. A child whose parent is gone stands on its own and is never re-adopted. Saved web tabs are layout refs like sessions, but OPENNESS stays per device: a grouped web tab renders (and takes an Alt+N slot) only while it is open on this device, and reopens where the layout keeps it.
|
||||
- **A case's default session group** (`caseDefaultGroups` in state.json, keyed by the layout owner key then case name; a group id or `null` for Ungrouped) is the fallback placement for a new session of that case. It is read and written ONLY through `TabLayoutService` (`caseDefaultGroup`, `setCaseDefaultGroup`, `forgetCaseDefaultGroup`, and `sessionCreated`'s `caseName` hint), under the owner lock, never by a route or the store directly. Precedence inside `sessionCreated`'s single write: an explicit `tabGroupId` found in the owner's layout, then a parent that places the child (`hasPlacingParent`, the same conditions as `pinCreatedChild`), then the case default, else normal placement. The id is looked up in the creating owner's own layout, so a deleted or foreign id never fails a spawn; a stale id is forgotten only AFTER the creating write lands (a failed write rolls back and changes nothing). `POST /api/quick-start` and `POST /api/ralph-loop/start` pass their `caseName`; `POST /api/sessions` infers it LEXICALLY from `workingDir` (`inferLocalCaseName`: a direct child of the caller's case space, or an exact linked-case path for an admin or single-user), never for a remote attach and never touching the filesystem. Cron jobs, the one-shot run route and reboot restore keep normal placement. The Case settings selector (`onCaseDefaultGroupChanged`, session-ui.js) reads it on popover open and is redrawn from every adopted layout (`_refreshCaseDefaultGroupOptions` in `_applyTabLayout`).
|
||||
- **Only the grouped rail is a tree.** `#sessionTabs` ships as `role=tablist` with `role=tab` rows, and the header strip, sidebar and flat rail keep exactly that. While grouped, `_applyTabListRole` makes it `role=tree` (and restores `tablist` + its label when grouping ends), named-group headers are level-1 `treeitem`s that `aria-owns` their rows' `role=group` (rows sit beside the header, not inside it), and ungrouped rows plus a collapsed group's kept selection are level-1 items. A collapsed header owns nothing, a group with no open rows is a leaf (no `aria-expanded`, no owned group), and the "Ungrouped" heading is `aria-hidden`. Rows are re-roled in the DOM by `_applyTabTreeSemantics` after render, never by rewriting their markup, so a grouped row's content stays the flat row's.
|
||||
- **One tab stop in the tree.** Exactly one treeitem carries `tabindex=0` (the focused or selected item); every control inside a row drops to `-1`, which is why Shift+F10 / ContextMenu open a row's actions from the keyboard. Focus survives a full re-render by identity (`group:`/`session:`/`webview:`; a row a collapse just hid hands focus to its header), but only when focus was already inside the rail. The tree walk (`_tabTreeItems`) follows painted order WITHIN each group when the rail is sorted; the flat list keeps its own whole-list computed-order walk. `aria-posinset`/`aria-setsize` follow painted order too, so the incremental render path re-runs `_applyTabTreePositions` after it re-sorts rows in place. ⚠️ `_handleTabTreeKeydown` acts only when the key lands on the treeitem ITSELF: a key on a focused in-row control (close, overflow, the rename input) is that control's, or Enter on the overflow button re-selects the row instead of reopening its menu. ⚠️ The roving `tabindex=-1` also hides every item but the stop from the keyboard-dismiss selector's `[tabindex]` arm, which is why `MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR` lists `[role="treeitem"]` (see Dismissing the on-screen keyboard).
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ Codeman-side configuration:
|
||||
|
||||
- Which CLI the Run button should default to.
|
||||
- Per-case toggles (Agent Teams, 1M Opus context).
|
||||
- A **Default session group** (Case settings…): new sessions of the case land in that tab group of the
|
||||
vertical rail unless you start them from a group's own *New session* or they follow the session that
|
||||
spawned them. *Ungrouped* turns it off. It follows you across devices, never moves existing tabs, and a
|
||||
deleted group simply falls back to Ungrouped.
|
||||
- Where it runs, if it is not the local filesystem: see [Location overlays](#location-overlays).
|
||||
|
||||
Three ways to get one, all under **New or link a case…** at the bottom of the case picker
|
||||
|
||||
@@ -286,6 +286,9 @@ export class StateStore {
|
||||
if (this.state.tabLayouts !== undefined) {
|
||||
parts.push(`"tabLayouts":${JSON.stringify(this.state.tabLayouts)}`);
|
||||
}
|
||||
if (this.state.caseDefaultGroups !== undefined) {
|
||||
parts.push(`"caseDefaultGroups":${JSON.stringify(this.state.caseDefaultGroups)}`);
|
||||
}
|
||||
|
||||
return `{${parts.join(',')}}`;
|
||||
}
|
||||
@@ -710,6 +713,38 @@ export class StateStore {
|
||||
return { layouts: structuredClone(validated), sessionOrder: [...sessionOrder] };
|
||||
}
|
||||
|
||||
/**
|
||||
* An owner's default session group for a case: a group id, `null` for an
|
||||
* intentional Ungrouped choice, or `undefined` when unset. state.json is read
|
||||
* unvalidated, so anything but a string or null reads as unset.
|
||||
*/
|
||||
getCaseDefaultGroup(owner: string, caseName: string): string | null | undefined {
|
||||
const all = this.state.caseDefaultGroups;
|
||||
if (!all || typeof all !== 'object' || !Object.hasOwn(all, owner)) return undefined;
|
||||
const forOwner = all[owner];
|
||||
if (!forOwner || typeof forOwner !== 'object' || !Object.hasOwn(forOwner, caseName)) return undefined;
|
||||
const value = forOwner[caseName];
|
||||
return typeof value === 'string' || value === null ? value : undefined;
|
||||
}
|
||||
|
||||
/** Persist an owner's default session group for a case (`null` = Ungrouped). */
|
||||
setCaseDefaultGroup(owner: string, caseName: string, groupId: string | null): void {
|
||||
const all = this.state.caseDefaultGroups ?? {};
|
||||
const forOwner = Object.hasOwn(all, owner) ? all[owner] : {};
|
||||
this.state.caseDefaultGroups = { ...all, [owner]: { ...forOwner, [caseName]: groupId } };
|
||||
this.save();
|
||||
}
|
||||
|
||||
/** Forget an owner's default session group for a case (unset, not Ungrouped). */
|
||||
deleteCaseDefaultGroup(owner: string, caseName: string): void {
|
||||
if (this.getCaseDefaultGroup(owner, caseName) === undefined) return;
|
||||
const all = this.state.caseDefaultGroups ?? {};
|
||||
const forOwner = { ...all[owner] };
|
||||
delete forOwner[caseName];
|
||||
this.state.caseDefaultGroups = { ...all, [owner]: forOwner };
|
||||
this.save();
|
||||
}
|
||||
|
||||
/** Resets all state to initial values and saves immediately. */
|
||||
reset(): void {
|
||||
this.state = createInitialState();
|
||||
|
||||
@@ -50,6 +50,11 @@ interface TabLayoutServiceDeps {
|
||||
* from then on; on, it keeps following its parent until moved by hand.
|
||||
*/
|
||||
childrenFollowParent?(): boolean | Promise<boolean>;
|
||||
/**
|
||||
* Where per-case default session groups live (StateStore). Optional so a
|
||||
* harness without it simply never applies a case default.
|
||||
*/
|
||||
caseDefaults?: Pick<StateStore, 'getCaseDefaultGroup' | 'setCaseDefaultGroup' | 'deleteCaseDefaultGroup'>;
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
@@ -78,6 +83,17 @@ export interface RemovedTabLayoutSession {
|
||||
/** Where a newly created session asked to be placed. Advisory: an unknown group is ignored. */
|
||||
export interface SessionPlacementHint {
|
||||
tabGroupId?: string;
|
||||
/**
|
||||
* The case the session was started for. Its default session group (if any)
|
||||
* is the fallback when neither `tabGroupId` nor a parent places the session.
|
||||
*/
|
||||
caseName?: string;
|
||||
}
|
||||
|
||||
/** A case's default session group plus the owner's current named groups to choose from. */
|
||||
export interface CaseDefaultGroupView {
|
||||
groupId: string | null;
|
||||
groups: Array<{ id: string; name: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,6 +174,20 @@ function pinCreatedChild(layout: TabLayout, sessionId: string, metadata: readonl
|
||||
return moveRef(pinned, { kind: 'session', id: sessionId }, { groupId: group?.id ?? null, index: to }, metadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the just-created session have a parent that places it (right after that
|
||||
* parent)? Mirrors the conditions under which normalization and
|
||||
* {@link pinCreatedChild} treat it as a child.
|
||||
*/
|
||||
function hasPlacingParent(layout: TabLayout, sessionId: string, metadata: readonly TabRefMetadata[]): boolean {
|
||||
const item = metadata.find((fact) => fact.kind === 'session' && fact.id === sessionId);
|
||||
const parentId = item?.parentSessionId;
|
||||
if (!item?.ownerValid || !parentId) return false;
|
||||
const parentValid = metadata.some((fact) => fact.kind === 'session' && fact.id === parentId && fact.ownerValid);
|
||||
const refs = [...layout.groups.flatMap((group) => group.refs), ...layout.ungrouped];
|
||||
return parentValid && refs.some((ref) => ref.kind === 'session' && ref.id === parentId);
|
||||
}
|
||||
|
||||
/** Move a just-created session to the end of `groupId`, or leave the layout alone. */
|
||||
function placeCreatedSession(
|
||||
layout: TabLayout,
|
||||
@@ -550,17 +580,31 @@ export class TabLayoutService {
|
||||
): Promise<TabLayout> {
|
||||
return this.withOwner(owner, async () => {
|
||||
const follow = sessionId ? (await this.deps.childrenFollowParent?.()) === true : true;
|
||||
const caseName = sessionId ? placement.caseName : undefined;
|
||||
const caseDefault = caseName ? this.deps.caseDefaults?.getCaseDefaultGroup(owner, caseName) : undefined;
|
||||
let staleCaseDefault = false;
|
||||
const rollback = register?.();
|
||||
try {
|
||||
const groupId = placement.tabGroupId;
|
||||
const adjust =
|
||||
sessionId && (groupId || !follow)
|
||||
sessionId && (groupId || !follow || typeof caseDefault === 'string')
|
||||
? (layout: TabLayout, metadata: readonly TabRefMetadata[]) => {
|
||||
const placed = groupId ? placeCreatedSession(layout, sessionId, groupId, metadata) : layout;
|
||||
// Precedence: explicit group > parent placement > case default > none.
|
||||
const explicit = groupId && layout.groups.some((group) => group.id === groupId) ? groupId : undefined;
|
||||
let placed = explicit ? placeCreatedSession(layout, sessionId, explicit, metadata) : layout;
|
||||
if (!explicit && typeof caseDefault === 'string') {
|
||||
if (!layout.groups.some((group) => group.id === caseDefault)) staleCaseDefault = true;
|
||||
else if (!hasPlacingParent(layout, sessionId, metadata))
|
||||
placed = placeCreatedSession(layout, sessionId, caseDefault, metadata);
|
||||
}
|
||||
return follow ? placed : pinCreatedChild(placed, sessionId, metadata);
|
||||
}
|
||||
: undefined;
|
||||
return await this.getUnlocked(owner, adjust);
|
||||
const layout = await this.getUnlocked(owner, adjust);
|
||||
// A default whose group was deleted is ignored above and forgotten here,
|
||||
// only once the creation's own write has landed.
|
||||
if (staleCaseDefault && caseName) this.deps.caseDefaults?.deleteCaseDefaultGroup(owner, caseName);
|
||||
return layout;
|
||||
} catch (error) {
|
||||
if (typeof rollback === 'function') rollback();
|
||||
throw error;
|
||||
@@ -568,6 +612,50 @@ export class TabLayoutService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A case's default session group and the owner's named groups to choose from.
|
||||
* A stored id that is no longer one of this owner's groups is forgotten and
|
||||
* reported as `null` (Ungrouped), which is also where creation would put it.
|
||||
*/
|
||||
async caseDefaultGroup(owner: string, caseName: string): Promise<CaseDefaultGroupView> {
|
||||
return this.withOwner(owner, async () => {
|
||||
const { authoritative } = await this.prepareUnlocked(owner);
|
||||
const groups = authoritative.groups.map((group) => ({ id: group.id, name: group.name }));
|
||||
const stored = this.deps.caseDefaults?.getCaseDefaultGroup(owner, caseName);
|
||||
if (typeof stored === 'string' && !groups.some((group) => group.id === stored)) {
|
||||
this.deps.caseDefaults?.deleteCaseDefaultGroup(owner, caseName);
|
||||
return { groupId: null, groups };
|
||||
}
|
||||
return { groupId: typeof stored === 'string' ? stored : null, groups };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a case's default session group: one of this owner's current groups, or
|
||||
* `null` for Ungrouped. Only future creations read it; nothing is moved.
|
||||
* Throws {@link TabLayoutValidationError} for an id not in the owner's layout.
|
||||
*/
|
||||
async setCaseDefaultGroup(owner: string, caseName: string, groupId: string | null): Promise<CaseDefaultGroupView> {
|
||||
return this.withOwner(owner, async () => {
|
||||
const caseDefaults = this.deps.caseDefaults;
|
||||
if (!caseDefaults) throw new Error('Case default groups are not available');
|
||||
const { authoritative } = await this.prepareUnlocked(owner);
|
||||
const groups = authoritative.groups.map((group) => ({ id: group.id, name: group.name }));
|
||||
if (groupId !== null && !groups.some((group) => group.id === groupId)) {
|
||||
throw new TabLayoutValidationError('Unknown tab group');
|
||||
}
|
||||
caseDefaults.setCaseDefaultGroup(owner, caseName, groupId);
|
||||
return { groupId, groups };
|
||||
});
|
||||
}
|
||||
|
||||
/** Forget a case's default session group (the case was deleted or unlinked). */
|
||||
async forgetCaseDefaultGroup(owner: string, caseName: string): Promise<void> {
|
||||
await this.withOwner(owner, async () => {
|
||||
this.deps.caseDefaults?.deleteCaseDefaultGroup(owner, caseName);
|
||||
});
|
||||
}
|
||||
|
||||
/** Reconcile one completed saved-webview creation into one versioned mutation. */
|
||||
async webviewCreated(owner: string): Promise<TabLayout> {
|
||||
return this.get(owner);
|
||||
|
||||
@@ -121,6 +121,12 @@ export interface AppState {
|
||||
sessionOrder?: string[];
|
||||
/** Owner-scoped authoritative grouped tab layouts. */
|
||||
tabLayouts?: Record<string, TabLayout>;
|
||||
/**
|
||||
* Per-case default session group, keyed by the tab-layout owner key, then case
|
||||
* name. A group id from that owner's layout, or null for an intentional
|
||||
* Ungrouped choice. Read and written only through TabLayoutService.
|
||||
*/
|
||||
caseDefaultGroups?: Record<string, Record<string, string | null>>;
|
||||
}
|
||||
|
||||
// ========== Default Configuration ==========
|
||||
|
||||
@@ -13,7 +13,9 @@ export interface SessionPort {
|
||||
/**
|
||||
* Register a created session with the owner's tab layout. `placement.tabGroupId`
|
||||
* puts it at the end of that group in the same layout write (ignored when the
|
||||
* group is not in the owner's layout). Resolves to the committed layout.
|
||||
* group is not in the owner's layout); without one (and without a parent that
|
||||
* places it), `placement.caseName`'s default session group does the same.
|
||||
* Resolves to the committed layout.
|
||||
*/
|
||||
addSession(session: Session, placement?: SessionPlacementHint): Promise<TabLayout>;
|
||||
cleanupSession(sessionId: string, killMux?: boolean, reason?: string): Promise<void>;
|
||||
|
||||
@@ -7692,6 +7692,8 @@ class CodemanApp {
|
||||
this._tabLayoutEditor = null;
|
||||
}
|
||||
this.tabLayout = next;
|
||||
// An open Case settings popover lists the groups as its Default session group options.
|
||||
this._refreshCaseDefaultGroupOptions?.(next);
|
||||
const storage = this._getTabCollapseStorage();
|
||||
const collapsed = storage && next
|
||||
? window.CodemanTabLayout.loadCollapsedGroupIds(storage, next.groups.map((group) => group.id))
|
||||
|
||||
@@ -678,6 +678,9 @@
|
||||
'Agent Teams': '智能体团队',
|
||||
'Claude Model': 'Claude 模型',
|
||||
'1M Opus Context': 'Opus 100 万上下文',
|
||||
'Default session group': '默认会话分组',
|
||||
'New sessions for this case land in this group': '此案例的新会话将放入此分组',
|
||||
'Could not save the default session group.': '无法保存默认会话分组。',
|
||||
'Remote auto-reconnect': '远程自动重连',
|
||||
'Pin tab names on the CLI': '在 CLI 上固定标签名',
|
||||
"Launch every Claude session with its tab name, so the CLI's prompt label and /resume list match your tabs. Claude then stops generating its own titles for those sessions, and a rename in Codeman holds only until the next turn. Applies from the next session start or respawn, no server restart needed.":
|
||||
|
||||
@@ -774,6 +774,11 @@
|
||||
<span>1M Opus Context</span>
|
||||
</label>
|
||||
<span class="form-hint">Use 1M token context window for new sessions</span>
|
||||
<label class="case-default-group-label" for="caseDefaultGroup">Default session group</label>
|
||||
<select id="caseDefaultGroup" class="case-default-group-select" onchange="app.onCaseDefaultGroupChanged(this)">
|
||||
<option value="">Ungrouped</option>
|
||||
</select>
|
||||
<span class="form-hint">New sessions for this case land in this group</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Mobile-only case button + gear -->
|
||||
@@ -818,6 +823,11 @@
|
||||
<span>1M Opus Context</span>
|
||||
</label>
|
||||
<span class="form-hint">Use 1M token context window</span>
|
||||
<label class="case-default-group-label" for="caseDefaultGroupMobile">Default session group</label>
|
||||
<select id="caseDefaultGroupMobile" class="case-default-group-select" onchange="app.onCaseDefaultGroupChanged(this)">
|
||||
<option value="">Ungrouped</option>
|
||||
</select>
|
||||
<span class="form-hint">New sessions for this case land in this group</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3272,6 +3272,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('caseAgentTeams').checked = settings.agentTeams;
|
||||
document.getElementById('caseOpusContext1m').checked = settings.opusContext1m;
|
||||
popover.classList.remove('hidden');
|
||||
this._loadCaseDefaultGroup();
|
||||
|
||||
// Close on outside click (one-shot listener)
|
||||
const closeHandler = (e) => {
|
||||
@@ -3320,6 +3321,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('caseAgentTeamsMobile').checked = settings.agentTeams;
|
||||
document.getElementById('caseOpusContext1mMobile').checked = settings.opusContext1m;
|
||||
popover.classList.remove('hidden');
|
||||
this._loadCaseDefaultGroup();
|
||||
|
||||
const closeHandler = (e) => {
|
||||
if (!popover.contains(e.target) && !e.target.classList.contains('btn-case-settings-mobile')) {
|
||||
@@ -3346,6 +3348,97 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (desktopOpusCheckbox) desktopOpusCheckbox.checked = settings.opusContext1m;
|
||||
},
|
||||
|
||||
// ── Default session group (server-side, per owner + case) ──
|
||||
//
|
||||
// Unlike the two checkboxes above (this browser's localStorage), the default
|
||||
// group lives on the server, because the server places a new session in it in
|
||||
// the same layout write that registers it. The value is a group ID; '' in the
|
||||
// <select> is Ungrouped (null on the wire). Desktop and phone popovers mirror.
|
||||
|
||||
_caseDefaultGroupSelects() {
|
||||
return ['caseDefaultGroup', 'caseDefaultGroupMobile']
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter(Boolean);
|
||||
},
|
||||
|
||||
/** Rebuild both selectors from `groups`, keeping `groupId` if it still exists. */
|
||||
_renderCaseDefaultGroupSelects(groups, groupId) {
|
||||
const known = groups.some((group) => group.id === groupId);
|
||||
const value = known ? groupId : '';
|
||||
for (const select of this._caseDefaultGroupSelects()) {
|
||||
const ungrouped = document.createElement('option');
|
||||
ungrouped.value = '';
|
||||
ungrouped.textContent = 'Ungrouped';
|
||||
const options = groups.map((group) => {
|
||||
const option = document.createElement('option');
|
||||
option.value = group.id;
|
||||
option.textContent = group.name;
|
||||
option.setAttribute('data-i18n-skip', '');
|
||||
return option;
|
||||
});
|
||||
select.replaceChildren(ungrouped, ...options);
|
||||
select.value = value;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
|
||||
/** Read the selected case's default group from the server (popover open). */
|
||||
async _loadCaseDefaultGroup() {
|
||||
const caseName = document.getElementById('quickStartCase')?.value;
|
||||
const selects = this._caseDefaultGroupSelects();
|
||||
if (!caseName || selects.length === 0) return;
|
||||
for (const select of selects) select.disabled = true;
|
||||
const data = await this._apiJson(`/api/cases/${encodeURIComponent(caseName)}/default-group`);
|
||||
if (document.getElementById('quickStartCase')?.value !== caseName) return; // case switched meanwhile
|
||||
const groups = Array.isArray(data?.groups) ? data.groups : [];
|
||||
const groupId = typeof data?.groupId === 'string' ? data.groupId : null;
|
||||
this._caseDefaultGroupState = { caseName, groupId, groups };
|
||||
this._renderCaseDefaultGroupSelects(groups, groupId);
|
||||
for (const select of selects) select.disabled = !data;
|
||||
},
|
||||
|
||||
/** Save a selector change; on refusal restore the last confirmed value. */
|
||||
async onCaseDefaultGroupChanged(select) {
|
||||
const state = this._caseDefaultGroupState;
|
||||
if (!state) return;
|
||||
const groupId = select.value || null;
|
||||
const selects = this._caseDefaultGroupSelects();
|
||||
for (const other of selects) {
|
||||
other.value = select.value;
|
||||
other.disabled = true;
|
||||
}
|
||||
const res = await this._apiPut(`/api/cases/${encodeURIComponent(state.caseName)}/default-group`, { groupId });
|
||||
let saved = null;
|
||||
if (res?.ok) {
|
||||
try {
|
||||
saved = (await res.json())?.data ?? null;
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
}
|
||||
if (saved) {
|
||||
state.groupId = typeof saved.groupId === 'string' ? saved.groupId : null;
|
||||
if (Array.isArray(saved.groups)) state.groups = saved.groups;
|
||||
} else {
|
||||
this.showToast?.('Could not save the default session group.', 'error');
|
||||
}
|
||||
this._renderCaseDefaultGroupSelects(state.groups, state.groupId);
|
||||
for (const other of selects) other.disabled = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* The tab layout changed (a group was created, renamed or deleted): redraw the
|
||||
* options from it. A deleted selection shows as Ungrouped, which is where the
|
||||
* server now places new sessions (it forgets the stale ID on its next read).
|
||||
*/
|
||||
_refreshCaseDefaultGroupOptions(layout) {
|
||||
const state = this._caseDefaultGroupState;
|
||||
if (!state || !layout || !Array.isArray(layout.groups)) return;
|
||||
state.groups = layout.groups.map((group) => ({ id: group.id, name: group.name }));
|
||||
const value = this._renderCaseDefaultGroupSelects(state.groups, state.groupId);
|
||||
if (!value) state.groupId = null;
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Create Case Modal
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -6669,6 +6669,27 @@ html[data-skin="og"] .welcome-primary:hover {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Default session group selector (Case settings, desktop and phone popovers) */
|
||||
.case-default-group-label {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.case-default-group-select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
padding: 3px 6px;
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text);
|
||||
background: var(--bg-input, var(--bg-card));
|
||||
border: 1px solid var(--control-border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.case-settings-popover .form-hint {
|
||||
margin-top: 0.2rem;
|
||||
font-size: 0.6rem;
|
||||
|
||||
@@ -42,6 +42,8 @@ import { SseEvent } from '../sse-events.js';
|
||||
import type { AuthPort } from '../ports/auth-port.js';
|
||||
import type { SessionPort } from '../ports/session-port.js';
|
||||
import type { EventPort } from '../ports/event-port.js';
|
||||
import type { TabLayoutPort } from '../ports/tab-layout-port.js';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
|
||||
const CreateUserSchema = z.object({
|
||||
username: z.string().min(1).max(64),
|
||||
@@ -73,7 +75,10 @@ function storeError(reply: FastifyReply, err: unknown): ReturnType<typeof create
|
||||
return createErrorResponse(ApiErrorCode.INTERNAL_ERROR, err instanceof Error ? err.message : 'error');
|
||||
}
|
||||
|
||||
export function registerAdminRoutes(app: FastifyInstance, ctx: SessionPort & AuthPort & EventPort): void {
|
||||
export function registerAdminRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & AuthPort & EventPort & TabLayoutPort
|
||||
): void {
|
||||
// Gate: admin routes exist only in multi-user mode, and only for admins.
|
||||
const gate = (req: FastifyRequest, reply: FastifyReply): boolean => {
|
||||
if (!isMultiUserMode()) {
|
||||
@@ -299,6 +304,8 @@ export function registerAdminRoutes(app: FastifyInstance, ctx: SessionPort & Aut
|
||||
);
|
||||
}
|
||||
await fsp.rm(realTarget, { recursive: true, force: true });
|
||||
// The user's default session group for that case goes with it.
|
||||
await ctx.tabLayouts.forgetCaseDefaultGroup(ownerLayoutKey(username), params.caseName).catch(() => undefined);
|
||||
audit(req, 'user.case-delete', username, { caseName: params.caseName });
|
||||
ctx.broadcast(SseEvent.AdminUsersChanged, {});
|
||||
return { success: true, data: { username, caseName: params.caseName } };
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
ClonePreflightSchema,
|
||||
LinkCaseSchema,
|
||||
CaseOrderSchema,
|
||||
CaseDefaultGroupSchema,
|
||||
RemoteCaseLinkSchema,
|
||||
RemoteHostSchema,
|
||||
DockerCaseLinkSchema,
|
||||
@@ -51,7 +52,7 @@ import {
|
||||
import type { GitRemoteProbe, GitUrlParse } from '../../git-clone.js';
|
||||
import { generateClaudeMd } from '../../templates/claude-md.js';
|
||||
import { prepareNewCasePath } from '../case-path.js';
|
||||
import { boundedPathExists, describeUnknownPath, probePath } from '../../utils/index.js';
|
||||
import { boundedPathExists, describeUnknownPath, probePath, probePathKind } from '../../utils/index.js';
|
||||
import { readAgentCaseMarker, type AgentCaseMarker } from '../../agent-case-marker.js';
|
||||
import { settingsWriteBlocker, writeHooksConfig } from '../../hooks-config.js';
|
||||
import {
|
||||
@@ -70,7 +71,9 @@ import {
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import type { AuthUser } from '../../types.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import type { EventPort, ConfigPort, SessionPort } from '../ports/index.js';
|
||||
import type { EventPort, ConfigPort, SessionPort, TabLayoutPort } from '../ports/index.js';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
import { TabLayoutValidationError } from '../../tab-layout.js';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { dataPath, getDataDir } from '../../config/instance.js';
|
||||
import {
|
||||
@@ -246,7 +249,33 @@ async function ensureCaseImage(
|
||||
return { ok: true, imageBuilding: true };
|
||||
}
|
||||
|
||||
export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & ConfigPort & SessionPort): void {
|
||||
/**
|
||||
* Is `name` a case the caller can see (the same rules as GET /api/cases and
|
||||
* resolveCasePath): an owned remote or Docker case, a linked case (admin or
|
||||
* single-user only), or a directory in the caller's own case space. Bounded:
|
||||
* a case folder on a mount that stopped answering still counts as there, like
|
||||
* the case list keeps listing it.
|
||||
*/
|
||||
async function caseVisibleToCaller(name: string, req: FastifyRequest): Promise<boolean> {
|
||||
if (!SAFE_CASE_NAME.test(name)) return false;
|
||||
const user = getAuthUser(req);
|
||||
if ((await readRemoteCases(CODEMAN_CONFIG_DIR)).some((c) => c.name === name && canAccessOwned(user, c.owner))) {
|
||||
return true;
|
||||
}
|
||||
if ((await readDockerCases(CODEMAN_CONFIG_DIR)).some((c) => c.name === name && canAccessOwned(user, c.owner))) {
|
||||
return true;
|
||||
}
|
||||
const linkedCases = await readLinkedCases();
|
||||
if (linkedCases[name] && (!isMultiUserMode() || isAdmin(req)))
|
||||
return (await probePath(linkedCases[name])) !== 'absent';
|
||||
const kind = await probePathKind(join(resolveCasesDir(user), name));
|
||||
return kind === 'directory' || kind === 'unknown';
|
||||
}
|
||||
|
||||
export function registerCaseRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: EventPort & ConfigPort & SessionPort & TabLayoutPort
|
||||
): void {
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Case CRUD (list, create, link, detail, fix-plan)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -1584,6 +1613,19 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
app.delete('/api/cases/:name', async (req): Promise<ApiResponse<{ name: string }>> => {
|
||||
const { name } = req.params as { name: string };
|
||||
const user = getAuthUser(req);
|
||||
// The caller's default session group for this case goes with it (best-effort:
|
||||
// a stale value is ignored at creation anyway).
|
||||
// An admin deleting another user's remote/Docker case clears that owner's too.
|
||||
const forgetCaseDefault = async (caseOwner?: string): Promise<void> => {
|
||||
const owners = new Set([ownerLayoutKey(ownerFor(req)), ...(caseOwner ? [ownerLayoutKey(caseOwner)] : [])]);
|
||||
for (const owner of owners) {
|
||||
try {
|
||||
await ctx.tabLayouts.forgetCaseDefaultGroup(owner, name);
|
||||
} catch {
|
||||
/* never blocks the delete */
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (!validatePathWithinBase(name, resolveCasesDir(user))) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case name');
|
||||
@@ -1593,12 +1635,14 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
// docker case is skipped so control falls through to the caller's own local delete.
|
||||
// canAccessOwned is all-true for admins/single-user, so flag-OFF stays byte-identical.
|
||||
const remoteCases = await readRemoteCases(CODEMAN_CONFIG_DIR);
|
||||
if (remoteCases.some((item) => item.name === name && canAccessOwned(user, item.owner))) {
|
||||
const remoteCase = remoteCases.find((item) => item.name === name && canAccessOwned(user, item.owner));
|
||||
if (remoteCase) {
|
||||
await writeRemoteCases(
|
||||
CODEMAN_CONFIG_DIR,
|
||||
remoteCases.filter((item) => !(item.name === name && canAccessOwned(user, item.owner)))
|
||||
);
|
||||
ctx.broadcast(SseEvent.CaseDeleted, { name, type: 'remote-unlinked' });
|
||||
await forgetCaseDefault(remoteCase.owner);
|
||||
return { success: true, data: { name } };
|
||||
}
|
||||
|
||||
@@ -1631,6 +1675,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
.catch(() => {});
|
||||
}
|
||||
ctx.broadcast(SseEvent.CaseDeleted, { name, type: 'docker-unlinked' });
|
||||
await forgetCaseDefault(dockerCase.owner);
|
||||
return { success: true, data: { name } };
|
||||
}
|
||||
|
||||
@@ -1643,6 +1688,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
try {
|
||||
await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(linkedCases, null, 2));
|
||||
ctx.broadcast(SseEvent.CaseDeleted, { name, type: 'unlinked' });
|
||||
await forgetCaseDefault();
|
||||
return { success: true, data: { name } };
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
@@ -1658,12 +1704,48 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
try {
|
||||
await fs.rm(casePath, { recursive: true, force: true });
|
||||
ctx.broadcast(SseEvent.CaseDeleted, { name, type: 'deleted' });
|
||||
await forgetCaseDefault();
|
||||
return { success: true, data: { name } };
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Default session group ==========
|
||||
|
||||
/**
|
||||
* The tab group new sessions of this case land in when the create request names
|
||||
* no group and no parent places them. Scoped to the caller's own tab layout: the
|
||||
* options are their groups, and a stored id that is no longer one of them reads
|
||||
* as Ungrouped (null) and is forgotten. Not admin-gated in multi-user mode: the
|
||||
* value is per owner (like the layout it points into), never server-wide.
|
||||
*/
|
||||
app.get('/api/cases/:name/default-group', async (req, reply) => {
|
||||
const { name } = req.params as { name: string };
|
||||
if (!(await caseVisibleToCaller(name, req))) {
|
||||
return reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, `Case "${name}" not found`));
|
||||
}
|
||||
const view = await ctx.tabLayouts.caseDefaultGroup(ownerLayoutKey(ownerFor(req)), name);
|
||||
return { success: true, data: { caseName: name, ...view } };
|
||||
});
|
||||
|
||||
app.put('/api/cases/:name/default-group', async (req, reply) => {
|
||||
const { name } = req.params as { name: string };
|
||||
const { groupId } = parseBody(CaseDefaultGroupSchema, req.body, 'Invalid default group');
|
||||
if (!(await caseVisibleToCaller(name, req))) {
|
||||
return reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, `Case "${name}" not found`));
|
||||
}
|
||||
try {
|
||||
const view = await ctx.tabLayouts.setCaseDefaultGroup(ownerLayoutKey(ownerFor(req)), name, groupId);
|
||||
return { success: true, data: { caseName: name, ...view } };
|
||||
} catch (err) {
|
||||
if (err instanceof TabLayoutValidationError) {
|
||||
return reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'That tab group does not exist'));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Reorder Cases ==========
|
||||
|
||||
app.put('/api/cases/order', async (req, reply): Promise<ApiResponse<{ order: string[] }> | undefined> => {
|
||||
|
||||
@@ -413,8 +413,8 @@ export function registerRalphRoutes(
|
||||
const promptPath = join(casePath, '@ralph_prompt.md');
|
||||
writeFileSync(promptPath, fullPrompt, 'utf-8');
|
||||
|
||||
// Register session
|
||||
await ctx.addSession(session);
|
||||
// Register session (in its case's default session group, if one is set)
|
||||
await ctx.addSession(session, { caseName });
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
* auto-clear, auto-compact, image watcher, flicker filter, and logout.
|
||||
*/
|
||||
|
||||
import { FastifyInstance, type FastifyReply } from 'fastify';
|
||||
import { FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { join, dirname, extname, basename } from 'node:path';
|
||||
import { join, dirname, extname, basename, resolve as resolvePath } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { existsSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { execFile } from 'node:child_process';
|
||||
@@ -76,7 +76,7 @@ import {
|
||||
} from './custom-model-routes.js';
|
||||
import { matchesPattern } from '../../config/cli-registry/patterns.js';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
import { TabLayoutValidationError } from '../../tab-layout.js';
|
||||
import { TabLayoutValidationError, type TabLayout } from '../../tab-layout.js';
|
||||
import {
|
||||
sessionWaits,
|
||||
resolveWaitSignals,
|
||||
@@ -107,6 +107,7 @@ import {
|
||||
ownerFor,
|
||||
parseBody,
|
||||
persistAndBroadcastSession,
|
||||
readJsonConfig,
|
||||
resolveAgentCaseOrigin,
|
||||
resolveCasesDir,
|
||||
resolveParentSessionId,
|
||||
@@ -204,6 +205,35 @@ import { UPLOADS_DIR } from '../paste-image-gc.js';
|
||||
const LINKED_CASES_FILE = dataPath('linked-cases.json');
|
||||
const CODEMAN_CONFIG_DIR = getDataDir();
|
||||
|
||||
const SAFE_CASE_NAME = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
/** Did the committed layout put this session in a named group (not Ungrouped)? */
|
||||
function landedInGroup(layout: TabLayout | undefined, sessionId: string): boolean {
|
||||
return !!layout?.groups.some((group) => group.refs.some((ref) => ref.kind === 'session' && ref.id === sessionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* The case a POST /api/sessions `workingDir` belongs to, for its default session
|
||||
* group: a direct child of the caller's case space, or (admin / single-user, as
|
||||
* GET /api/cases lists them) a linked case's exact path. Lexical only: the
|
||||
* browser sends the path the case list gave it, and this must never touch a
|
||||
* possibly-dead mount. Anything else is no case, which keeps today's placement.
|
||||
*/
|
||||
async function inferLocalCaseName(req: FastifyRequest, workingDir: string): Promise<string | undefined> {
|
||||
const target = resolvePath(workingDir);
|
||||
const user = getAuthUser(req);
|
||||
if (dirname(target) === resolvePath(resolveCasesDir(user))) {
|
||||
const name = basename(target);
|
||||
if (SAFE_CASE_NAME.test(name)) return name;
|
||||
}
|
||||
if (isMultiUserMode() && !isAdmin(req)) return undefined;
|
||||
const linked = await readJsonConfig<Record<string, string>>(LINKED_CASES_FILE, 'linked cases', {});
|
||||
for (const [name, path] of Object.entries(linked)) {
|
||||
if (SAFE_CASE_NAME.test(name) && typeof path === 'string' && resolvePath(path) === target) return name;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Pre-compiled regex for terminal buffer cleaning (avoids per-request compilation)
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CLAUDE_BANNER_PATTERN = /\x1b\[1mClaud/;
|
||||
@@ -1412,9 +1442,13 @@ export function registerSessionRoutes(
|
||||
parentSessionId: resolveParentSessionId(ctx, req, body.parentSessionId, owner),
|
||||
});
|
||||
|
||||
const tabLayout = body.tabGroupId
|
||||
? await ctx.addSession(session, { tabGroupId: body.tabGroupId })
|
||||
: await ctx.addSession(session);
|
||||
const placementCase = remote ? undefined : await inferLocalCaseName(req, workingDir);
|
||||
const placement = {
|
||||
...(body.tabGroupId ? { tabGroupId: body.tabGroupId } : {}),
|
||||
...(placementCase ? { caseName: placementCase } : {}),
|
||||
};
|
||||
const tabLayout =
|
||||
Object.keys(placement).length > 0 ? await ctx.addSession(session, placement) : await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
@@ -1432,9 +1466,13 @@ export function registerSessionRoutes(
|
||||
// Avoids serializing 2-3MB of terminal+text buffers per session creation.
|
||||
const lightState = ctx.getSessionStateWithRespawn(session);
|
||||
ctx.broadcast(SseEvent.SessionCreated, lightState);
|
||||
// A grouped creation also returns the layout that placed it, so the browser
|
||||
// draws the tab inside its group at once instead of after a re-read.
|
||||
return { session: lightState, ...(body.tabGroupId ? { tabLayout } : {}) };
|
||||
// A grouped creation (asked for, or its case's default group) also returns the
|
||||
// layout that placed it, so the browser draws the tab inside its group at once
|
||||
// instead of after a re-read.
|
||||
return {
|
||||
session: lightState,
|
||||
...(body.tabGroupId || landedInGroup(tabLayout, session.id) ? { tabLayout } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Rename Session ==========
|
||||
@@ -4461,7 +4499,7 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
const tabLayout = tabGroupId ? await ctx.addSession(session, { tabGroupId }) : await ctx.addSession(session);
|
||||
const tabLayout = await ctx.addSession(session, { caseName, ...(tabGroupId ? { tabGroupId } : {}) });
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
@@ -4553,7 +4591,7 @@ export function registerSessionRoutes(
|
||||
caseName,
|
||||
...(worktree ? { worktree, workingDir: workspacePath } : {}),
|
||||
...(customModel ? { modelSwapInProgress: qsCustomModelSwapInProgress } : {}),
|
||||
...(tabGroupId ? { tabLayout } : {}),
|
||||
...(tabGroupId || landedInGroup(tabLayout, session.id) ? { tabLayout } : {}),
|
||||
};
|
||||
} catch (err) {
|
||||
// Clean up session on error to prevent orphaned resources
|
||||
|
||||
@@ -1978,6 +1978,15 @@ export const CaseOrderSchema = z.object({
|
||||
order: z.array(z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid case name format')),
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /api/cases/:name/default-group — the tab group new sessions of this case
|
||||
* land in: one of the caller's own group ids, or null for Ungrouped. Same bounds
|
||||
* as tabGroupIdSchema; the route checks the id against the caller's layout.
|
||||
*/
|
||||
export const CaseDefaultGroupSchema = z.object({
|
||||
groupId: z.string().min(1).max(100).nullable(),
|
||||
});
|
||||
|
||||
/** PUT /api/session-order — global tab order (ordered sessionIds), COD-131 */
|
||||
export const SessionOrderUpdateSchema = z.object({
|
||||
// Bounded defensively: ids are uuid-ish (<=100 chars) and the client pushes only
|
||||
|
||||
+3
-2
@@ -470,6 +470,7 @@ export class WebServer extends EventEmitter {
|
||||
// Fresh, not the 2s cache: the settings PUT does not invalidate it, and a
|
||||
// flip must apply to the very next spawn.
|
||||
childrenFollowParent: async () => (await this.readSettings(true)).spawnedTabsFollowParent === true,
|
||||
caseDefaults: this.store,
|
||||
});
|
||||
if (this.testMode) this.tabLayouts.markRestorationSkipped();
|
||||
|
||||
@@ -725,8 +726,8 @@ export class WebServer extends EventEmitter {
|
||||
/**
|
||||
* Add a tentative session only after its owner layout accepts the creation.
|
||||
* The session enters the live map inside the layout service's owner lock, so
|
||||
* the placement it asked for (`tabGroupId`) lands in the same versioned write
|
||||
* that first records it.
|
||||
* the placement it asked for (`tabGroupId`, else its case's default group)
|
||||
* lands in the same versioned write that first records it.
|
||||
*/
|
||||
private async registerSessionWithLayout(session: Session, placement?: SessionPlacementHint): Promise<TabLayout> {
|
||||
return this.tabLayouts.sessionCreated(ownerLayoutKey(session.owner), session.id, placement, () => {
|
||||
|
||||
@@ -189,10 +189,13 @@ describe('admin case-folder API', () => {
|
||||
expect(sl.status).toBe(400);
|
||||
await expect(fs.stat(path.join(spacesDir, 'outside'))).resolves.toBeTruthy();
|
||||
|
||||
// A real folder is deleted.
|
||||
// A real folder is deleted, and kim's default session group for it goes with it.
|
||||
const store = (server as unknown as { store: import('../src/state-store.js').StateStore }).store;
|
||||
store.setCaseDefaultGroup('kim', 'proj1', null);
|
||||
const del = await fetch(url('/api/admin/users/kim/cases/proj1'), { method: 'DELETE', headers: adminNoBody });
|
||||
expect(del.status).toBe(200);
|
||||
await expect(fs.stat(path.join(spacesDir, 'kim', 'cases', 'proj1'))).rejects.toBeTruthy();
|
||||
expect(store.getCaseDefaultGroup('kim', 'proj1')).toBeUndefined();
|
||||
|
||||
// Deleting it again 404s.
|
||||
const gone = await fetch(url('/api/admin/users/kim/cases/proj1'), { method: 'DELETE', headers: adminNoBody });
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* @fileoverview The Case settings "Default session group" selector (session-ui.js):
|
||||
* it lists Ungrouped plus every named group the server reports, saves through
|
||||
* PUT /api/cases/:name/default-group, reverts on a refused save, mirrors the
|
||||
* desktop and phone popovers, and refreshes its options when the tab layout
|
||||
* changes (groups created, renamed or deleted). Also pins the zh-CN strings.
|
||||
*
|
||||
* Port: none (vm sandbox, stubbed fetch and DOM).
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
|
||||
function fakeSelect() {
|
||||
const select: any = {
|
||||
value: '',
|
||||
disabled: false,
|
||||
options: [] as any[],
|
||||
replaceChildren(...nodes: any[]) {
|
||||
select.options = nodes;
|
||||
},
|
||||
};
|
||||
return select;
|
||||
}
|
||||
|
||||
function harness(server: { groups: Array<{ id: string; name: string }>; groupId: string | null; putStatus?: number }) {
|
||||
const elements: Record<string, any> = {
|
||||
quickStartCase: { value: 'proj' },
|
||||
caseDefaultGroup: fakeSelect(),
|
||||
caseDefaultGroupMobile: fakeSelect(),
|
||||
};
|
||||
const requests: Array<{ url: string; method: string; body?: any }> = [];
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
localStorage: { getItem: () => null, setItem: () => {} },
|
||||
document: {
|
||||
getElementById: (id: string) => elements[id] ?? null,
|
||||
createElement: () => {
|
||||
const attrs: Record<string, string> = {};
|
||||
return { value: '', textContent: '', attrs, setAttribute: (k: string, v: string) => (attrs[k] = v) };
|
||||
},
|
||||
},
|
||||
fetch: async (url: string, init?: { method?: string; body?: string }) => {
|
||||
const method = init?.method ?? 'GET';
|
||||
const body = init?.body ? JSON.parse(init.body) : undefined;
|
||||
requests.push({ url, method, body });
|
||||
const ok = method !== 'PUT' || (server.putStatus ?? 200) === 200;
|
||||
if (method === 'PUT' && ok) server.groupId = body.groupId;
|
||||
const payload = ok
|
||||
? { success: true, data: { caseName: 'proj', groupId: server.groupId, groups: server.groups } }
|
||||
: { success: false, error: 'nope', errorCode: 'INVALID_INPUT' };
|
||||
return { ok, status: ok ? 200 : (server.putStatus ?? 400), json: async () => payload };
|
||||
},
|
||||
console,
|
||||
});
|
||||
for (const file of ['api-client.js', 'session-ui.js']) {
|
||||
vm.runInContext(readFileSync(resolve(PUBLIC, file), 'utf8'), context, { filename: file });
|
||||
}
|
||||
const app = new (CodemanApp as any)();
|
||||
app.showToast = vi.fn();
|
||||
return { app, elements, requests, server };
|
||||
}
|
||||
|
||||
const optionView = (select: any) => select.options.map((o: any) => [o.value, o.textContent]);
|
||||
|
||||
describe('Case settings: Default session group selector', () => {
|
||||
it('lists Ungrouped plus every named group, selecting the stored one in both popovers', async () => {
|
||||
const h = harness({
|
||||
groups: [
|
||||
{ id: 'g1', name: 'Core' },
|
||||
{ id: 'g2', name: 'Ops' },
|
||||
],
|
||||
groupId: 'g2',
|
||||
});
|
||||
await h.app._loadCaseDefaultGroup();
|
||||
expect(h.requests[0]).toMatchObject({ url: '/api/cases/proj/default-group', method: 'GET' });
|
||||
for (const id of ['caseDefaultGroup', 'caseDefaultGroupMobile']) {
|
||||
const select = h.elements[id];
|
||||
expect(optionView(select)).toEqual([
|
||||
['', 'Ungrouped'],
|
||||
['g1', 'Core'],
|
||||
['g2', 'Ops'],
|
||||
]);
|
||||
expect(select.value).toBe('g2');
|
||||
expect(select.disabled).toBe(false);
|
||||
// Group names are user text: never handed to the translator.
|
||||
expect(select.options[1].attrs['data-i18n-skip']).toBe('');
|
||||
expect(select.options[0].attrs['data-i18n-skip']).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('saves a choice (and Ungrouped as null) and mirrors it to the other popover', async () => {
|
||||
const h = harness({ groups: [{ id: 'g1', name: 'Core' }], groupId: null });
|
||||
await h.app._loadCaseDefaultGroup();
|
||||
h.elements.caseDefaultGroup.value = 'g1';
|
||||
await h.app.onCaseDefaultGroupChanged(h.elements.caseDefaultGroup);
|
||||
expect(h.requests.at(-1)).toEqual({ url: '/api/cases/proj/default-group', method: 'PUT', body: { groupId: 'g1' } });
|
||||
expect(h.elements.caseDefaultGroupMobile.value).toBe('g1');
|
||||
|
||||
h.elements.caseDefaultGroupMobile.value = '';
|
||||
await h.app.onCaseDefaultGroupChanged(h.elements.caseDefaultGroupMobile);
|
||||
expect(h.requests.at(-1)?.body).toEqual({ groupId: null });
|
||||
expect(h.elements.caseDefaultGroup.value).toBe('');
|
||||
});
|
||||
|
||||
it('reverts to the confirmed value and says so when the save is refused', async () => {
|
||||
const h = harness({ groups: [{ id: 'g1', name: 'Core' }], groupId: 'g1', putStatus: 400 });
|
||||
await h.app._loadCaseDefaultGroup();
|
||||
h.elements.caseDefaultGroup.value = '';
|
||||
await h.app.onCaseDefaultGroupChanged(h.elements.caseDefaultGroup);
|
||||
expect(h.elements.caseDefaultGroup.value).toBe('g1');
|
||||
expect(h.app.showToast).toHaveBeenCalledWith('Could not save the default session group.', 'error');
|
||||
});
|
||||
|
||||
it('refreshes its options when the layout changes: created, renamed and deleted groups', async () => {
|
||||
const h = harness({ groups: [{ id: 'g1', name: 'Core' }], groupId: 'g1' });
|
||||
await h.app._loadCaseDefaultGroup();
|
||||
h.app._refreshCaseDefaultGroupOptions({
|
||||
groups: [
|
||||
{ id: 'g1', name: 'Core team' },
|
||||
{ id: 'g3', name: 'New' },
|
||||
],
|
||||
});
|
||||
expect(optionView(h.elements.caseDefaultGroup)).toEqual([
|
||||
['', 'Ungrouped'],
|
||||
['g1', 'Core team'],
|
||||
['g3', 'New'],
|
||||
]);
|
||||
expect(h.elements.caseDefaultGroup.value).toBe('g1');
|
||||
// The selected group is deleted: the selector visibly falls back to Ungrouped.
|
||||
h.app._refreshCaseDefaultGroupOptions({ groups: [{ id: 'g3', name: 'New' }] });
|
||||
expect(h.elements.caseDefaultGroup.value).toBe('');
|
||||
expect(h.elements.caseDefaultGroupMobile.value).toBe('');
|
||||
});
|
||||
|
||||
it('the layout refresh is wired into _applyTabLayout', () => {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
const body = app.slice(app.indexOf(' _applyTabLayout(layout) {'));
|
||||
expect(body.slice(0, body.indexOf('\n }\n'))).toMatch(/^\s*this\._refreshCaseDefaultGroupOptions\?\.\(next\);/m);
|
||||
});
|
||||
|
||||
it('both popovers carry the selector, and every new string has a zh-CN entry', () => {
|
||||
const html = readFileSync(resolve(PUBLIC, 'index.html'), 'utf8');
|
||||
expect(html).toContain('id="caseDefaultGroup"');
|
||||
expect(html).toContain('id="caseDefaultGroupMobile"');
|
||||
const i18n = readFileSync(resolve(PUBLIC, 'i18n.js'), 'utf8');
|
||||
for (const text of [
|
||||
'Default session group',
|
||||
'New sessions for this case land in this group',
|
||||
'Could not save the default session group.',
|
||||
'Ungrouped',
|
||||
]) {
|
||||
expect(i18n, text).toMatch(new RegExp(`['"]?${text.replace(/[.]/g, '\\.')}['"]?: '`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* @fileoverview Per-case default session group: the state.json store and the
|
||||
* TabLayoutService placement precedence (explicit group > parent > case default > none).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { StateStore } from '../src/state-store.js';
|
||||
import { TabLayoutService } from '../src/tab-layout-service.js';
|
||||
import { TabLayoutValidationError, type TabLayout } from '../src/tab-layout.js';
|
||||
|
||||
type SessionFact = { id: string; owner?: string; createdAt: number; parentSessionId?: string };
|
||||
|
||||
describe('StateStore case default groups', () => {
|
||||
let dir: string;
|
||||
let file: string;
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'codeman-case-default-'));
|
||||
file = join(dir, 'state.json');
|
||||
});
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
it('distinguishes unset from an intentional Ungrouped choice, per owner', () => {
|
||||
const store = new StateStore(file);
|
||||
expect(store.getCaseDefaultGroup('@single', 'app')).toBeUndefined();
|
||||
store.setCaseDefaultGroup('@single', 'app', 'g1');
|
||||
store.setCaseDefaultGroup('@single', 'other', null);
|
||||
store.setCaseDefaultGroup('bob', 'app', 'g9');
|
||||
expect(store.getCaseDefaultGroup('@single', 'app')).toBe('g1');
|
||||
expect(store.getCaseDefaultGroup('@single', 'other')).toBeNull();
|
||||
expect(store.getCaseDefaultGroup('bob', 'app')).toBe('g9');
|
||||
expect(store.getCaseDefaultGroup('alice', 'app')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('survives a save and reload (persistence round-trip)', () => {
|
||||
const store = new StateStore(file);
|
||||
store.setCaseDefaultGroup('@single', 'app', 'g1');
|
||||
store.setCaseDefaultGroup('@single', 'none', null);
|
||||
store.saveNow();
|
||||
const disk = JSON.parse(readFileSync(file, 'utf-8'));
|
||||
expect(disk.caseDefaultGroups).toEqual({ '@single': { app: 'g1', none: null } });
|
||||
const reloaded = new StateStore(file);
|
||||
expect(reloaded.getCaseDefaultGroup('@single', 'app')).toBe('g1');
|
||||
expect(reloaded.getCaseDefaultGroup('@single', 'none')).toBeNull();
|
||||
});
|
||||
|
||||
it('forgets one owner mapping without touching another owner', () => {
|
||||
const store = new StateStore(file);
|
||||
store.setCaseDefaultGroup('alice', 'app', 'g1');
|
||||
store.setCaseDefaultGroup('bob', 'app', 'g2');
|
||||
store.deleteCaseDefaultGroup('alice', 'app');
|
||||
expect(store.getCaseDefaultGroup('alice', 'app')).toBeUndefined();
|
||||
expect(store.getCaseDefaultGroup('bob', 'app')).toBe('g2');
|
||||
});
|
||||
|
||||
it('reads a malformed on-disk value as unset instead of throwing', () => {
|
||||
writeFileSync(
|
||||
file,
|
||||
JSON.stringify({ sessions: {}, caseDefaultGroups: { '@single': { app: 42, ok: 'g1' }, bad: 'x' } })
|
||||
);
|
||||
const store = new StateStore(file);
|
||||
expect(store.getCaseDefaultGroup('@single', 'app')).toBeUndefined();
|
||||
expect(store.getCaseDefaultGroup('@single', 'ok')).toBe('g1');
|
||||
expect(store.getCaseDefaultGroup('bad', 'app')).toBeUndefined();
|
||||
expect(store.getCaseDefaultGroup('@single', '__proto__')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
function createHarness(options: { layouts?: Record<string, TabLayout>; live?: SessionFact[]; follow?: boolean } = {}) {
|
||||
const layouts = { ...(options.layouts ?? {}) };
|
||||
const live = new Map((options.live ?? []).map((session) => [session.id, session]));
|
||||
const order: string[] = [];
|
||||
const defaults: Record<string, Record<string, string | null>> = {};
|
||||
const caseDefaults = {
|
||||
getCaseDefaultGroup: vi.fn((owner: string, caseName: string) =>
|
||||
defaults[owner] && caseName in defaults[owner] ? defaults[owner][caseName] : undefined
|
||||
),
|
||||
setCaseDefaultGroup: vi.fn((owner: string, caseName: string, groupId: string | null) => {
|
||||
defaults[owner] = { ...(defaults[owner] ?? {}), [caseName]: groupId };
|
||||
}),
|
||||
deleteCaseDefaultGroup: vi.fn((owner: string, caseName: string) => {
|
||||
if (defaults[owner]) delete defaults[owner][caseName];
|
||||
}),
|
||||
};
|
||||
const store = {
|
||||
getTabLayout: vi.fn((owner: string) => layouts[owner] ?? null),
|
||||
getTabLayouts: vi.fn(() => ({ ...layouts })),
|
||||
getSessions: vi.fn(() => ({})),
|
||||
getSessionOrder: vi.fn(() => [...order]),
|
||||
commitTabLayoutProjection: vi.fn(
|
||||
(updates: Readonly<Record<string, TabLayout>>, project: (latest: readonly string[]) => readonly string[]) => {
|
||||
const projected = [...project([...order])];
|
||||
Object.assign(layouts, structuredClone(updates));
|
||||
order.splice(0, order.length, ...projected);
|
||||
return { layouts: structuredClone(updates), sessionOrder: [...order] };
|
||||
}
|
||||
),
|
||||
};
|
||||
const service = new TabLayoutService({
|
||||
store: store as never,
|
||||
sessions: live as never,
|
||||
readWebviews: vi.fn(async () => []),
|
||||
broadcast: vi.fn(),
|
||||
broadcastSessionOrder: vi.fn(),
|
||||
childrenFollowParent: vi.fn(() => options.follow === true),
|
||||
caseDefaults,
|
||||
now: () => '2026-10-22T12:00:00.000Z',
|
||||
});
|
||||
const register = (fact: SessionFact) =>
|
||||
vi.fn(() => {
|
||||
live.set(fact.id, fact);
|
||||
return () => live.delete(fact.id);
|
||||
});
|
||||
return { service, store, layouts, live, defaults, caseDefaults, register };
|
||||
}
|
||||
|
||||
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-10-21T00:00:00.000Z',
|
||||
});
|
||||
const facts = (owner = 'alice'): SessionFact[] => [
|
||||
{ id: 'a', owner, createdAt: 1 },
|
||||
{ id: 'b', owner, createdAt: 2 },
|
||||
];
|
||||
const idsIn = (layout: TabLayout, groupId: string | null): string[] =>
|
||||
(groupId === null ? layout.ungrouped : (layout.groups.find((g) => g.id === groupId)?.refs ?? [])).map((r) => r.id);
|
||||
|
||||
describe('TabLayoutService case default placement', () => {
|
||||
it('places a session for the case into its default group in the creating write', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'new',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'new', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(idsIn(layout, 'g2')).toEqual(['new']);
|
||||
expect(idsIn(layout, null)).toEqual(['b']);
|
||||
expect(layout.version).toBe(8);
|
||||
// One versioned write: no transient Ungrouped layout was ever committed.
|
||||
expect(h.store.commitTabLayoutProjection).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('an explicit tabGroupId wins over the case default', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'new',
|
||||
{ caseName: 'app', tabGroupId: 'g1' },
|
||||
h.register({ id: 'new', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(idsIn(layout, 'g1')).toEqual(['a', 'new']);
|
||||
expect(idsIn(layout, 'g2')).toEqual([]);
|
||||
});
|
||||
|
||||
it('an unknown explicit group falls through to the case default', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'new',
|
||||
{ caseName: 'app', tabGroupId: 'gone' },
|
||||
h.register({ id: 'new', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(idsIn(layout, 'g2')).toEqual(['new']);
|
||||
});
|
||||
|
||||
it.each([true, false])('the parent placement wins over the case default (follow=%s)', async (follow) => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts(), follow });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'child',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'child', owner: 'alice', createdAt: 3, parentSessionId: 'a' })
|
||||
);
|
||||
expect(idsIn(layout, 'g1')).toEqual(['a', 'child']);
|
||||
expect(idsIn(layout, 'g2')).toEqual([]);
|
||||
});
|
||||
|
||||
it('a parent that is not in the layout does not block the case default', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'orphan',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'orphan', owner: 'alice', createdAt: 3, parentSessionId: 'nobody' })
|
||||
);
|
||||
expect(idsIn(layout, 'g2')).toEqual(['orphan']);
|
||||
});
|
||||
|
||||
it('an intentional Ungrouped default (null) or no default leaves the session ungrouped', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: null };
|
||||
const first = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'n1',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'n1', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(idsIn(first, null)).toEqual(['b', 'n1']);
|
||||
const second = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'n2',
|
||||
{ caseName: 'unset' },
|
||||
h.register({ id: 'n2', owner: 'alice', createdAt: 4 })
|
||||
);
|
||||
expect(idsIn(second, null)).toEqual(['b', 'n1', 'n2']);
|
||||
});
|
||||
|
||||
it('a deleted default group never fails creation: Ungrouped, and the stale value is cleared', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'deleted-group' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'new',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'new', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(idsIn(layout, null)).toEqual(['b', 'new']);
|
||||
expect(h.caseDefaults.getCaseDefaultGroup('alice', 'app')).toBeUndefined();
|
||||
});
|
||||
|
||||
it("never applies another owner's group id", async () => {
|
||||
const h = createHarness({
|
||||
layouts: { alice: grouped(), bob: { ...grouped(3), groups: [], ungrouped: [] } },
|
||||
live: [...facts()],
|
||||
});
|
||||
// A value naming alice's group, stored under bob, is not found in bob's layout.
|
||||
h.defaults.bob = { app: 'g1' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'bob',
|
||||
'bob-new',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'bob-new', owner: 'bob', createdAt: 5 })
|
||||
);
|
||||
expect(layout.groups).toEqual([]);
|
||||
expect(idsIn(layout, null)).toEqual(['bob-new']);
|
||||
expect(idsIn(h.layouts.alice, 'g1')).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('a renamed group keeps receiving sessions (the default is the stable id)', async () => {
|
||||
const renamed = grouped();
|
||||
renamed.groups[1] = { ...renamed.groups[1], name: 'Operations' };
|
||||
const h = createHarness({ layouts: { alice: renamed }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
'new',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 'new', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
expect(layout.groups[1]).toMatchObject({ id: 'g2', name: 'Operations' });
|
||||
expect(idsIn(layout, 'g2')).toEqual(['new']);
|
||||
});
|
||||
|
||||
it('changing the default never moves an existing session', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g2' };
|
||||
await h.service.sessionCreated(
|
||||
'alice',
|
||||
's1',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 's1', owner: 'alice', createdAt: 3 })
|
||||
);
|
||||
await h.service.setCaseDefaultGroup('alice', 'app', 'g1');
|
||||
const layout = await h.service.sessionCreated(
|
||||
'alice',
|
||||
's2',
|
||||
{ caseName: 'app' },
|
||||
h.register({ id: 's2', owner: 'alice', createdAt: 4 })
|
||||
);
|
||||
expect(idsIn(layout, 'g2')).toEqual(['s1']);
|
||||
expect(idsIn(layout, 'g1')).toEqual(['a', 's2']);
|
||||
});
|
||||
|
||||
it('a failed layout write rolls the registration back and writes no case default change', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'deleted-group' };
|
||||
h.store.commitTabLayoutProjection.mockImplementationOnce(() => {
|
||||
throw new Error('disk full');
|
||||
});
|
||||
const added = h.register({ id: 'new', owner: 'alice', createdAt: 3 });
|
||||
await expect(h.service.sessionCreated('alice', 'new', { caseName: 'app' }, added)).rejects.toThrow('disk full');
|
||||
expect(h.live.has('new')).toBe(false);
|
||||
expect(h.layouts.alice).toEqual(grouped());
|
||||
expect(h.caseDefaults.setCaseDefaultGroup).not.toHaveBeenCalled();
|
||||
expect(h.caseDefaults.deleteCaseDefaultGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabLayoutService case default reads and writes', () => {
|
||||
it('reports the selection with the owner group options, clearing a stale id', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
expect(await h.service.caseDefaultGroup('alice', 'app')).toEqual({
|
||||
groupId: null,
|
||||
groups: [
|
||||
{ id: 'g1', name: 'Core' },
|
||||
{ id: 'g2', name: 'Ops' },
|
||||
],
|
||||
});
|
||||
h.defaults.alice = { app: 'gone' };
|
||||
expect((await h.service.caseDefaultGroup('alice', 'app')).groupId).toBeNull();
|
||||
expect(h.caseDefaults.getCaseDefaultGroup('alice', 'app')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('saves a known group or null, and refuses an id that is not in the owner layout', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped(), bob: { ...grouped(1), groups: [] } }, live: facts() });
|
||||
await h.service.setCaseDefaultGroup('alice', 'app', 'g2');
|
||||
expect(h.defaults.alice.app).toBe('g2');
|
||||
await h.service.setCaseDefaultGroup('alice', 'app', null);
|
||||
expect(h.defaults.alice.app).toBeNull();
|
||||
await expect(h.service.setCaseDefaultGroup('bob', 'app', 'g1')).rejects.toBeInstanceOf(TabLayoutValidationError);
|
||||
expect(h.defaults.bob).toBeUndefined();
|
||||
});
|
||||
|
||||
it('forgets a mapping when its case goes away', async () => {
|
||||
const h = createHarness({ layouts: { alice: grouped() }, live: facts() });
|
||||
h.defaults.alice = { app: 'g1' };
|
||||
await h.service.forgetCaseDefaultGroup('alice', 'app');
|
||||
expect(h.caseDefaults.getCaseDefaultGroup('alice', 'app')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,12 @@ export function createMockRouteContext(options?: {
|
||||
runSessionDeletion: vi.fn(async (_removed, action) => action()),
|
||||
runStaleSessionCleanup: vi.fn(async (_activeIds, action) => action(new Set())),
|
||||
reconcileAfterRestoration: vi.fn(async () => {}),
|
||||
caseDefaultGroup: vi.fn(async () => ({ groupId: null, groups: [] })),
|
||||
setCaseDefaultGroup: vi.fn(async (_owner: string, _caseName: string, groupId: string | null) => ({
|
||||
groupId,
|
||||
groups: [],
|
||||
})),
|
||||
forgetCaseDefaultGroup: vi.fn(async () => {}),
|
||||
},
|
||||
cleanupSession: vi.fn(async () => {}),
|
||||
setupSessionListeners: vi.fn(async () => {}),
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* @fileoverview Per-case default session group over HTTP: the case routes that
|
||||
* read and write it, and the create routes that carry the case into the real
|
||||
* TabLayoutService so a new session lands in its case's group in the creating
|
||||
* write (POST /api/sessions, and POST /api/quick-start for local, remote and
|
||||
* Docker cases).
|
||||
*
|
||||
* Uses app.inject(), so no real HTTP port is needed.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-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';
|
||||
import { CASES_DIR } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { safeRmHomeTree } from '../mocks/index.js';
|
||||
|
||||
vi.mock('../../src/utils/cli-launcher.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/cli-launcher.js')>();
|
||||
return { ...actual, resolveCliLaunchError: vi.fn().mockResolvedValue(null) };
|
||||
});
|
||||
|
||||
const CASE = 'cdgcase';
|
||||
const DATA_FILES = ['docker-hosts.json', 'docker-cases.json', 'remote-hosts.json', 'remote-cases.json'];
|
||||
|
||||
interface World {
|
||||
layouts: Record<string, TabLayout>;
|
||||
order: string[];
|
||||
defaults: Record<string, Record<string, string | null>>;
|
||||
service: TabLayoutService;
|
||||
}
|
||||
|
||||
/** The real layout service over an in-memory store, wired the way server.ts wires it. */
|
||||
function attachRealLayout(harness: RouteTestHarness): World {
|
||||
const world = { layouts: {}, order: [], defaults: {} } as unknown as World;
|
||||
const caseDefaults = {
|
||||
getCaseDefaultGroup: (owner: string, name: string) =>
|
||||
world.defaults[owner] && name in world.defaults[owner] ? world.defaults[owner][name] : undefined,
|
||||
setCaseDefaultGroup: (owner: string, name: string, id: string | null) => {
|
||||
world.defaults[owner] = { ...(world.defaults[owner] ?? {}), [name]: id };
|
||||
},
|
||||
deleteCaseDefaultGroup: (owner: string, name: string) => {
|
||||
if (world.defaults[owner]) delete world.defaults[owner][name];
|
||||
},
|
||||
};
|
||||
world.service = new TabLayoutService({
|
||||
store: {
|
||||
getTabLayout: (owner: string) => world.layouts[owner] ?? null,
|
||||
getTabLayouts: () => ({ ...world.layouts }),
|
||||
getSessions: () => ({}),
|
||||
getSessionOrder: () => [...world.order],
|
||||
commitTabLayoutProjection: (
|
||||
updates: Readonly<Record<string, TabLayout>>,
|
||||
project: (latest: readonly string[]) => readonly string[]
|
||||
) => {
|
||||
world.order = [...project(world.order)];
|
||||
Object.assign(world.layouts, structuredClone(updates));
|
||||
return { layouts: structuredClone(updates), sessionOrder: [...world.order] };
|
||||
},
|
||||
} as never,
|
||||
sessions: harness.ctx.sessions as never,
|
||||
readWebviews: async () => [],
|
||||
broadcast: () => {},
|
||||
broadcastSessionOrder: () => {},
|
||||
caseDefaults,
|
||||
});
|
||||
world.service.markRestorationSkipped();
|
||||
(harness.ctx as unknown as { tabLayouts: TabLayoutService }).tabLayouts = world.service;
|
||||
harness.ctx.addSession.mockImplementation((session: Session, placement?: object) =>
|
||||
world.service.sessionCreated(ownerLayoutKey(session.owner), session.id, placement, () => {
|
||||
harness.ctx.sessions.set(session.id, session as never);
|
||||
return () => harness.ctx.sessions.delete(session.id);
|
||||
})
|
||||
);
|
||||
return world;
|
||||
}
|
||||
|
||||
const OWNER = ownerLayoutKey(undefined);
|
||||
const withGroups = (world: World) => {
|
||||
world.layouts[OWNER] = {
|
||||
version: 3,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [
|
||||
{ id: 'g-core', name: 'Core', refs: [] },
|
||||
{ id: 'g-ops', name: 'Ops', refs: [] },
|
||||
],
|
||||
ungrouped: [],
|
||||
};
|
||||
};
|
||||
const groupOf = (layout: TabLayout, sessionId: string): string | null =>
|
||||
layout.groups.find((g) => g.refs.some((r) => r.id === sessionId))?.id ?? null;
|
||||
const unwrap = (raw: string) => {
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed.data ?? parsed;
|
||||
};
|
||||
|
||||
describe('case default group: create routes', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let world: World;
|
||||
const caseDir = join(CASES_DIR, CASE);
|
||||
const outside = join(homedir(), 'cdg-not-a-case');
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
await mkdir(caseDir, { recursive: true });
|
||||
await mkdir(outside, { recursive: true });
|
||||
vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
|
||||
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
|
||||
harness = await createRouteTestHarness(registerSessionRoutes);
|
||||
harness.ctx.sessions.clear();
|
||||
world = attachRealLayout(harness);
|
||||
withGroups(world);
|
||||
world.defaults[OWNER] = { [CASE]: 'g-ops' };
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
safeRmHomeTree(outside);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('POST /api/sessions in a case folder lands in the case default group and returns that layout', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-cdg', mode: 'shell', workingDir: caseDir },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBe('g-ops');
|
||||
// The response carries the committed layout so the browser draws the tab in place.
|
||||
expect(data.tabLayout).toEqual(world.layouts[OWNER]);
|
||||
});
|
||||
|
||||
it('POST /api/sessions outside any case gets no case default and keeps its response shape', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-out', mode: 'shell', workingDir: outside },
|
||||
});
|
||||
const data = unwrap(res.body);
|
||||
expect(Object.keys(data)).toEqual(['session']);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('POST /api/sessions: an explicit tabGroupId still wins', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-cdg', mode: 'shell', workingDir: caseDir, tabGroupId: 'g-core' },
|
||||
});
|
||||
expect(groupOf(world.layouts[OWNER], unwrap(res.body).session.id)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a local case lands in the case default group', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-ops');
|
||||
expect(data.tabLayout).toEqual(world.layouts[OWNER]);
|
||||
});
|
||||
|
||||
it('POST /api/quick-start: explicit tabGroupId wins over the case default', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell', tabGroupId: 'g-core' },
|
||||
});
|
||||
expect(groupOf(world.layouts[OWNER], unwrap(res.body).sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a remote case lands in the case default group', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-hosts.json'),
|
||||
JSON.stringify([{ id: 'remote1', label: 'Remote', host: '10.0.0.5', username: 'dev' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgremote', type: 'remote', hostId: 'remote1', remotePath: '/home/dev/work' }])
|
||||
);
|
||||
world.defaults[OWNER].cdgremote = 'g-core';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: 'cdgremote', mode: 'claude' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(data.sessionId, res.body).toBeTruthy();
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a Docker case lands in the case default group', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-hosts.json'),
|
||||
JSON.stringify([{ id: 'docker1', label: 'Docker', image: 'codeman/agent:base' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-cases.json'),
|
||||
JSON.stringify([
|
||||
{ name: 'cdgdocker', type: 'docker', hostId: 'docker1', hostWorkspacePath: caseDir, container: 'codeman-cdg' },
|
||||
])
|
||||
);
|
||||
world.defaults[OWNER].cdgdocker = 'g-core';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: 'cdgdocker', mode: 'claude' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(data.sessionId, res.body).toBeTruthy();
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('a deleted default group never fails creation: the session lands ungrouped and the value is cleared', async () => {
|
||||
world.defaults[OWNER][CASE] = 'g-deleted';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBeNull();
|
||||
expect(data.tabLayout).toBeUndefined();
|
||||
expect(CASE in world.defaults[OWNER]).toBe(false);
|
||||
});
|
||||
|
||||
it('a creation that fails after registration leaves no layout reference', async () => {
|
||||
vi.mocked(Session.prototype.startShell).mockRejectedValueOnce(new Error('pane failed'));
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(unwrap(res.body).sessionId).toBeUndefined();
|
||||
// The route's own error path ran cleanupSession for the registered id.
|
||||
expect(harness.ctx.cleanupSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('case default group: GET/PUT /api/cases/:name/default-group', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let world: World;
|
||||
const caseDir = join(CASES_DIR, CASE);
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
await mkdir(caseDir, { recursive: true });
|
||||
harness = await createRouteTestHarness(registerCaseRoutes);
|
||||
world = attachRealLayout(harness);
|
||||
withGroups(world);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const get = (name = CASE) => harness.app.inject({ method: 'GET', url: `/api/cases/${name}/default-group` });
|
||||
const put = (groupId: unknown, name = CASE) =>
|
||||
harness.app.inject({ method: 'PUT', url: `/api/cases/${name}/default-group`, payload: { groupId } });
|
||||
|
||||
it('lists Ungrouped (null) and every named group of the owner', async () => {
|
||||
const res = await get();
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({
|
||||
success: true,
|
||||
data: {
|
||||
caseName: CASE,
|
||||
groupId: null,
|
||||
groups: [
|
||||
{ id: 'g-core', name: 'Core' },
|
||||
{ id: 'g-ops', name: 'Ops' },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('saves a group and reads it back; null is an intentional Ungrouped', async () => {
|
||||
expect((await put('g-ops')).json().data.groupId).toBe('g-ops');
|
||||
expect(world.defaults[OWNER][CASE]).toBe('g-ops');
|
||||
expect((await get()).json().data.groupId).toBe('g-ops');
|
||||
expect((await put(null)).json().data.groupId).toBeNull();
|
||||
expect(world.defaults[OWNER][CASE]).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the current group names, so a rename shows through (the id is stored)', async () => {
|
||||
await put('g-ops');
|
||||
world.layouts[OWNER].groups[1].name = 'Operations';
|
||||
const data = (await get()).json().data;
|
||||
expect(data.groupId).toBe('g-ops');
|
||||
expect(data.groups[1]).toEqual({ id: 'g-ops', name: 'Operations' });
|
||||
});
|
||||
|
||||
it('a deleted group reads back as Ungrouped and is cleared', async () => {
|
||||
world.defaults[OWNER] = { [CASE]: 'g-gone' };
|
||||
expect((await get()).json().data.groupId).toBeNull();
|
||||
expect(CASE in world.defaults[OWNER]).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unknown group', 'g-nope', 400],
|
||||
['an empty string', '', 400],
|
||||
['a number', 7, 400],
|
||||
])('refuses %s without changing the stored value', async (_label, groupId, status) => {
|
||||
await put('g-core');
|
||||
const res = await put(groupId);
|
||||
expect(res.statusCode).toBe(status);
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(world.defaults[OWNER][CASE]).toBe('g-core');
|
||||
});
|
||||
|
||||
it('404s a case that does not exist (or is not the caller’s), for both verbs', async () => {
|
||||
expect((await get('nosuchcase')).statusCode).toBe(404);
|
||||
expect((await put('g-core', 'nosuchcase')).statusCode).toBe(404);
|
||||
expect(world.defaults[OWNER]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts a remote case and a Docker case by name', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-hosts.json'),
|
||||
JSON.stringify([{ id: 'remote1', label: 'Remote', host: '10.0.0.5', username: 'dev' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgremote', type: 'remote', hostId: 'remote1', remotePath: '/home/dev/work' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgdocker', type: 'docker', hostId: 'docker1', hostWorkspacePath: caseDir }])
|
||||
);
|
||||
expect((await put('g-core', 'cdgremote')).statusCode).toBe(200);
|
||||
expect((await put('g-ops', 'cdgdocker')).statusCode).toBe(200);
|
||||
expect(world.defaults[OWNER]).toMatchObject({ cdgremote: 'g-core', cdgdocker: 'g-ops' });
|
||||
});
|
||||
|
||||
it('DELETE /api/cases/:name forgets the mapping', async () => {
|
||||
await put('g-ops');
|
||||
const res = await harness.app.inject({ method: 'DELETE', url: `/api/cases/${CASE}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(CASE in world.defaults[OWNER]).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('case default group: multi-user scoping', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("stores a non-admin's choice under their own owner key and validates against their own groups", async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const harness = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
try {
|
||||
harness.ctx.sessions.clear();
|
||||
const world = attachRealLayout(harness);
|
||||
world.layouts.alice = {
|
||||
version: 1,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [{ id: 'g-alice', name: 'Alice', refs: [] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
world.layouts.bob = {
|
||||
version: 1,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [{ id: 'g-bob', name: 'Bob', refs: [] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
const { resolveCasesDir } = await import('../../src/web/route-helpers.js');
|
||||
const bobCases = resolveCasesDir({ username: 'bob', role: 'user' } as never);
|
||||
await mkdir(join(bobCases, 'bobcase'), { recursive: true });
|
||||
|
||||
const read = await harness.app.inject({ method: 'GET', url: '/api/cases/bobcase/default-group' });
|
||||
expect(read.json().data.groups).toEqual([{ id: 'g-bob', name: 'Bob' }]);
|
||||
const foreign = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/cases/bobcase/default-group',
|
||||
payload: { groupId: 'g-alice' },
|
||||
});
|
||||
expect(foreign.statusCode).toBe(400);
|
||||
const own = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/cases/bobcase/default-group',
|
||||
payload: { groupId: 'g-bob' },
|
||||
});
|
||||
expect(own.statusCode).toBe(200);
|
||||
expect(world.defaults).toEqual({ bob: { bobcase: 'g-bob' } });
|
||||
safeRmHomeTree(join(bobCases, '..'));
|
||||
} finally {
|
||||
await harness.app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -104,7 +104,9 @@ describe('create routes: tabGroupId', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = body(res.body);
|
||||
expect(ctx.addSession.mock.calls[0][1]).toEqual({ tabGroupId: 'g1' });
|
||||
// quick-start always names its case too, for the case's default group (the
|
||||
// explicit group still wins inside TabLayoutService).
|
||||
expect(ctx.addSession.mock.calls[0][1]).toEqual({ caseName: 'tabgroupcase', tabGroupId: 'g1' });
|
||||
expect(data.tabLayout.groups[0].refs).toEqual([{ kind: 'session', id: data.sessionId }]);
|
||||
|
||||
const plain = await app.inject({
|
||||
|
||||
Reference in new issue
Block a user