@causyne/agent 1.20.79 → 1.20.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cliMode.js +26 -1
- package/src/commands.js +10 -8
- package/src/tui/completion.js +35 -7
- package/src/tui/prompt.js +27 -18
- package/src/tui/sessionPicker.js +5 -10
- package/src/tui/sessionPicker.ts +6 -10
- package/src/tui/sessionPickerView.js +215 -0
- package/src/tui/sessionPickerView.ts +249 -0
- package/src/tui/workspaceSwitch.js +52 -0
- package/src/tui/workspaceSwitch.ts +79 -0
package/package.json
CHANGED
package/src/cliMode.js
CHANGED
|
@@ -4,6 +4,7 @@ import { getProcessEntitlementGate } from './licensing/entitlements.js';
|
|
|
4
4
|
import { loadConfig, saveConfig } from './config.js';
|
|
5
5
|
import readline from 'readline';
|
|
6
6
|
import { ChatPrompt, isInteractive } from './tui/prompt.js';
|
|
7
|
+
import { switchChatWorkspace } from './tui/workspaceSwitch.js';
|
|
7
8
|
import { handleInput, listCommands, isCommandInput } from './commands.js';
|
|
8
9
|
import { CodeStreamRenderer as ChatRenderer } from './tui/codeStreamRenderer.js';
|
|
9
10
|
import { paint, bold, dim, badge, GLYPHS, terminalWidth } from './tui/theme.js';
|
|
@@ -304,7 +305,7 @@ export async function chatMode({ home = false } = {}) {
|
|
|
304
305
|
// .agents/rules.json.
|
|
305
306
|
const conn = new LocalCLIConnection();
|
|
306
307
|
const taskId = `cli_chat_${Date.now()}`;
|
|
307
|
-
|
|
308
|
+
let loop = new AgentLoop(conn, taskId, null);
|
|
308
309
|
|
|
309
310
|
// The context the CLI never showed: which model is about to spend the user's
|
|
310
311
|
// money, in which autonomy mode, over which paths. All of it was already
|
|
@@ -458,7 +459,31 @@ export async function chatMode({ home = false } = {}) {
|
|
|
458
459
|
// A leading slash is a command, not a task. handleInput returns null for
|
|
459
460
|
// anything else, which is what sends the line to the agent — so a prompt
|
|
460
461
|
// that merely mentions a path like /usr/local is still a task.
|
|
462
|
+
const previousWorkspaceRoot = loop.workspaceRoot;
|
|
461
463
|
const commandResult = await handleInput(task, { surface: 'terminal', loop, prompt });
|
|
464
|
+
if (commandResult?.effect === 'workspace-changed') {
|
|
465
|
+
try {
|
|
466
|
+
// Fresh sandbox AND memory: an old AgentLoop cannot be repointed by
|
|
467
|
+
// changing process.cwd() or assigning only loop.workspaceContext.
|
|
468
|
+
const nextRoot = commandResult.workspaceRoot;
|
|
469
|
+
loop = switchChatWorkspace({
|
|
470
|
+
workspaceRoot: nextRoot,
|
|
471
|
+
createLoop: (workspaceRoot) => new AgentLoop(
|
|
472
|
+
conn, `cli_chat_${Date.now()}`, null, { workspaceRoot }
|
|
473
|
+
),
|
|
474
|
+
prompt, surface, renderer: conn.renderer, headerInfo,
|
|
475
|
+
approvalHandler: makeApprovalHandler(conn, prompt),
|
|
476
|
+
decisionHandler: makeDecisionHandler(conn, prompt)
|
|
477
|
+
});
|
|
478
|
+
conn.renderer.write(`\n Workspace switched to: ${nextRoot}\n`);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
// Roll back process cwd and prompt state if creation/rebinding fails.
|
|
481
|
+
try { process.chdir(previousWorkspaceRoot); } catch { /* report below */ }
|
|
482
|
+
try { prompt?.setWorkingRoot(previousWorkspaceRoot); } catch { /* report below */ }
|
|
483
|
+
conn.renderer.write(`\n Workspace switch failed: ${error.message}\n`);
|
|
484
|
+
}
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
462
487
|
if (commandResult) {
|
|
463
488
|
// Route command output through the renderer, not console.log.
|
|
464
489
|
//
|
package/src/commands.js
CHANGED
|
@@ -154,20 +154,22 @@ export const COMMANDS = [
|
|
|
154
154
|
if (!stat.isDirectory()) {
|
|
155
155
|
return fail(`Not a directory: ${resolved}`);
|
|
156
156
|
}
|
|
157
|
+
// Do not mutate the existing AgentLoop: its workspaceRoot, Sandbox,
|
|
158
|
+
// MemoryManager and loaded session belong to the previous workspace.
|
|
159
|
+
// The chat controller rebuilds the loop after this explicit command.
|
|
160
|
+
let canonicalRoot;
|
|
157
161
|
try {
|
|
158
|
-
|
|
162
|
+
canonicalRoot = fs.realpathSync(resolved);
|
|
163
|
+
process.chdir(canonicalRoot);
|
|
159
164
|
} catch (err) {
|
|
160
165
|
return fail(`Cannot switch to ${resolved}: ${err.message}`);
|
|
161
166
|
}
|
|
162
167
|
if (ctx.prompt && typeof ctx.prompt.setWorkingRoot === 'function') {
|
|
163
|
-
ctx.prompt.setWorkingRoot(
|
|
168
|
+
ctx.prompt.setWorkingRoot(canonicalRoot);
|
|
164
169
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
} catch (e) {}
|
|
169
|
-
}
|
|
170
|
-
return ok(`Working directory changed to: ${resolved}`);
|
|
170
|
+
return ok(`Working directory changed to: ${canonicalRoot}`, {
|
|
171
|
+
effect: 'workspace-changed', workspaceRoot: canonicalRoot
|
|
172
|
+
});
|
|
171
173
|
}
|
|
172
174
|
},
|
|
173
175
|
|
package/src/tui/completion.js
CHANGED
|
@@ -269,9 +269,10 @@ export class FileIndex {
|
|
|
269
269
|
async walk() {
|
|
270
270
|
const found = [];
|
|
271
271
|
const queue = [{ dir: this.root, depth: 0 }];
|
|
272
|
+
let next = 0;
|
|
272
273
|
|
|
273
|
-
while (queue.length
|
|
274
|
-
const { dir, depth } = queue
|
|
274
|
+
while (next < queue.length && found.length < MAX_INDEX_ENTRIES) {
|
|
275
|
+
const { dir, depth } = queue[next++];
|
|
275
276
|
let listing;
|
|
276
277
|
try {
|
|
277
278
|
listing = await fsp.readdir(dir, { withFileTypes: true });
|
|
@@ -305,6 +306,23 @@ export class FileIndex {
|
|
|
305
306
|
}
|
|
306
307
|
}
|
|
307
308
|
|
|
309
|
+
/**
|
|
310
|
+
* Resolve both the authorized root and candidate to physical paths before
|
|
311
|
+
* touching a directory. Lexical path.resolve() alone follows symlinks outside
|
|
312
|
+
* the workspace and can leak private filenames through @ completion.
|
|
313
|
+
*/
|
|
314
|
+
function isPhysicalChild(root, candidate) {
|
|
315
|
+
try {
|
|
316
|
+
const base = fs.realpathSync(root);
|
|
317
|
+
const target = fs.realpathSync(candidate);
|
|
318
|
+
const relative = path.relative(base, target);
|
|
319
|
+
return relative === '' || (relative !== '..' &&
|
|
320
|
+
!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
321
|
+
} catch {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
308
326
|
/** Instant, shell-style completion of one directory level. */
|
|
309
327
|
function directoryItems(root, partial) {
|
|
310
328
|
const slash = partial.lastIndexOf('/');
|
|
@@ -313,7 +331,8 @@ function directoryItems(root, partial) {
|
|
|
313
331
|
|
|
314
332
|
// Never offer paths outside the workspace root, whatever the user typed.
|
|
315
333
|
const relativeToRoot = path.relative(root, target);
|
|
316
|
-
if (relativeToRoot
|
|
334
|
+
if (relativeToRoot === '..' || relativeToRoot.startsWith(`..${path.sep}`) ||
|
|
335
|
+
path.isAbsolute(relativeToRoot) || !isPhysicalChild(root, target)) return [];
|
|
317
336
|
|
|
318
337
|
let listing;
|
|
319
338
|
try {
|
|
@@ -325,14 +344,23 @@ function directoryItems(root, partial) {
|
|
|
325
344
|
const items = [];
|
|
326
345
|
for (const entry of listing) {
|
|
327
346
|
if (entry.name.startsWith('.')) continue;
|
|
328
|
-
|
|
329
|
-
|
|
347
|
+
const candidate = path.join(target, entry.name);
|
|
348
|
+
// A lexical entry can be a symlink to a private directory. Do not offer
|
|
349
|
+
// any symlink whose physical target leaves the active workspace.
|
|
350
|
+
if (entry.isSymbolicLink() && !isPhysicalChild(root, candidate)) continue;
|
|
351
|
+
let isDirectory = entry.isDirectory();
|
|
352
|
+
if (entry.isSymbolicLink()) {
|
|
353
|
+
try { isDirectory = fs.statSync(candidate).isDirectory(); }
|
|
354
|
+
catch { continue; }
|
|
355
|
+
}
|
|
356
|
+
if (isDirectory && SKIP_DIRECTORIES.has(entry.name)) continue;
|
|
357
|
+
const value = dirPart + entry.name + (isDirectory ? '/' : '');
|
|
330
358
|
if (!isTerminalSafe(value)) continue;
|
|
331
359
|
items.push({
|
|
332
360
|
value,
|
|
333
361
|
match: value,
|
|
334
362
|
label: value,
|
|
335
|
-
description:
|
|
363
|
+
description: isDirectory ? 'directory' : ''
|
|
336
364
|
});
|
|
337
365
|
}
|
|
338
366
|
return items;
|
|
@@ -449,7 +477,7 @@ export function suggest(text, cursor, options = {}) {
|
|
|
449
477
|
if (focusDir) {
|
|
450
478
|
const focusTarget = path.resolve(root, focusDir);
|
|
451
479
|
try {
|
|
452
|
-
if (
|
|
480
|
+
if (isPhysicalChild(root, focusTarget) && fs.statSync(focusTarget).isDirectory()) {
|
|
453
481
|
const focusedItems = directoryItems(focusTarget, trigger.query).map((item) => ({
|
|
454
482
|
...item,
|
|
455
483
|
value: `${focusDir}/${item.value}`,
|
package/src/tui/prompt.js
CHANGED
|
@@ -785,15 +785,13 @@ export class ChatPrompt {
|
|
|
785
785
|
// Control commands take priority over busy turns so the user is never locked out.
|
|
786
786
|
// Commands like /stop, /new, /model, /session, /sessions, /continuum, /clear can interrupt
|
|
787
787
|
// a stalled/long-running turn and execute immediately.
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
text === '/clear'
|
|
796
|
-
);
|
|
788
|
+
// Match a COMPLETE command token. Prefix tests made unrelated
|
|
789
|
+
// commands such as /newsletter interrupt an active agent turn.
|
|
790
|
+
const commandToken = text.trim().split(/\s+/, 1)[0].toLowerCase();
|
|
791
|
+
const isControlCommand = this.isCommand(text) && new Set([
|
|
792
|
+
'/stop', '/interrupt', '/new', '/model', '/models',
|
|
793
|
+
'/session', '/sessions', '/continuum', '/clear'
|
|
794
|
+
]).has(commandToken);
|
|
797
795
|
|
|
798
796
|
// Immediate abort signals interrupt the running turn directly without queuing as a future task.
|
|
799
797
|
if ((text === '/stop' || text === '/interrupt') && this.busy) {
|
|
@@ -1265,10 +1263,12 @@ export class ChatPrompt {
|
|
|
1265
1263
|
}
|
|
1266
1264
|
|
|
1267
1265
|
cursorOffset() {
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1266
|
+
// The editor stores Unicode code points; String.slice() in the completion
|
|
1267
|
+
// provider expects UTF-16 code units. Count units at this API boundary.
|
|
1268
|
+
const before = this.editor.lines.slice(0, this.editor.line)
|
|
1269
|
+
.reduce((total, line) => total + line.join('').length + 1, 0);
|
|
1270
|
+
return before + this.editor.lines[this.editor.line]
|
|
1271
|
+
.slice(0, this.editor.col).join('').length;
|
|
1272
1272
|
}
|
|
1273
1273
|
|
|
1274
1274
|
openCompletion(force = false) {
|
|
@@ -1465,15 +1465,24 @@ export class ChatPrompt {
|
|
|
1465
1465
|
}
|
|
1466
1466
|
|
|
1467
1467
|
setCursorOffset(offset) {
|
|
1468
|
-
|
|
1468
|
+
// Convert completion's UTF-16 offset back into the editor's code-point
|
|
1469
|
+
// column, never splitting a surrogate pair or moving to the wrong row.
|
|
1470
|
+
let remaining = Math.max(0, Number.isFinite(offset) ? offset : 0);
|
|
1469
1471
|
for (let index = 0; index < this.editor.lines.length; index++) {
|
|
1470
|
-
const
|
|
1471
|
-
|
|
1472
|
+
const line = this.editor.lines[index];
|
|
1473
|
+
const units = line.join('').length;
|
|
1474
|
+
if (remaining <= units || index === this.editor.lines.length - 1) {
|
|
1475
|
+
let column = 0;
|
|
1476
|
+
let consumed = 0;
|
|
1477
|
+
while (column < line.length && consumed + line[column].length <= remaining) {
|
|
1478
|
+
consumed += line[column].length;
|
|
1479
|
+
column++;
|
|
1480
|
+
}
|
|
1472
1481
|
this.editor.line = index;
|
|
1473
|
-
this.editor.col =
|
|
1482
|
+
this.editor.col = column;
|
|
1474
1483
|
return;
|
|
1475
1484
|
}
|
|
1476
|
-
remaining -=
|
|
1485
|
+
remaining -= units + 1;
|
|
1477
1486
|
}
|
|
1478
1487
|
}
|
|
1479
1488
|
|
package/src/tui/sessionPicker.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
// Sovereign Interactive Session Picker — modal dialog for listing, switching, and creating sessions.
|
|
2
2
|
// Authored in Strict TypeScript for Causyne Agent.
|
|
3
3
|
// Source-available under BUSL-1.1.
|
|
4
|
-
|
|
5
|
-
import { SelectLayer } from './dialogs.js';
|
|
4
|
+
import { SessionPickerLayer } from './sessionPickerView.js';
|
|
6
5
|
// @ts-expect-error untyped local TUI theme
|
|
7
6
|
import { GLYPHS } from './theme.js';
|
|
8
7
|
import { listSessions, getActiveSessionId, switchSession, createSession, forkSession } from '../sessionJournal.js';
|
|
@@ -106,6 +105,7 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
|
|
|
106
105
|
title: s.title,
|
|
107
106
|
workspace: s.workspace,
|
|
108
107
|
messageCount: s.messageCount,
|
|
108
|
+
updatedAt: s.updatedAt,
|
|
109
109
|
isCurrent
|
|
110
110
|
}
|
|
111
111
|
});
|
|
@@ -121,7 +121,6 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
|
|
|
121
121
|
const sessions = listSessions();
|
|
122
122
|
const activeId = getActiveSessionId();
|
|
123
123
|
const items = buildSessionPickerItems(sessions, activeId, workspace);
|
|
124
|
-
const conversationCount = items.filter(item => item.value.type === 'switch').length;
|
|
125
124
|
const cleanPrompt = () => {
|
|
126
125
|
if (prompt.editor && typeof prompt.editor.clear === 'function') {
|
|
127
126
|
prompt.editor.clear();
|
|
@@ -130,14 +129,10 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
|
|
|
130
129
|
}
|
|
131
130
|
};
|
|
132
131
|
const picked = await new Promise((resolve) => {
|
|
133
|
-
const layer = new
|
|
134
|
-
title: `Sessions (${conversationCount})`,
|
|
135
|
-
placeholder: 'search sessions by title, id, or workspace...',
|
|
136
|
-
emptyText: 'no matching sessions found',
|
|
137
|
-
width: 78,
|
|
138
|
-
height: 20,
|
|
139
|
-
footer: `enter select session ${GLYPHS.dot} esc cancel`,
|
|
132
|
+
const layer = new SessionPickerLayer({
|
|
140
133
|
items,
|
|
134
|
+
activeId,
|
|
135
|
+
currentWorkspace: workspace,
|
|
141
136
|
onPick: (item) => {
|
|
142
137
|
resolve(item || null);
|
|
143
138
|
}
|
package/src/tui/sessionPicker.ts
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
// Authored in Strict TypeScript for Causyne Agent.
|
|
3
3
|
// Source-available under BUSL-1.1.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
import { SelectLayer } from './dialogs.js';
|
|
5
|
+
import { SessionPickerLayer } from './sessionPickerView.js';
|
|
7
6
|
// @ts-expect-error untyped local TUI theme
|
|
8
7
|
import { GLYPHS } from './theme.js';
|
|
9
8
|
import {
|
|
@@ -22,6 +21,7 @@ export interface SessionPickerItemValue {
|
|
|
22
21
|
title?: string | undefined;
|
|
23
22
|
workspace?: string | undefined;
|
|
24
23
|
messageCount?: number | undefined;
|
|
24
|
+
updatedAt?: number | undefined;
|
|
25
25
|
isCurrent?: boolean | undefined;
|
|
26
26
|
}
|
|
27
27
|
|
|
@@ -157,6 +157,7 @@ export function buildSessionPickerItems(
|
|
|
157
157
|
title: s.title,
|
|
158
158
|
workspace: s.workspace,
|
|
159
159
|
messageCount: s.messageCount,
|
|
160
|
+
updatedAt: s.updatedAt,
|
|
160
161
|
isCurrent
|
|
161
162
|
}
|
|
162
163
|
});
|
|
@@ -184,7 +185,6 @@ export async function runInteractiveSessionPicker(
|
|
|
184
185
|
const activeId = getActiveSessionId();
|
|
185
186
|
|
|
186
187
|
const items = buildSessionPickerItems(sessions, activeId, workspace);
|
|
187
|
-
const conversationCount = items.filter(item => item.value.type === 'switch').length;
|
|
188
188
|
|
|
189
189
|
const cleanPrompt = () => {
|
|
190
190
|
if (prompt.editor && typeof prompt.editor.clear === 'function') {
|
|
@@ -194,14 +194,10 @@ export async function runInteractiveSessionPicker(
|
|
|
194
194
|
};
|
|
195
195
|
|
|
196
196
|
const picked = await new Promise<SessionPickerItem | null>((resolve) => {
|
|
197
|
-
const layer = new
|
|
198
|
-
title: `Sessions (${conversationCount})`,
|
|
199
|
-
placeholder: 'search sessions by title, id, or workspace...',
|
|
200
|
-
emptyText: 'no matching sessions found',
|
|
201
|
-
width: 78,
|
|
202
|
-
height: 20,
|
|
203
|
-
footer: `enter select session ${GLYPHS.dot} esc cancel`,
|
|
197
|
+
const layer = new SessionPickerLayer({
|
|
204
198
|
items,
|
|
199
|
+
activeId,
|
|
200
|
+
currentWorkspace: workspace,
|
|
205
201
|
onPick: (item: SessionPickerItem | null) => {
|
|
206
202
|
resolve(item || null);
|
|
207
203
|
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent /sessions: session-specific presentation on the existing modal stack.
|
|
3
|
+
* No changes to the session store, approval policy or the shared SelectList.
|
|
4
|
+
*/
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
// @ts-expect-error The existing dialog component is authored in JavaScript.
|
|
7
|
+
import { SelectLayer } from './dialogs.js';
|
|
8
|
+
// @ts-expect-error The theme is authored in JavaScript.
|
|
9
|
+
import { bold, dim, paint, GLYPHS } from './theme.js';
|
|
10
|
+
import { safeDisplay, truncate, visibleWidth } from './text.js';
|
|
11
|
+
const INNER_HEADER_ROWS = 3; // scope, search, divider
|
|
12
|
+
const INNER_DETAIL_ROWS = 3; // divider, selected title, metadata
|
|
13
|
+
const MAX_PANEL_HEIGHT = 28;
|
|
14
|
+
function clean(value) {
|
|
15
|
+
return safeDisplay(typeof value === 'string' ? value : String(value ?? ''));
|
|
16
|
+
}
|
|
17
|
+
function sameWorkspace(first, second) {
|
|
18
|
+
if (!first || !second)
|
|
19
|
+
return false;
|
|
20
|
+
const a = path.resolve(first);
|
|
21
|
+
const b = path.resolve(second);
|
|
22
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
23
|
+
}
|
|
24
|
+
function rowPair(left, right, width) {
|
|
25
|
+
const room = Math.max(0, Math.floor(width));
|
|
26
|
+
const rightWidth = visibleWidth(right);
|
|
27
|
+
if (rightWidth >= room - 5)
|
|
28
|
+
return truncate(left, room, '…');
|
|
29
|
+
const safeLeft = truncate(left, Math.max(0, room - rightWidth - 2), '…');
|
|
30
|
+
return safeLeft + ' '.repeat(Math.max(1, room - visibleWidth(safeLeft) - rightWidth)) + right;
|
|
31
|
+
}
|
|
32
|
+
function itemTitle(item) {
|
|
33
|
+
if (item.value.type === 'new')
|
|
34
|
+
return 'New session';
|
|
35
|
+
if (item.value.type === 'fork')
|
|
36
|
+
return 'Fork current session';
|
|
37
|
+
return clean(item.value.title || item.label).replace(/\s*\[active\]\s*$/, '');
|
|
38
|
+
}
|
|
39
|
+
function shortTime(item) {
|
|
40
|
+
const timestamp = item.value.updatedAt;
|
|
41
|
+
if (!Number.isFinite(timestamp))
|
|
42
|
+
return '';
|
|
43
|
+
const minutes = Math.max(0, Math.floor((Date.now() - Number(timestamp)) / 60000));
|
|
44
|
+
if (minutes < 1)
|
|
45
|
+
return 'now';
|
|
46
|
+
if (minutes < 60)
|
|
47
|
+
return `${minutes}m`;
|
|
48
|
+
if (minutes < 1440)
|
|
49
|
+
return `${Math.floor(minutes / 60)}h`;
|
|
50
|
+
return `${Math.floor(minutes / 1440)}d`;
|
|
51
|
+
}
|
|
52
|
+
function actionOrSessionText(item, selected, width) {
|
|
53
|
+
const isAction = item.value.type !== 'switch';
|
|
54
|
+
const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
|
|
55
|
+
const leftPrefix = ` ${marker} `;
|
|
56
|
+
const rawName = itemTitle(item);
|
|
57
|
+
const right = isAction
|
|
58
|
+
? dim(item.value.type === 'new' ? 'create' : 'branch')
|
|
59
|
+
: dim(`${item.value.messageCount ?? 0} msgs ${GLYPHS.dot} ${shortTime(item)}${item.value.isCurrent ? ' ACTIVE' : ''}`);
|
|
60
|
+
const available = Math.max(1, width - visibleWidth(leftPrefix) - 1);
|
|
61
|
+
// Keep titles legible on small terminals instead of allowing metadata to eat them.
|
|
62
|
+
const showMeta = available >= 42;
|
|
63
|
+
const usableRight = showMeta ? right : '';
|
|
64
|
+
const titleBudget = Math.max(1, available - (showMeta ? visibleWidth(usableRight) + 2 : 0));
|
|
65
|
+
const name = truncate(rawName, titleBudget, '…');
|
|
66
|
+
const styledName = selected ? bold(paint('ink', name)) : paint('ink', name);
|
|
67
|
+
return rowPair(leftPrefix + styledName, usableRight, width);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Category headers are terminal rows, not selectable items. This window is
|
|
71
|
+
* measured in *actual rows*, preventing selection disappearing at group edges.
|
|
72
|
+
*/
|
|
73
|
+
export function renderSessionRows(entries, start, selected, width, budget) {
|
|
74
|
+
const rows = [];
|
|
75
|
+
let lastIndex = start - 1;
|
|
76
|
+
let previousCategory = null;
|
|
77
|
+
for (let i = start; i < entries.length && rows.length < budget; i++) {
|
|
78
|
+
const item = entries[i].item;
|
|
79
|
+
const category = clean(item.category || 'Sessions');
|
|
80
|
+
const isNewGroup = category !== previousCategory;
|
|
81
|
+
// Avoid leaving an orphaned header in the final available row.
|
|
82
|
+
if (isNewGroup && budget - rows.length >= 2) {
|
|
83
|
+
rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, width - 4), '…')}`));
|
|
84
|
+
}
|
|
85
|
+
else if (isNewGroup && rows.length > 0) {
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
if (rows.length >= budget)
|
|
89
|
+
break;
|
|
90
|
+
rows.push(actionOrSessionText(item, i === selected, width));
|
|
91
|
+
lastIndex = i;
|
|
92
|
+
previousCategory = category;
|
|
93
|
+
}
|
|
94
|
+
return { rows, lastIndex };
|
|
95
|
+
}
|
|
96
|
+
export class SessionPickerLayer extends SelectLayer {
|
|
97
|
+
currentWorkspace;
|
|
98
|
+
activeId;
|
|
99
|
+
allItems;
|
|
100
|
+
scope = 'all';
|
|
101
|
+
constructor(options) {
|
|
102
|
+
super({
|
|
103
|
+
title: `Sessions ${options.items.filter(i => i.value.type === 'switch').length}`,
|
|
104
|
+
width: 100,
|
|
105
|
+
height: MAX_PANEL_HEIGHT,
|
|
106
|
+
items: options.items,
|
|
107
|
+
placeholder: 'Search sessions by title, ID or workspace',
|
|
108
|
+
emptyText: 'No matching sessions',
|
|
109
|
+
footer: `↑↓ navigate ${GLYPHS.dot} enter open ${GLYPHS.dot} tab workspace ${GLYPHS.dot} esc close`,
|
|
110
|
+
onPick: options.onPick
|
|
111
|
+
});
|
|
112
|
+
this.allItems = options.items;
|
|
113
|
+
this.currentWorkspace = options.currentWorkspace;
|
|
114
|
+
this.activeId = options.activeId;
|
|
115
|
+
}
|
|
116
|
+
preferredHeight() {
|
|
117
|
+
// Modals with a few sessions do not retain a large blank area.
|
|
118
|
+
const distinctGroups = new Set(this.list.filtered.map((entry) => entry.item.category));
|
|
119
|
+
const content = this.list.filtered.length + distinctGroups.size;
|
|
120
|
+
return Math.min(MAX_PANEL_HEIGHT, Math.max(12, content + INNER_HEADER_ROWS + INNER_DETAIL_ROWS + 2));
|
|
121
|
+
}
|
|
122
|
+
countSessions() {
|
|
123
|
+
return this.list.filtered.filter((entry) => entry.item.value.type === 'switch').length;
|
|
124
|
+
}
|
|
125
|
+
toggleWorkspace() {
|
|
126
|
+
const oldId = this.list.current?.id;
|
|
127
|
+
this.scope = this.scope === 'all' ? 'workspace' : 'all';
|
|
128
|
+
const scoped = this.scope === 'all'
|
|
129
|
+
? this.allItems
|
|
130
|
+
: this.allItems.filter(item => item.value.type !== 'switch' ||
|
|
131
|
+
sameWorkspace(item.value.workspace, this.currentWorkspace));
|
|
132
|
+
this.list.setItems(scoped);
|
|
133
|
+
const next = this.list.filtered.findIndex((entry) => entry.item.id === oldId);
|
|
134
|
+
const firstSession = this.list.filtered.findIndex((entry) => entry.item.value.type === 'switch');
|
|
135
|
+
this.list.selected = next >= 0 ? next : Math.max(0, firstSession);
|
|
136
|
+
this.list.offset = 0;
|
|
137
|
+
}
|
|
138
|
+
key(event) {
|
|
139
|
+
if (event?.name === 'tab') {
|
|
140
|
+
this.toggleWorkspace();
|
|
141
|
+
return 'handled';
|
|
142
|
+
}
|
|
143
|
+
const previousQuery = this.list.query;
|
|
144
|
+
const result = super.key(event);
|
|
145
|
+
if (this.list.query !== previousQuery) {
|
|
146
|
+
this.list.selected = 0;
|
|
147
|
+
this.list.offset = 0;
|
|
148
|
+
}
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
body(width, height) {
|
|
152
|
+
const w = Math.max(12, Math.floor(width));
|
|
153
|
+
const h = Math.max(1, Math.floor(height));
|
|
154
|
+
const rows = [];
|
|
155
|
+
const scopeLabel = this.scope === 'all' ? 'ALL WORKSPACES' : 'THIS WORKSPACE';
|
|
156
|
+
const total = this.allItems.filter(item => item.value.type === 'switch').length;
|
|
157
|
+
const count = this.countSessions();
|
|
158
|
+
rows.push(rowPair(` ${paint('accent', scopeLabel)}`, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
|
|
159
|
+
const query = String(this.list.query || '');
|
|
160
|
+
const lead = ` ${paint('accent', GLYPHS.arrow)} `;
|
|
161
|
+
const maxInput = Math.max(1, w - visibleWidth(lead) - 1);
|
|
162
|
+
let visibleQuery = query;
|
|
163
|
+
// Show the tail of long queries so the edit caret stays near the typing point.
|
|
164
|
+
while (visibleWidth(visibleQuery) > maxInput)
|
|
165
|
+
visibleQuery = visibleQuery.slice(1);
|
|
166
|
+
const shown = query ? clean(visibleQuery) : dim('Search by title, workspace or ID…');
|
|
167
|
+
rows.push(lead + truncate(shown, maxInput, '…'));
|
|
168
|
+
this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + (query ? visibleWidth(visibleQuery) : 0)), y: 1 };
|
|
169
|
+
rows.push(paint('rule', '─'.repeat(w)));
|
|
170
|
+
const available = Math.max(0, h - INNER_HEADER_ROWS - INNER_DETAIL_ROWS);
|
|
171
|
+
const entries = this.list.filtered;
|
|
172
|
+
if (available > 0) {
|
|
173
|
+
if (!entries.length) {
|
|
174
|
+
rows.push('');
|
|
175
|
+
if (rows.length < h - INNER_DETAIL_ROWS)
|
|
176
|
+
rows.push(dim(' No sessions match this search.'));
|
|
177
|
+
if (rows.length < h - INNER_DETAIL_ROWS)
|
|
178
|
+
rows.push(dim(' Try another title, ID, or workspace.'));
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const selected = Math.max(0, Math.min(this.list.selected, entries.length - 1));
|
|
182
|
+
let start = Math.max(0, Math.min(this.list.offset, selected));
|
|
183
|
+
let output = renderSessionRows(entries, start, selected, w, available);
|
|
184
|
+
while (output.lastIndex < selected && start < selected) {
|
|
185
|
+
start++;
|
|
186
|
+
output = renderSessionRows(entries, start, selected, w, available);
|
|
187
|
+
}
|
|
188
|
+
this.list.offset = start;
|
|
189
|
+
this.list.lastItemRows = available;
|
|
190
|
+
rows.push(...output.rows);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
while (rows.length < Math.max(0, h - INNER_DETAIL_ROWS))
|
|
194
|
+
rows.push('');
|
|
195
|
+
if (h >= INNER_DETAIL_ROWS) {
|
|
196
|
+
rows.push(paint('rule', '─'.repeat(w)));
|
|
197
|
+
const chosen = this.list.current;
|
|
198
|
+
if (chosen) {
|
|
199
|
+
const title = itemTitle(chosen);
|
|
200
|
+
const state = chosen.value.isCurrent ? paint('accent', 'ACTIVE') : dim('SELECTED');
|
|
201
|
+
rows.push(rowPair(` ${truncate(title, Math.max(1, w - 19), '…')}`, state, w));
|
|
202
|
+
const description = chosen.value.type === 'switch'
|
|
203
|
+
? chosen.description
|
|
204
|
+
: chosen.value.type === 'new' ? 'Start with an empty conversation in this workspace'
|
|
205
|
+
: 'Duplicate conversation history; authorization is reset';
|
|
206
|
+
rows.push(dim(` ${truncate(clean(description), Math.max(1, w - 3), '…')}`));
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
rows.push(dim(' No session selected'));
|
|
210
|
+
rows.push('');
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return rows.slice(0, h).map(line => truncate(line, w, '…'));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent /sessions: session-specific presentation on the existing modal stack.
|
|
3
|
+
* No changes to the session store, approval policy or the shared SelectList.
|
|
4
|
+
*/
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
// @ts-expect-error The existing dialog component is authored in JavaScript.
|
|
7
|
+
import { SelectLayer } from './dialogs.js';
|
|
8
|
+
// @ts-expect-error The theme is authored in JavaScript.
|
|
9
|
+
import { bold, dim, paint, GLYPHS } from './theme.js';
|
|
10
|
+
import { safeDisplay, truncate, visibleWidth } from './text.js';
|
|
11
|
+
import type { SessionPickerItem } from './sessionPicker.js';
|
|
12
|
+
|
|
13
|
+
export interface SessionPickerViewOptions {
|
|
14
|
+
items: SessionPickerItem[];
|
|
15
|
+
currentWorkspace: string;
|
|
16
|
+
activeId: string | null;
|
|
17
|
+
onPick: (item: SessionPickerItem | null) => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type SessionScope = 'all' | 'workspace';
|
|
21
|
+
type Key = { name?: string; ctrl?: boolean; sequence?: string; text?: string } | null;
|
|
22
|
+
|
|
23
|
+
const INNER_HEADER_ROWS = 3; // scope, search, divider
|
|
24
|
+
const INNER_DETAIL_ROWS = 3; // divider, selected title, metadata
|
|
25
|
+
const MAX_PANEL_HEIGHT = 28;
|
|
26
|
+
|
|
27
|
+
function clean(value: unknown): string {
|
|
28
|
+
return safeDisplay(typeof value === 'string' ? value : String(value ?? ''));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sameWorkspace(first: string | undefined, second: string): boolean {
|
|
32
|
+
if (!first || !second) return false;
|
|
33
|
+
const a = path.resolve(first);
|
|
34
|
+
const b = path.resolve(second);
|
|
35
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function rowPair(left: string, right: string, width: number): string {
|
|
39
|
+
const room = Math.max(0, Math.floor(width));
|
|
40
|
+
const rightWidth = visibleWidth(right);
|
|
41
|
+
if (rightWidth >= room - 5) return truncate(left, room, '…');
|
|
42
|
+
const safeLeft = truncate(left, Math.max(0, room - rightWidth - 2), '…');
|
|
43
|
+
return safeLeft + ' '.repeat(Math.max(1, room - visibleWidth(safeLeft) - rightWidth)) + right;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function itemTitle(item: SessionPickerItem): string {
|
|
47
|
+
if (item.value.type === 'new') return 'New session';
|
|
48
|
+
if (item.value.type === 'fork') return 'Fork current session';
|
|
49
|
+
return clean(item.value.title || item.label).replace(/\s*\[active\]\s*$/, '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function shortTime(item: SessionPickerItem): string {
|
|
53
|
+
const timestamp = item.value.updatedAt;
|
|
54
|
+
if (!Number.isFinite(timestamp)) return '';
|
|
55
|
+
const minutes = Math.max(0, Math.floor((Date.now() - Number(timestamp)) / 60000));
|
|
56
|
+
if (minutes < 1) return 'now';
|
|
57
|
+
if (minutes < 60) return `${minutes}m`;
|
|
58
|
+
if (minutes < 1440) return `${Math.floor(minutes / 60)}h`;
|
|
59
|
+
return `${Math.floor(minutes / 1440)}d`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function actionOrSessionText(item: SessionPickerItem, selected: boolean, width: number): string {
|
|
63
|
+
const isAction = item.value.type !== 'switch';
|
|
64
|
+
const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
|
|
65
|
+
const leftPrefix = ` ${marker} `;
|
|
66
|
+
const rawName = itemTitle(item);
|
|
67
|
+
const right = isAction
|
|
68
|
+
? dim(item.value.type === 'new' ? 'create' : 'branch')
|
|
69
|
+
: dim(`${item.value.messageCount ?? 0} msgs ${GLYPHS.dot} ${shortTime(item)}${item.value.isCurrent ? ' ACTIVE' : ''}`);
|
|
70
|
+
const available = Math.max(1, width - visibleWidth(leftPrefix) - 1);
|
|
71
|
+
// Keep titles legible on small terminals instead of allowing metadata to eat them.
|
|
72
|
+
const showMeta = available >= 42;
|
|
73
|
+
const usableRight = showMeta ? right : '';
|
|
74
|
+
const titleBudget = Math.max(1, available - (showMeta ? visibleWidth(usableRight) + 2 : 0));
|
|
75
|
+
const name = truncate(rawName, titleBudget, '…');
|
|
76
|
+
const styledName = selected ? bold(paint('ink', name)) : paint('ink', name);
|
|
77
|
+
return rowPair(leftPrefix + styledName, usableRight, width);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface ListWindow { rows: string[]; lastIndex: number; }
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Category headers are terminal rows, not selectable items. This window is
|
|
84
|
+
* measured in *actual rows*, preventing selection disappearing at group edges.
|
|
85
|
+
*/
|
|
86
|
+
export function renderSessionRows(
|
|
87
|
+
entries: Array<{ item: SessionPickerItem }>,
|
|
88
|
+
start: number,
|
|
89
|
+
selected: number,
|
|
90
|
+
width: number,
|
|
91
|
+
budget: number
|
|
92
|
+
): ListWindow {
|
|
93
|
+
const rows: string[] = [];
|
|
94
|
+
let lastIndex = start - 1;
|
|
95
|
+
let previousCategory: string | null = null;
|
|
96
|
+
for (let i = start; i < entries.length && rows.length < budget; i++) {
|
|
97
|
+
const item = entries[i]!.item;
|
|
98
|
+
const category = clean(item.category || 'Sessions');
|
|
99
|
+
const isNewGroup = category !== previousCategory;
|
|
100
|
+
// Avoid leaving an orphaned header in the final available row.
|
|
101
|
+
if (isNewGroup && budget - rows.length >= 2) {
|
|
102
|
+
rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, width - 4), '…')}`));
|
|
103
|
+
} else if (isNewGroup && rows.length > 0) {
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
if (rows.length >= budget) break;
|
|
107
|
+
rows.push(actionOrSessionText(item, i === selected, width));
|
|
108
|
+
lastIndex = i;
|
|
109
|
+
previousCategory = category;
|
|
110
|
+
}
|
|
111
|
+
return { rows, lastIndex };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export class SessionPickerLayer extends SelectLayer {
|
|
115
|
+
// SelectLayer is currently an untyped JavaScript class in the repository.
|
|
116
|
+
// Declare the inherited API used here without introducing runtime fields.
|
|
117
|
+
declare list: {
|
|
118
|
+
all: SessionPickerItem[];
|
|
119
|
+
filtered: Array<{ item: SessionPickerItem }>;
|
|
120
|
+
selected: number;
|
|
121
|
+
offset: number;
|
|
122
|
+
query: string;
|
|
123
|
+
current: SessionPickerItem | null;
|
|
124
|
+
lastItemRows?: number;
|
|
125
|
+
setItems(items: SessionPickerItem[]): void;
|
|
126
|
+
moveTo(index: number, visibleRows: number): void;
|
|
127
|
+
};
|
|
128
|
+
declare cursor: { x: number; y: number } | null;
|
|
129
|
+
readonly currentWorkspace: string;
|
|
130
|
+
readonly activeId: string | null;
|
|
131
|
+
readonly allItems: SessionPickerItem[];
|
|
132
|
+
scope: SessionScope = 'all';
|
|
133
|
+
|
|
134
|
+
constructor(options: SessionPickerViewOptions) {
|
|
135
|
+
super({
|
|
136
|
+
title: `Sessions ${options.items.filter(i => i.value.type === 'switch').length}`,
|
|
137
|
+
width: 100,
|
|
138
|
+
height: MAX_PANEL_HEIGHT,
|
|
139
|
+
items: options.items,
|
|
140
|
+
placeholder: 'Search sessions by title, ID or workspace',
|
|
141
|
+
emptyText: 'No matching sessions',
|
|
142
|
+
footer: `↑↓ navigate ${GLYPHS.dot} enter open ${GLYPHS.dot} tab workspace ${GLYPHS.dot} esc close`,
|
|
143
|
+
onPick: options.onPick
|
|
144
|
+
});
|
|
145
|
+
this.allItems = options.items;
|
|
146
|
+
this.currentWorkspace = options.currentWorkspace;
|
|
147
|
+
this.activeId = options.activeId;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
preferredHeight(): number {
|
|
151
|
+
// Modals with a few sessions do not retain a large blank area.
|
|
152
|
+
const distinctGroups = new Set(this.list.filtered.map((entry: { item: SessionPickerItem }) => entry.item.category));
|
|
153
|
+
const content = this.list.filtered.length + distinctGroups.size;
|
|
154
|
+
return Math.min(MAX_PANEL_HEIGHT, Math.max(12, content + INNER_HEADER_ROWS + INNER_DETAIL_ROWS + 2));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private countSessions(): number {
|
|
158
|
+
return this.list.filtered.filter((entry: { item: SessionPickerItem }) => entry.item.value.type === 'switch').length;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private toggleWorkspace(): void {
|
|
162
|
+
const oldId = (this.list.current as SessionPickerItem | null)?.id;
|
|
163
|
+
this.scope = this.scope === 'all' ? 'workspace' : 'all';
|
|
164
|
+
const scoped = this.scope === 'all'
|
|
165
|
+
? this.allItems
|
|
166
|
+
: this.allItems.filter(item => item.value.type !== 'switch' ||
|
|
167
|
+
sameWorkspace(item.value.workspace, this.currentWorkspace));
|
|
168
|
+
this.list.setItems(scoped);
|
|
169
|
+
const next = this.list.filtered.findIndex((entry: { item: SessionPickerItem }) => entry.item.id === oldId);
|
|
170
|
+
const firstSession = this.list.filtered.findIndex((entry: { item: SessionPickerItem }) => entry.item.value.type === 'switch');
|
|
171
|
+
this.list.selected = next >= 0 ? next : Math.max(0, firstSession);
|
|
172
|
+
this.list.offset = 0;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
key(event: Key): string | null {
|
|
176
|
+
if (event?.name === 'tab') {
|
|
177
|
+
this.toggleWorkspace();
|
|
178
|
+
return 'handled';
|
|
179
|
+
}
|
|
180
|
+
const previousQuery = this.list.query;
|
|
181
|
+
const result = super.key(event);
|
|
182
|
+
if (this.list.query !== previousQuery) {
|
|
183
|
+
this.list.selected = 0;
|
|
184
|
+
this.list.offset = 0;
|
|
185
|
+
}
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
body(width: number, height: number): string[] {
|
|
190
|
+
const w = Math.max(12, Math.floor(width));
|
|
191
|
+
const h = Math.max(1, Math.floor(height));
|
|
192
|
+
const rows: string[] = [];
|
|
193
|
+
const scopeLabel = this.scope === 'all' ? 'ALL WORKSPACES' : 'THIS WORKSPACE';
|
|
194
|
+
const total = this.allItems.filter(item => item.value.type === 'switch').length;
|
|
195
|
+
const count = this.countSessions();
|
|
196
|
+
|
|
197
|
+
rows.push(rowPair(` ${paint('accent', scopeLabel)}`, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
|
|
198
|
+
const query = String(this.list.query || '');
|
|
199
|
+
const lead = ` ${paint('accent', GLYPHS.arrow)} `;
|
|
200
|
+
const maxInput = Math.max(1, w - visibleWidth(lead) - 1);
|
|
201
|
+
let visibleQuery = query;
|
|
202
|
+
// Show the tail of long queries so the edit caret stays near the typing point.
|
|
203
|
+
while (visibleWidth(visibleQuery) > maxInput) visibleQuery = visibleQuery.slice(1);
|
|
204
|
+
const shown = query ? clean(visibleQuery) : dim('Search by title, workspace or ID…');
|
|
205
|
+
rows.push(lead + truncate(shown, maxInput, '…'));
|
|
206
|
+
this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + (query ? visibleWidth(visibleQuery) : 0)), y: 1 };
|
|
207
|
+
rows.push(paint('rule', '─'.repeat(w)));
|
|
208
|
+
|
|
209
|
+
const available = Math.max(0, h - INNER_HEADER_ROWS - INNER_DETAIL_ROWS);
|
|
210
|
+
const entries = this.list.filtered as Array<{ item: SessionPickerItem }>;
|
|
211
|
+
if (available > 0) {
|
|
212
|
+
if (!entries.length) {
|
|
213
|
+
rows.push('');
|
|
214
|
+
if (rows.length < h - INNER_DETAIL_ROWS) rows.push(dim(' No sessions match this search.'));
|
|
215
|
+
if (rows.length < h - INNER_DETAIL_ROWS) rows.push(dim(' Try another title, ID, or workspace.'));
|
|
216
|
+
} else {
|
|
217
|
+
const selected = Math.max(0, Math.min(this.list.selected, entries.length - 1));
|
|
218
|
+
let start = Math.max(0, Math.min(this.list.offset, selected));
|
|
219
|
+
let output = renderSessionRows(entries, start, selected, w, available);
|
|
220
|
+
while (output.lastIndex < selected && start < selected) {
|
|
221
|
+
start++;
|
|
222
|
+
output = renderSessionRows(entries, start, selected, w, available);
|
|
223
|
+
}
|
|
224
|
+
this.list.offset = start;
|
|
225
|
+
this.list.lastItemRows = available;
|
|
226
|
+
rows.push(...output.rows);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
while (rows.length < Math.max(0, h - INNER_DETAIL_ROWS)) rows.push('');
|
|
230
|
+
if (h >= INNER_DETAIL_ROWS) {
|
|
231
|
+
rows.push(paint('rule', '─'.repeat(w)));
|
|
232
|
+
const chosen = this.list.current as SessionPickerItem | null;
|
|
233
|
+
if (chosen) {
|
|
234
|
+
const title = itemTitle(chosen);
|
|
235
|
+
const state = chosen.value.isCurrent ? paint('accent', 'ACTIVE') : dim('SELECTED');
|
|
236
|
+
rows.push(rowPair(` ${truncate(title, Math.max(1, w - 19), '…')}`, state, w));
|
|
237
|
+
const description = chosen.value.type === 'switch'
|
|
238
|
+
? chosen.description
|
|
239
|
+
: chosen.value.type === 'new' ? 'Start with an empty conversation in this workspace'
|
|
240
|
+
: 'Duplicate conversation history; authorization is reset';
|
|
241
|
+
rows.push(dim(` ${truncate(clean(description), Math.max(1, w - 3), '…')}`));
|
|
242
|
+
} else {
|
|
243
|
+
rows.push(dim(' No session selected'));
|
|
244
|
+
rows.push('');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return rows.slice(0, h).map(line => truncate(line, w, '…'));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebind a chat session to a different workspace without mutating the previous
|
|
3
|
+
* agent's sandbox or mixing old workspace memory into the new session.
|
|
4
|
+
*
|
|
5
|
+
* This module owns no disk changes or CLI command parsing. createLoop() is the
|
|
6
|
+
* existing AgentLoop constructor, injected by cliMode for deterministic tests.
|
|
7
|
+
*/
|
|
8
|
+
export function switchChatWorkspace({ workspaceRoot, createLoop, prompt = null, surface = null, renderer = null, headerInfo = null, approvalHandler, decisionHandler }) {
|
|
9
|
+
if (typeof workspaceRoot !== 'string' || !workspaceRoot) {
|
|
10
|
+
throw new TypeError('A nonempty workspace root is required');
|
|
11
|
+
}
|
|
12
|
+
if (typeof createLoop !== 'function') {
|
|
13
|
+
throw new TypeError('createLoop must construct a new AgentLoop');
|
|
14
|
+
}
|
|
15
|
+
// Build the replacement before updating any displayed state. If construction
|
|
16
|
+
// fails, the previous loop and prompt remain intact for caller rollback.
|
|
17
|
+
const replacement = createLoop(workspaceRoot);
|
|
18
|
+
if (!replacement || replacement.workspaceRoot !== workspaceRoot) {
|
|
19
|
+
throw new Error('New agent loop did not adopt the requested workspace root');
|
|
20
|
+
}
|
|
21
|
+
const paths = replacement.sandbox?.workspacePaths;
|
|
22
|
+
if (!replacement.sandbox?.grantAllAccess &&
|
|
23
|
+
(!Array.isArray(paths) || !paths.includes(workspaceRoot))) {
|
|
24
|
+
throw new Error('New agent sandbox did not adopt the requested workspace root');
|
|
25
|
+
}
|
|
26
|
+
replacement.waitForApproval = approvalHandler;
|
|
27
|
+
replacement.waitForDecision = decisionHandler;
|
|
28
|
+
if (prompt) {
|
|
29
|
+
prompt.setWorkingRoot(workspaceRoot);
|
|
30
|
+
prompt.messageActionLoop = replacement;
|
|
31
|
+
// A workspace switch is also a change of task context. Do not transfer
|
|
32
|
+
// queued attachments or active skills from the previous workspace.
|
|
33
|
+
prompt.pendingAttachments = [];
|
|
34
|
+
prompt.completion = null;
|
|
35
|
+
if (typeof prompt.scheduleDraw === 'function')
|
|
36
|
+
prompt.scheduleDraw();
|
|
37
|
+
}
|
|
38
|
+
if (headerInfo) {
|
|
39
|
+
headerInfo.cwd = workspaceRoot;
|
|
40
|
+
headerInfo.workspace = replacement.sandbox?.grantAllAccess
|
|
41
|
+
? 'ALL ACCESS'
|
|
42
|
+
: replacement.sandbox?.workspacePaths?.join(', ') ?? '';
|
|
43
|
+
if (renderer?.status?.setSession)
|
|
44
|
+
renderer.status.setSession(headerInfo);
|
|
45
|
+
if (surface?.setSessionInfo)
|
|
46
|
+
surface.setSessionInfo({
|
|
47
|
+
...headerInfo,
|
|
48
|
+
activeSkill: null
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return replacement;
|
|
52
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export interface SwitchChatWorkspaceOptions<TLoop = any> {
|
|
2
|
+
workspaceRoot: string;
|
|
3
|
+
createLoop: (workspaceRoot: string) => TLoop;
|
|
4
|
+
prompt?: any;
|
|
5
|
+
surface?: any;
|
|
6
|
+
renderer?: any;
|
|
7
|
+
headerInfo?: any;
|
|
8
|
+
approvalHandler?: any;
|
|
9
|
+
decisionHandler?: any;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Rebind a chat session to a different workspace without mutating the previous
|
|
14
|
+
* agent's sandbox or mixing old workspace memory into the new session.
|
|
15
|
+
*
|
|
16
|
+
* This module owns no disk changes or CLI command parsing. createLoop() is the
|
|
17
|
+
* existing AgentLoop constructor, injected by cliMode for deterministic tests.
|
|
18
|
+
*/
|
|
19
|
+
export function switchChatWorkspace<TLoop extends {
|
|
20
|
+
workspaceRoot?: string;
|
|
21
|
+
sandbox?: { grantAllAccess?: boolean; workspacePaths?: string[] };
|
|
22
|
+
waitForApproval?: any;
|
|
23
|
+
waitForDecision?: any;
|
|
24
|
+
} = any>({
|
|
25
|
+
workspaceRoot,
|
|
26
|
+
createLoop,
|
|
27
|
+
prompt = null,
|
|
28
|
+
surface = null,
|
|
29
|
+
renderer = null,
|
|
30
|
+
headerInfo = null,
|
|
31
|
+
approvalHandler,
|
|
32
|
+
decisionHandler
|
|
33
|
+
}: SwitchChatWorkspaceOptions<TLoop>): TLoop {
|
|
34
|
+
if (typeof workspaceRoot !== 'string' || !workspaceRoot) {
|
|
35
|
+
throw new TypeError('A nonempty workspace root is required');
|
|
36
|
+
}
|
|
37
|
+
if (typeof createLoop !== 'function') {
|
|
38
|
+
throw new TypeError('createLoop must construct a new AgentLoop');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Build the replacement before updating any displayed state. If construction
|
|
42
|
+
// fails, the previous loop and prompt remain intact for caller rollback.
|
|
43
|
+
const replacement = createLoop(workspaceRoot);
|
|
44
|
+
if (!replacement || replacement.workspaceRoot !== workspaceRoot) {
|
|
45
|
+
throw new Error('New agent loop did not adopt the requested workspace root');
|
|
46
|
+
}
|
|
47
|
+
const paths = replacement.sandbox?.workspacePaths;
|
|
48
|
+
if (!replacement.sandbox?.grantAllAccess &&
|
|
49
|
+
(!Array.isArray(paths) || !paths.includes(workspaceRoot))) {
|
|
50
|
+
throw new Error('New agent sandbox did not adopt the requested workspace root');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
replacement.waitForApproval = approvalHandler;
|
|
54
|
+
replacement.waitForDecision = decisionHandler;
|
|
55
|
+
|
|
56
|
+
if (prompt) {
|
|
57
|
+
prompt.setWorkingRoot(workspaceRoot);
|
|
58
|
+
prompt.messageActionLoop = replacement;
|
|
59
|
+
// A workspace switch is also a change of task context. Do not transfer
|
|
60
|
+
// queued attachments or active skills from the previous workspace.
|
|
61
|
+
prompt.pendingAttachments = [];
|
|
62
|
+
prompt.completion = null;
|
|
63
|
+
if (typeof prompt.scheduleDraw === 'function') prompt.scheduleDraw();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (headerInfo) {
|
|
67
|
+
headerInfo.cwd = workspaceRoot;
|
|
68
|
+
headerInfo.workspace = replacement.sandbox?.grantAllAccess
|
|
69
|
+
? 'ALL ACCESS'
|
|
70
|
+
: replacement.sandbox?.workspacePaths?.join(', ') ?? '';
|
|
71
|
+
if (renderer?.status?.setSession) renderer.status.setSession(headerInfo);
|
|
72
|
+
if (surface?.setSessionInfo) surface.setSessionInfo({
|
|
73
|
+
...headerInfo,
|
|
74
|
+
activeSkill: null
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return replacement;
|
|
79
|
+
}
|